check.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/check/check.h"
  5. #include "common/check.h"
  6. #include "toolchain/base/pretty_stack_trace_function.h"
  7. #include "toolchain/base/value_store.h"
  8. #include "toolchain/check/context.h"
  9. #include "toolchain/diagnostics/diagnostic_emitter.h"
  10. #include "toolchain/parse/tree.h"
  11. #include "toolchain/parse/tree_node_location_translator.h"
  12. #include "toolchain/sem_ir/file.h"
  13. namespace Carbon::Check {
  14. struct UnitInfo {
  15. explicit UnitInfo(Unit& unit)
  16. : unit(&unit),
  17. translator(unit.tokens, unit.tokens->filename(), unit.parse_tree),
  18. err_tracker(*unit.consumer),
  19. emitter(translator, err_tracker) {}
  20. Unit* unit;
  21. // Emitter information.
  22. Parse::NodeLocationTranslator translator;
  23. ErrorTrackingDiagnosticConsumer err_tracker;
  24. DiagnosticEmitter<Parse::Node> emitter;
  25. // A list of outgoing imports.
  26. llvm::SmallVector<std::pair<Parse::Node, UnitInfo*>> imports;
  27. // The remaining number of imports which must be checked before this unit can
  28. // be processed.
  29. int32_t imports_remaining = 0;
  30. // A list of incoming imports. This will be empty for `impl` files, because
  31. // imports only touch `api` files.
  32. llvm::SmallVector<UnitInfo*> incoming_imports;
  33. };
  34. // Produces and checks the IR for the provided Parse::Tree.
  35. // TODO: Both valid and invalid imports should be recorded on the SemIR. Invalid
  36. // imports should suppress errors where it makes sense.
  37. static auto CheckParseTree(const SemIR::File& builtin_ir, UnitInfo& unit_info,
  38. llvm::raw_ostream* vlog_stream) -> void {
  39. unit_info.unit->sem_ir->emplace(*unit_info.unit->value_stores,
  40. unit_info.unit->tokens->filename().str(),
  41. &builtin_ir);
  42. // For ease-of-access.
  43. SemIR::File& sem_ir = **unit_info.unit->sem_ir;
  44. const Parse::Tree& parse_tree = *unit_info.unit->parse_tree;
  45. Check::Context context(*unit_info.unit->tokens, unit_info.emitter, parse_tree,
  46. sem_ir, vlog_stream);
  47. PrettyStackTraceFunction context_dumper(
  48. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  49. // Add a block for the Parse::Tree.
  50. context.inst_block_stack().Push();
  51. context.PushScope();
  52. // Loops over all nodes in the tree. On some errors, this may return early,
  53. // for example if an unrecoverable state is encountered.
  54. for (auto parse_node : parse_tree.postorder()) {
  55. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  56. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  57. switch (auto parse_kind = parse_tree.node_kind(parse_node)) {
  58. #define CARBON_PARSE_NODE_KIND(Name) \
  59. case Parse::NodeKind::Name: { \
  60. if (!Check::Handle##Name(context, parse_node)) { \
  61. CARBON_CHECK(unit_info.err_tracker.seen_error()) \
  62. << "Handle" #Name " returned false without printing a diagnostic"; \
  63. sem_ir.set_has_errors(true); \
  64. return; \
  65. } \
  66. break; \
  67. }
  68. #include "toolchain/parse/node_kind.def"
  69. }
  70. }
  71. // Pop information for the file-level scope.
  72. sem_ir.set_top_inst_block_id(context.inst_block_stack().Pop());
  73. context.PopScope();
  74. context.VerifyOnFinish();
  75. sem_ir.set_has_errors(unit_info.err_tracker.seen_error());
  76. #ifndef NDEBUG
  77. if (auto verify = sem_ir.Verify(); !verify.ok()) {
  78. CARBON_FATAL() << sem_ir << "Built invalid semantics IR: " << verify.error()
  79. << "\n";
  80. }
  81. #endif
  82. }
  83. // The package and library names, used as map keys.
  84. using ImportKey = std::pair<llvm::StringRef, llvm::StringRef>;
  85. // Returns a key form of the package object. file_package_id is only used for
  86. // imports, not the main package directive; as a consequence, it will be invalid
  87. // for the main package directive.
  88. static auto GetImportKey(UnitInfo& unit_info, IdentifierId file_package_id,
  89. Parse::Tree::PackagingNames names) -> ImportKey {
  90. auto* stores = unit_info.unit->value_stores;
  91. llvm::StringRef package_name =
  92. names.package_id.is_valid() ? stores->identifiers().Get(names.package_id)
  93. : file_package_id.is_valid() ? stores->identifiers().Get(file_package_id)
  94. : "";
  95. llvm::StringRef library_name =
  96. names.library_id.is_valid()
  97. ? stores->string_literals().Get(names.library_id)
  98. : "";
  99. return {package_name, library_name};
  100. }
  101. static constexpr llvm::StringLiteral ExplicitMainName = "Main";
  102. // Marks an import as required on both the source and target file.
  103. //
  104. // The ID comparisons between the import and unit are okay because they both
  105. // come from the same file.
  106. static auto TrackImport(
  107. llvm::DenseMap<ImportKey, UnitInfo*>& api_map,
  108. llvm::DenseMap<ImportKey, Parse::Node>* explicit_import_map,
  109. UnitInfo& unit_info, Parse::Tree::PackagingNames import) -> void {
  110. const auto& packaging = unit_info.unit->parse_tree->packaging_directive();
  111. IdentifierId file_package_id =
  112. packaging ? packaging->names.package_id : IdentifierId::Invalid;
  113. auto import_key = GetImportKey(unit_info, file_package_id, import);
  114. // True if the import has `Main` as the package name, even if it comes from
  115. // the file's packaging (diagnostics may differentiate).
  116. bool is_explicit_main = import_key.first == ExplicitMainName;
  117. // Explicit imports need more validation than implicit ones. We try to do
  118. // these in an order of imports that should be removed, followed by imports
  119. // that might be valid with syntax fixes.
  120. if (explicit_import_map) {
  121. // Diagnose redundant imports.
  122. if (auto [insert_it, success] =
  123. explicit_import_map->insert({import_key, import.node});
  124. !success) {
  125. CARBON_DIAGNOSTIC(RepeatedImport, Error,
  126. "Library imported more than once.");
  127. CARBON_DIAGNOSTIC(FirstImported, Note, "First import here.");
  128. unit_info.emitter.Build(import.node, RepeatedImport)
  129. .Note(insert_it->second, FirstImported)
  130. .Emit();
  131. return;
  132. }
  133. // True if the file's package is implicitly `Main` (by omitting an explicit
  134. // package name).
  135. bool is_file_implicit_main =
  136. !packaging || !packaging->names.package_id.is_valid();
  137. // True if the import is using implicit "current package" syntax (by
  138. // omitting an explicit package name).
  139. bool is_import_implicit_current_package = !import.package_id.is_valid();
  140. // True if the import is using `default` library syntax.
  141. bool is_import_default_library = !import.library_id.is_valid();
  142. // True if the import and file point at the same package, even by
  143. // incorrectly specifying the current package name to `import`.
  144. bool is_same_package = is_import_implicit_current_package ||
  145. import.package_id == file_package_id;
  146. // True if the import points at the same library as the file's library.
  147. bool is_same_library =
  148. is_same_package &&
  149. (packaging ? import.library_id == packaging->names.library_id
  150. : is_import_default_library);
  151. // Diagnose explicit imports of the same library, whether from `api` or
  152. // `impl`.
  153. if (is_same_library) {
  154. CARBON_DIAGNOSTIC(ExplicitImportApi, Error,
  155. "Explicit import of `api` from `impl` file is "
  156. "redundant with implicit import.");
  157. CARBON_DIAGNOSTIC(ImportSelf, Error, "File cannot import itself.");
  158. bool is_impl =
  159. !packaging || packaging->api_or_impl == Parse::Tree::ApiOrImpl::Impl;
  160. unit_info.emitter.Emit(import.node,
  161. is_impl ? ExplicitImportApi : ImportSelf);
  162. return;
  163. }
  164. // Diagnose explicit imports of `Main//default`. There is no `api` for it.
  165. // This lets other diagnostics handle explicit `Main` package naming.
  166. if (is_file_implicit_main && is_import_implicit_current_package &&
  167. is_import_default_library) {
  168. CARBON_DIAGNOSTIC(ImportMainDefaultLibrary, Error,
  169. "Cannot import `Main//default`.");
  170. unit_info.emitter.Emit(import.node, ImportMainDefaultLibrary);
  171. return;
  172. }
  173. if (!is_import_implicit_current_package) {
  174. // Diagnose explicit imports of the same package that use the package
  175. // name.
  176. if (is_same_package || (is_file_implicit_main && is_explicit_main)) {
  177. CARBON_DIAGNOSTIC(
  178. ImportCurrentPackageByName, Error,
  179. "Imports from the current package must omit the package name.");
  180. unit_info.emitter.Emit(import.node, ImportCurrentPackageByName);
  181. return;
  182. }
  183. // Diagnose explicit imports from `Main`.
  184. if (is_explicit_main) {
  185. CARBON_DIAGNOSTIC(ImportMainPackage, Error,
  186. "Cannot import `Main` from other packages.");
  187. unit_info.emitter.Emit(import.node, ImportMainPackage);
  188. return;
  189. }
  190. }
  191. } else if (is_explicit_main) {
  192. // An implicit import with an explicit `Main` occurs when a `package` rule
  193. // has bad syntax, which will have been diagnosed when building the API map.
  194. // As a consequence, we return silently.
  195. return;
  196. }
  197. if (auto api = api_map.find(import_key); api != api_map.end()) {
  198. unit_info.imports.push_back({import.node, api->second});
  199. ++unit_info.imports_remaining;
  200. api->second->incoming_imports.push_back(&unit_info);
  201. } else {
  202. CARBON_DIAGNOSTIC(LibraryApiNotFound, Error,
  203. "Corresponding API not found.");
  204. CARBON_DIAGNOSTIC(ImportNotFound, Error, "Imported API not found.");
  205. unit_info.emitter.Emit(
  206. import.node, explicit_import_map ? ImportNotFound : LibraryApiNotFound);
  207. }
  208. }
  209. auto CheckParseTrees(const SemIR::File& builtin_ir,
  210. llvm::MutableArrayRef<Unit> units,
  211. llvm::raw_ostream* vlog_stream) -> void {
  212. // Prepare diagnostic emitters in case we run into issues during package
  213. // checking.
  214. //
  215. // UnitInfo is big due to its SmallVectors, so we default to 0 on the stack.
  216. llvm::SmallVector<UnitInfo, 0> unit_infos;
  217. unit_infos.reserve(units.size());
  218. for (auto& unit : units) {
  219. unit_infos.emplace_back(unit);
  220. }
  221. // Create a map of APIs which might be imported.
  222. llvm::DenseMap<ImportKey, UnitInfo*> api_map;
  223. for (auto& unit_info : unit_infos) {
  224. // TODO: It may be good to validate filenames here, but that would have use
  225. // put .impl.carbon on almost all tests (which are in `Main//default`). We
  226. // should probably get leads direction on filenames before enforcing.
  227. const auto& packaging = unit_info.unit->parse_tree->packaging_directive();
  228. // An import key formed from the `package` or `library` directive. Or, for
  229. // Main//default, a placeholder key.
  230. auto import_key = packaging ? GetImportKey(unit_info, IdentifierId::Invalid,
  231. packaging->names)
  232. // Construct a boring key for Main//default.
  233. : ImportKey{"", ""};
  234. // Diagnose explicit `Main` uses before they become marked as possible
  235. // APIs.
  236. if (import_key.first == ExplicitMainName) {
  237. CARBON_DIAGNOSTIC(ExplicitMainPackage, Error,
  238. "`Main//default` must omit `package` directive.");
  239. CARBON_DIAGNOSTIC(ExplicitMainLibrary, Error,
  240. "Use `library` directive in `Main` package libraries.");
  241. unit_info.emitter.Emit(packaging->names.node, import_key.second.empty()
  242. ? ExplicitMainPackage
  243. : ExplicitMainLibrary);
  244. continue;
  245. }
  246. if (packaging && packaging->api_or_impl == Parse::Tree::ApiOrImpl::Impl) {
  247. continue;
  248. }
  249. auto [entry, success] = api_map.insert({import_key, &unit_info});
  250. if (!success) {
  251. llvm::StringRef prev_filename = entry->second->unit->tokens->filename();
  252. if (packaging) {
  253. CARBON_DIAGNOSTIC(DuplicateLibraryApi, Error,
  254. "Library's API previously provided by `{0}`.",
  255. llvm::StringRef);
  256. unit_info.emitter.Emit(packaging->names.node, DuplicateLibraryApi,
  257. prev_filename);
  258. } else {
  259. CARBON_DIAGNOSTIC(DuplicateMainApi, Error,
  260. "Main//default previously provided by `{0}`.",
  261. llvm::StringRef);
  262. // Use the invalid node because there's no node to associate with.
  263. unit_info.emitter.Emit(Parse::Node::Invalid, DuplicateMainApi,
  264. prev_filename);
  265. }
  266. }
  267. }
  268. // Mark down imports for all files.
  269. llvm::SmallVector<UnitInfo*> ready_to_check;
  270. ready_to_check.reserve(units.size());
  271. for (auto& unit_info : unit_infos) {
  272. if (const auto& packaging =
  273. unit_info.unit->parse_tree->packaging_directive()) {
  274. if (packaging->api_or_impl == Parse::Tree::ApiOrImpl::Impl) {
  275. // An `impl` has an implicit import of its `api`.
  276. TrackImport(api_map, nullptr, unit_info, packaging->names);
  277. }
  278. }
  279. llvm::DenseMap<ImportKey, Parse::Node> explicit_import_map;
  280. for (const auto& import : unit_info.unit->parse_tree->imports()) {
  281. TrackImport(api_map, &explicit_import_map, unit_info, import);
  282. }
  283. // If there were no imports, mark the file as ready to check for below.
  284. if (unit_info.imports_remaining == 0) {
  285. ready_to_check.push_back(&unit_info);
  286. }
  287. }
  288. // Check everything with no dependencies. Earlier entries with dependencies
  289. // will be checked as soon as all their dependencies have been checked.
  290. for (int check_index = 0;
  291. check_index < static_cast<int>(ready_to_check.size()); ++check_index) {
  292. auto* unit_info = ready_to_check[check_index];
  293. CheckParseTree(builtin_ir, *unit_info, vlog_stream);
  294. for (auto* incoming_import : unit_info->incoming_imports) {
  295. --incoming_import->imports_remaining;
  296. if (incoming_import->imports_remaining == 0) {
  297. ready_to_check.push_back(incoming_import);
  298. }
  299. }
  300. }
  301. // If there are still units with remaining imports, it means there's a
  302. // dependency loop.
  303. if (ready_to_check.size() < unit_infos.size()) {
  304. // Go through units and mask out unevaluated imports. This breaks everything
  305. // associated with a loop equivalently, whether it's part of it or depending
  306. // on a part of it.
  307. // TODO: Better identify cycles, maybe try to untangle them.
  308. for (auto& unit_info : unit_infos) {
  309. if (unit_info.imports_remaining > 0) {
  310. for (auto* import_it = unit_info.imports.begin();
  311. import_it != unit_info.imports.end();) {
  312. auto* import_unit = import_it->second->unit;
  313. if (*import_unit->sem_ir) {
  314. ++import_it;
  315. } else {
  316. CARBON_DIAGNOSTIC(ImportCycleDetected, Error,
  317. "Import cannot be used due to a cycle. Cycle "
  318. "must be fixed to import.");
  319. unit_info.emitter.Emit(import_it->first, ImportCycleDetected);
  320. import_it = unit_info.imports.erase(import_it);
  321. }
  322. }
  323. }
  324. }
  325. // Check the remaining file contents, which are probably broken due to
  326. // incomplete imports.
  327. for (auto& unit_info : unit_infos) {
  328. if (unit_info.imports_remaining > 0) {
  329. CheckParseTree(builtin_ir, unit_info, vlog_stream);
  330. }
  331. }
  332. }
  333. }
  334. } // namespace Carbon::Check