check.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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/check/context.h"
  8. #include "toolchain/check/import.h"
  9. #include "toolchain/diagnostics/diagnostic_emitter.h"
  10. #include "toolchain/lex/token_kind.h"
  11. #include "toolchain/parse/node_ids.h"
  12. #include "toolchain/parse/tree.h"
  13. #include "toolchain/parse/tree_node_location_translator.h"
  14. #include "toolchain/sem_ir/file.h"
  15. #include "toolchain/sem_ir/ids.h"
  16. #include "toolchain/sem_ir/typed_insts.h"
  17. #include "toolchain/sem_ir/value_stores.h"
  18. namespace Carbon::Check {
  19. // Parse node handlers. Returns false for unrecoverable errors.
  20. #define CARBON_PARSE_NODE_KIND(Name) \
  21. auto Handle##Name(Context& context, Parse::Name##Id parse_node) -> bool;
  22. #include "toolchain/parse/node_kind.def"
  23. // Handles the transformation of a SemIRLocation to a DiagnosticLocation.
  24. class SemIRLocationTranslator
  25. : public DiagnosticLocationTranslator<SemIRLocation> {
  26. public:
  27. explicit SemIRLocationTranslator(
  28. const llvm::DenseMap<const SemIR::File*, Parse::NodeLocationTranslator*>*
  29. node_translators,
  30. const SemIR::File* sem_ir)
  31. : node_translators_(node_translators), sem_ir_(sem_ir) {}
  32. auto GetLocation(SemIRLocation loc) -> DiagnosticLocation override {
  33. // Parse nodes always refer to the current IR.
  34. if (!loc.is_inst_id) {
  35. return GetLocationInFile(sem_ir_, loc.node_location);
  36. }
  37. const auto* cursor_ir = sem_ir_;
  38. auto cursor_inst_id = loc.inst_id;
  39. while (true) {
  40. // If the parse node is valid, use it for the location.
  41. if (auto parse_node = cursor_ir->insts().GetParseNode(cursor_inst_id);
  42. parse_node.is_valid()) {
  43. return GetLocationInFile(cursor_ir, parse_node);
  44. }
  45. // If the parse node was invalid, recurse through import references when
  46. // possible.
  47. if (auto import_ref = cursor_ir->insts().TryGetAs<SemIR::AnyImportRef>(
  48. cursor_inst_id)) {
  49. cursor_ir = cursor_ir->import_irs().Get(import_ref->ir_id);
  50. cursor_inst_id = import_ref->inst_id;
  51. continue;
  52. }
  53. // If a namespace has an instruction for an import, switch to looking at
  54. // it.
  55. if (auto ns =
  56. cursor_ir->insts().TryGetAs<SemIR::Namespace>(cursor_inst_id)) {
  57. if (ns->import_id.is_valid()) {
  58. cursor_inst_id = ns->import_id;
  59. continue;
  60. }
  61. }
  62. // Invalid parse node but not an import; just nothing to point at.
  63. return GetLocationInFile(cursor_ir, Parse::NodeId::Invalid);
  64. }
  65. }
  66. private:
  67. auto GetLocationInFile(const SemIR::File* sem_ir,
  68. Parse::NodeLocation node_location) const
  69. -> DiagnosticLocation {
  70. auto it = node_translators_->find(sem_ir);
  71. CARBON_CHECK(it != node_translators_->end());
  72. return it->second->GetLocation(node_location);
  73. }
  74. const llvm::DenseMap<const SemIR::File*, Parse::NodeLocationTranslator*>*
  75. node_translators_;
  76. const SemIR::File* sem_ir_;
  77. };
  78. struct UnitInfo {
  79. // A given import within the file, with its destination.
  80. struct Import {
  81. Parse::Tree::PackagingNames names;
  82. UnitInfo* unit_info;
  83. };
  84. // A file's imports corresponding to a single package, for the map.
  85. struct PackageImports {
  86. // Use the constructor so that the SmallVector is only constructed
  87. // as-needed.
  88. explicit PackageImports(Parse::NodeId node) : node(node) {}
  89. // The first `import` directive in the file, which declared the package's
  90. // identifier (even if the import failed). Used for associating diagnostics
  91. // not specific to a single import.
  92. Parse::NodeId node;
  93. // Whether there's an import that failed to load.
  94. bool has_load_error = false;
  95. // The list of valid imports.
  96. llvm::SmallVector<Import> imports;
  97. };
  98. explicit UnitInfo(Unit& unit)
  99. : unit(&unit),
  100. translator(unit.tokens, unit.tokens->source().filename(),
  101. unit.parse_tree),
  102. err_tracker(*unit.consumer),
  103. emitter(translator, err_tracker) {}
  104. Unit* unit;
  105. // Emitter information.
  106. Parse::NodeLocationTranslator translator;
  107. ErrorTrackingDiagnosticConsumer err_tracker;
  108. DiagnosticEmitter<Parse::NodeLocation> emitter;
  109. // A map of package names to outgoing imports. If the
  110. // import's target isn't available, the unit will be nullptr to assist with
  111. // name lookup. Invalid imports (for example, `import Main;`) aren't added
  112. // because they won't add identifiers to name lookup.
  113. llvm::DenseMap<IdentifierId, PackageImports> package_imports_map;
  114. // The remaining number of imports which must be checked before this unit can
  115. // be processed.
  116. int32_t imports_remaining = 0;
  117. // A list of incoming imports. This will be empty for `impl` files, because
  118. // imports only touch `api` files.
  119. llvm::SmallVector<UnitInfo*> incoming_imports;
  120. };
  121. // Add imports to the root block.
  122. static auto InitPackageScopeAndImports(Context& context, UnitInfo& unit_info)
  123. -> void {
  124. // Importing makes many namespaces, so only canonicalize the type once.
  125. auto namespace_type_id =
  126. context.GetBuiltinType(SemIR::BuiltinKind::NamespaceType);
  127. // Define the package scope, with an instruction for `package` expressions to
  128. // reference.
  129. auto package_scope_id = context.name_scopes().Add(
  130. SemIR::InstId::PackageNamespace, SemIR::NameId::PackageNamespace,
  131. SemIR::NameScopeId::Invalid);
  132. CARBON_CHECK(package_scope_id == SemIR::NameScopeId::Package);
  133. auto package_inst_id = context.AddInst(
  134. {Parse::NodeId::Invalid,
  135. SemIR::Namespace{namespace_type_id, SemIR::NameScopeId::Package,
  136. SemIR::InstId::Invalid}});
  137. CARBON_CHECK(package_inst_id == SemIR::InstId::PackageNamespace);
  138. // Add imports from the current package.
  139. auto self_import = unit_info.package_imports_map.find(IdentifierId::Invalid);
  140. if (self_import != unit_info.package_imports_map.end()) {
  141. bool error_in_import = self_import->second.has_load_error;
  142. for (const auto& import : self_import->second.imports) {
  143. const auto& import_sem_ir = **import.unit_info->unit->sem_ir;
  144. Import(context, namespace_type_id, import_sem_ir);
  145. error_in_import = error_in_import || import_sem_ir.name_scopes()
  146. .Get(SemIR::NameScopeId::Package)
  147. .has_error;
  148. }
  149. // If an import of the current package caused an error for the imported
  150. // file, it transitively affects the current file too.
  151. if (error_in_import) {
  152. context.name_scopes().Get(SemIR::NameScopeId::Package).has_error = true;
  153. }
  154. context.scope_stack().Push(package_inst_id, SemIR::NameScopeId::Package,
  155. error_in_import);
  156. } else {
  157. // Push the scope; there are no names to add.
  158. context.scope_stack().Push(package_inst_id, SemIR::NameScopeId::Package);
  159. }
  160. CARBON_CHECK(context.scope_stack().PeekIndex() == ScopeIndex::Package);
  161. for (auto& [package_id, package_imports] : unit_info.package_imports_map) {
  162. if (!package_id.is_valid()) {
  163. // Current package is handled above.
  164. continue;
  165. }
  166. llvm::SmallVector<const SemIR::File*> sem_irs;
  167. for (auto import : package_imports.imports) {
  168. sem_irs.push_back(&**import.unit_info->unit->sem_ir);
  169. }
  170. context.AddPackageImports(package_imports.node, package_id, sem_irs,
  171. package_imports.has_load_error);
  172. }
  173. context.import_ir_constant_values().resize(
  174. context.import_irs().size(),
  175. SemIR::ConstantValueStore(SemIR::ConstantId::Invalid));
  176. }
  177. // Loops over all nodes in the tree. On some errors, this may return early,
  178. // for example if an unrecoverable state is encountered.
  179. // NOLINTNEXTLINE(readability-function-size)
  180. static auto ProcessParseNodes(Context& context,
  181. ErrorTrackingDiagnosticConsumer& err_tracker)
  182. -> bool {
  183. for (auto parse_node : context.parse_tree().postorder()) {
  184. switch (auto parse_kind = context.parse_tree().node_kind(parse_node)) {
  185. #define CARBON_PARSE_NODE_KIND(Name) \
  186. case Parse::NodeKind::Name: { \
  187. if (!Check::Handle##Name(context, Parse::Name##Id(parse_node))) { \
  188. CARBON_CHECK(err_tracker.seen_error()) \
  189. << "Handle" #Name " returned false without printing a diagnostic"; \
  190. return false; \
  191. } \
  192. break; \
  193. }
  194. #include "toolchain/parse/node_kind.def"
  195. }
  196. }
  197. return true;
  198. }
  199. // Produces and checks the IR for the provided Parse::Tree.
  200. static auto CheckParseTree(
  201. llvm::DenseMap<const SemIR::File*, Parse::NodeLocationTranslator*>*
  202. node_translators,
  203. const SemIR::File& builtin_ir, UnitInfo& unit_info,
  204. llvm::raw_ostream* vlog_stream) -> void {
  205. unit_info.unit->sem_ir->emplace(
  206. *unit_info.unit->value_stores,
  207. unit_info.unit->tokens->source().filename().str(), &builtin_ir);
  208. // For ease-of-access.
  209. SemIR::File& sem_ir = **unit_info.unit->sem_ir;
  210. CARBON_CHECK(
  211. node_translators->insert({&sem_ir, &unit_info.translator}).second);
  212. SemIRLocationTranslator translator(node_translators, &sem_ir);
  213. Context::DiagnosticEmitter emitter(translator, unit_info.err_tracker);
  214. Context context(*unit_info.unit->tokens, emitter, *unit_info.unit->parse_tree,
  215. sem_ir, vlog_stream);
  216. PrettyStackTraceFunction context_dumper(
  217. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  218. // Add a block for the file.
  219. context.inst_block_stack().Push();
  220. InitPackageScopeAndImports(context, unit_info);
  221. if (!ProcessParseNodes(context, unit_info.err_tracker)) {
  222. context.sem_ir().set_has_errors(true);
  223. return;
  224. }
  225. // Pop information for the file-level scope.
  226. sem_ir.set_top_inst_block_id(context.inst_block_stack().Pop());
  227. context.scope_stack().Pop();
  228. context.FinalizeExports();
  229. context.FinalizeGlobalInit();
  230. context.VerifyOnFinish();
  231. sem_ir.set_has_errors(unit_info.err_tracker.seen_error());
  232. #ifndef NDEBUG
  233. if (auto verify = sem_ir.Verify(); !verify.ok()) {
  234. CARBON_FATAL() << sem_ir << "Built invalid semantics IR: " << verify.error()
  235. << "\n";
  236. }
  237. #endif
  238. }
  239. // The package and library names, used as map keys.
  240. using ImportKey = std::pair<llvm::StringRef, llvm::StringRef>;
  241. // Returns a key form of the package object. file_package_id is only used for
  242. // imports, not the main package directive; as a consequence, it will be invalid
  243. // for the main package directive.
  244. static auto GetImportKey(UnitInfo& unit_info, IdentifierId file_package_id,
  245. Parse::Tree::PackagingNames names) -> ImportKey {
  246. auto* stores = unit_info.unit->value_stores;
  247. llvm::StringRef package_name =
  248. names.package_id.is_valid() ? stores->identifiers().Get(names.package_id)
  249. : file_package_id.is_valid() ? stores->identifiers().Get(file_package_id)
  250. : "";
  251. llvm::StringRef library_name =
  252. names.library_id.is_valid()
  253. ? stores->string_literal_values().Get(names.library_id)
  254. : "";
  255. return {package_name, library_name};
  256. }
  257. static constexpr llvm::StringLiteral ExplicitMainName = "Main";
  258. // Marks an import as required on both the source and target file.
  259. //
  260. // The ID comparisons between the import and unit are okay because they both
  261. // come from the same file.
  262. static auto TrackImport(
  263. llvm::DenseMap<ImportKey, UnitInfo*>& api_map,
  264. llvm::DenseMap<ImportKey, Parse::NodeId>* explicit_import_map,
  265. UnitInfo& unit_info, Parse::Tree::PackagingNames import) -> void {
  266. const auto& packaging = unit_info.unit->parse_tree->packaging_directive();
  267. IdentifierId file_package_id =
  268. packaging ? packaging->names.package_id : IdentifierId::Invalid;
  269. auto import_key = GetImportKey(unit_info, file_package_id, import);
  270. // True if the import has `Main` as the package name, even if it comes from
  271. // the file's packaging (diagnostics may differentiate).
  272. bool is_explicit_main = import_key.first == ExplicitMainName;
  273. // Explicit imports need more validation than implicit ones. We try to do
  274. // these in an order of imports that should be removed, followed by imports
  275. // that might be valid with syntax fixes.
  276. if (explicit_import_map) {
  277. // Diagnose redundant imports.
  278. if (auto [insert_it, success] =
  279. explicit_import_map->insert({import_key, import.node});
  280. !success) {
  281. CARBON_DIAGNOSTIC(RepeatedImport, Error,
  282. "Library imported more than once.");
  283. CARBON_DIAGNOSTIC(FirstImported, Note, "First import here.");
  284. unit_info.emitter.Build(import.node, RepeatedImport)
  285. .Note(insert_it->second, FirstImported)
  286. .Emit();
  287. return;
  288. }
  289. // True if the file's package is implicitly `Main` (by omitting an explicit
  290. // package name).
  291. bool is_file_implicit_main =
  292. !packaging || !packaging->names.package_id.is_valid();
  293. // True if the import is using implicit "current package" syntax (by
  294. // omitting an explicit package name).
  295. bool is_import_implicit_current_package = !import.package_id.is_valid();
  296. // True if the import is using `default` library syntax.
  297. bool is_import_default_library = !import.library_id.is_valid();
  298. // True if the import and file point at the same package, even by
  299. // incorrectly specifying the current package name to `import`.
  300. bool is_same_package = is_import_implicit_current_package ||
  301. import.package_id == file_package_id;
  302. // True if the import points at the same library as the file's library.
  303. bool is_same_library =
  304. is_same_package &&
  305. (packaging ? import.library_id == packaging->names.library_id
  306. : is_import_default_library);
  307. // Diagnose explicit imports of the same library, whether from `api` or
  308. // `impl`.
  309. if (is_same_library) {
  310. CARBON_DIAGNOSTIC(ExplicitImportApi, Error,
  311. "Explicit import of `api` from `impl` file is "
  312. "redundant with implicit import.");
  313. CARBON_DIAGNOSTIC(ImportSelf, Error, "File cannot import itself.");
  314. bool is_impl =
  315. !packaging || packaging->api_or_impl == Parse::Tree::ApiOrImpl::Impl;
  316. unit_info.emitter.Emit(import.node,
  317. is_impl ? ExplicitImportApi : ImportSelf);
  318. return;
  319. }
  320. // Diagnose explicit imports of `Main//default`. There is no `api` for it.
  321. // This lets other diagnostics handle explicit `Main` package naming.
  322. if (is_file_implicit_main && is_import_implicit_current_package &&
  323. is_import_default_library) {
  324. CARBON_DIAGNOSTIC(ImportMainDefaultLibrary, Error,
  325. "Cannot import `Main//default`.");
  326. unit_info.emitter.Emit(import.node, ImportMainDefaultLibrary);
  327. return;
  328. }
  329. if (!is_import_implicit_current_package) {
  330. // Diagnose explicit imports of the same package that use the package
  331. // name.
  332. if (is_same_package || (is_file_implicit_main && is_explicit_main)) {
  333. CARBON_DIAGNOSTIC(
  334. ImportCurrentPackageByName, Error,
  335. "Imports from the current package must omit the package name.");
  336. unit_info.emitter.Emit(import.node, ImportCurrentPackageByName);
  337. return;
  338. }
  339. // Diagnose explicit imports from `Main`.
  340. if (is_explicit_main) {
  341. CARBON_DIAGNOSTIC(ImportMainPackage, Error,
  342. "Cannot import `Main` from other packages.");
  343. unit_info.emitter.Emit(import.node, ImportMainPackage);
  344. return;
  345. }
  346. }
  347. } else if (is_explicit_main) {
  348. // An implicit import with an explicit `Main` occurs when a `package` rule
  349. // has bad syntax, which will have been diagnosed when building the API map.
  350. // As a consequence, we return silently.
  351. return;
  352. }
  353. // Get the package imports.
  354. auto package_imports_it =
  355. unit_info.package_imports_map.try_emplace(import.package_id, import.node)
  356. .first;
  357. if (auto api = api_map.find(import_key); api != api_map.end()) {
  358. // Add references between the file and imported api.
  359. package_imports_it->second.imports.push_back({import, api->second});
  360. ++unit_info.imports_remaining;
  361. api->second->incoming_imports.push_back(&unit_info);
  362. } else {
  363. // The imported api is missing.
  364. package_imports_it->second.has_load_error = true;
  365. CARBON_DIAGNOSTIC(LibraryApiNotFound, Error,
  366. "Corresponding API not found.");
  367. CARBON_DIAGNOSTIC(ImportNotFound, Error, "Imported API not found.");
  368. unit_info.emitter.Emit(
  369. import.node, explicit_import_map ? ImportNotFound : LibraryApiNotFound);
  370. }
  371. }
  372. // Builds a map of `api` files which might be imported. Also diagnoses issues
  373. // related to the packaging because the strings are loaded as part of getting
  374. // the ImportKey (which we then do for `impl` files too).
  375. static auto BuildApiMapAndDiagnosePackaging(
  376. llvm::SmallVector<UnitInfo, 0>& unit_infos)
  377. -> llvm::DenseMap<ImportKey, UnitInfo*> {
  378. llvm::DenseMap<ImportKey, UnitInfo*> api_map;
  379. for (auto& unit_info : unit_infos) {
  380. const auto& packaging = unit_info.unit->parse_tree->packaging_directive();
  381. // An import key formed from the `package` or `library` directive. Or, for
  382. // Main//default, a placeholder key.
  383. auto import_key = packaging ? GetImportKey(unit_info, IdentifierId::Invalid,
  384. packaging->names)
  385. // Construct a boring key for Main//default.
  386. : ImportKey{"", ""};
  387. // Diagnose explicit `Main` uses before they become marked as possible
  388. // APIs.
  389. if (import_key.first == ExplicitMainName) {
  390. CARBON_DIAGNOSTIC(ExplicitMainPackage, Error,
  391. "`Main//default` must omit `package` directive.");
  392. CARBON_DIAGNOSTIC(ExplicitMainLibrary, Error,
  393. "Use `library` directive in `Main` package libraries.");
  394. unit_info.emitter.Emit(packaging->names.node, import_key.second.empty()
  395. ? ExplicitMainPackage
  396. : ExplicitMainLibrary);
  397. continue;
  398. }
  399. bool is_impl =
  400. packaging && packaging->api_or_impl == Parse::Tree::ApiOrImpl::Impl;
  401. // Add to the `api` map and diagnose duplicates. This occurs before the
  402. // file extension check because we might emit both diagnostics in situations
  403. // where the user forgets (or has syntax errors with) a package line
  404. // multiple times.
  405. if (!is_impl) {
  406. auto [entry, success] = api_map.insert({import_key, &unit_info});
  407. if (!success) {
  408. llvm::StringRef prev_filename =
  409. entry->second->unit->tokens->source().filename();
  410. if (packaging) {
  411. CARBON_DIAGNOSTIC(DuplicateLibraryApi, Error,
  412. "Library's API previously provided by `{0}`.",
  413. std::string);
  414. unit_info.emitter.Emit(packaging->names.node, DuplicateLibraryApi,
  415. prev_filename.str());
  416. } else {
  417. CARBON_DIAGNOSTIC(DuplicateMainApi, Error,
  418. "Main//default previously provided by `{0}`.",
  419. std::string);
  420. // Use the invalid node because there's no node to associate with.
  421. unit_info.emitter.Emit(Parse::NodeId::Invalid, DuplicateMainApi,
  422. prev_filename.str());
  423. }
  424. }
  425. }
  426. // Validate file extensions. Note imports rely the packaging directive, not
  427. // the extension. If the input is not a regular file, for example because it
  428. // is stdin, no filename checking is performed.
  429. if (unit_info.unit->tokens->source().is_regular_file()) {
  430. auto filename = unit_info.unit->tokens->source().filename();
  431. static constexpr llvm::StringLiteral ApiExt = ".carbon";
  432. static constexpr llvm::StringLiteral ImplExt = ".impl.carbon";
  433. bool is_api_with_impl_ext = !is_impl && filename.ends_with(ImplExt);
  434. auto want_ext = is_impl ? ImplExt : ApiExt;
  435. if (is_api_with_impl_ext || !filename.ends_with(want_ext)) {
  436. CARBON_DIAGNOSTIC(IncorrectExtension, Error,
  437. "File extension of `{0}` required for `{1}`.",
  438. llvm::StringLiteral, Lex::TokenKind);
  439. auto diag = unit_info.emitter.Build(
  440. packaging ? packaging->names.node : Parse::NodeId::Invalid,
  441. IncorrectExtension, want_ext,
  442. is_impl ? Lex::TokenKind::Impl : Lex::TokenKind::Api);
  443. if (is_api_with_impl_ext) {
  444. CARBON_DIAGNOSTIC(IncorrectExtensionImplNote, Note,
  445. "File extension of `{0}` only allowed for `{1}`.",
  446. llvm::StringLiteral, Lex::TokenKind);
  447. diag.Note(Parse::NodeId::Invalid, IncorrectExtensionImplNote, ImplExt,
  448. Lex::TokenKind::Impl);
  449. }
  450. diag.Emit();
  451. }
  452. }
  453. }
  454. return api_map;
  455. }
  456. auto CheckParseTrees(const SemIR::File& builtin_ir,
  457. llvm::MutableArrayRef<Unit> units,
  458. llvm::raw_ostream* vlog_stream) -> void {
  459. // Prepare diagnostic emitters in case we run into issues during package
  460. // checking.
  461. //
  462. // UnitInfo is big due to its SmallVectors, so we default to 0 on the stack.
  463. llvm::SmallVector<UnitInfo, 0> unit_infos;
  464. unit_infos.reserve(units.size());
  465. for (auto& unit : units) {
  466. unit_infos.emplace_back(unit);
  467. }
  468. llvm::DenseMap<ImportKey, UnitInfo*> api_map =
  469. BuildApiMapAndDiagnosePackaging(unit_infos);
  470. // Mark down imports for all files.
  471. llvm::SmallVector<UnitInfo*> ready_to_check;
  472. ready_to_check.reserve(units.size());
  473. for (auto& unit_info : unit_infos) {
  474. if (const auto& packaging =
  475. unit_info.unit->parse_tree->packaging_directive()) {
  476. if (packaging->api_or_impl == Parse::Tree::ApiOrImpl::Impl) {
  477. // An `impl` has an implicit import of its `api`.
  478. auto implicit_names = packaging->names;
  479. implicit_names.package_id = IdentifierId::Invalid;
  480. TrackImport(api_map, nullptr, unit_info, implicit_names);
  481. }
  482. }
  483. llvm::DenseMap<ImportKey, Parse::NodeId> explicit_import_map;
  484. for (const auto& import : unit_info.unit->parse_tree->imports()) {
  485. TrackImport(api_map, &explicit_import_map, unit_info, import);
  486. }
  487. // If there were no imports, mark the file as ready to check for below.
  488. if (unit_info.imports_remaining == 0) {
  489. ready_to_check.push_back(&unit_info);
  490. }
  491. }
  492. llvm::DenseMap<const SemIR::File*, Parse::NodeLocationTranslator*>
  493. node_translators;
  494. // Check everything with no dependencies. Earlier entries with dependencies
  495. // will be checked as soon as all their dependencies have been checked.
  496. for (int check_index = 0;
  497. check_index < static_cast<int>(ready_to_check.size()); ++check_index) {
  498. auto* unit_info = ready_to_check[check_index];
  499. CheckParseTree(&node_translators, builtin_ir, *unit_info, vlog_stream);
  500. for (auto* incoming_import : unit_info->incoming_imports) {
  501. --incoming_import->imports_remaining;
  502. if (incoming_import->imports_remaining == 0) {
  503. ready_to_check.push_back(incoming_import);
  504. }
  505. }
  506. }
  507. // If there are still units with remaining imports, it means there's a
  508. // dependency loop.
  509. if (ready_to_check.size() < unit_infos.size()) {
  510. // Go through units and mask out unevaluated imports. This breaks everything
  511. // associated with a loop equivalently, whether it's part of it or depending
  512. // on a part of it.
  513. // TODO: Better identify cycles, maybe try to untangle them.
  514. for (auto& unit_info : unit_infos) {
  515. if (unit_info.imports_remaining > 0) {
  516. for (auto& [package_id, package_imports] :
  517. unit_info.package_imports_map) {
  518. for (auto* import_it = package_imports.imports.begin();
  519. import_it != package_imports.imports.end();) {
  520. if (*import_it->unit_info->unit->sem_ir) {
  521. // The import is checked, so continue.
  522. ++import_it;
  523. } else {
  524. // The import hasn't been checked, indicating a cycle.
  525. CARBON_DIAGNOSTIC(ImportCycleDetected, Error,
  526. "Import cannot be used due to a cycle. Cycle "
  527. "must be fixed to import.");
  528. unit_info.emitter.Emit(import_it->names.node,
  529. ImportCycleDetected);
  530. // Make this look the same as an import which wasn't found.
  531. package_imports.has_load_error = true;
  532. import_it = package_imports.imports.erase(import_it);
  533. }
  534. }
  535. }
  536. }
  537. }
  538. // Check the remaining file contents, which are probably broken due to
  539. // incomplete imports.
  540. for (auto& unit_info : unit_infos) {
  541. if (unit_info.imports_remaining > 0) {
  542. CheckParseTree(&node_translators, builtin_ir, unit_info, vlog_stream);
  543. }
  544. }
  545. }
  546. }
  547. } // namespace Carbon::Check