check.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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/inst.h"
  17. #include "toolchain/sem_ir/typed_insts.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->cross_ref_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.PushScope(package_inst_id, SemIR::NameScopeId::Package,
  155. error_in_import);
  156. } else {
  157. // Push the scope; there are no names to add.
  158. context.PushScope(package_inst_id, SemIR::NameScopeId::Package);
  159. }
  160. CARBON_CHECK(context.current_scope_index() == 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. }
  174. // Loops over all nodes in the tree. On some errors, this may return early,
  175. // for example if an unrecoverable state is encountered.
  176. // NOLINTNEXTLINE(readability-function-size)
  177. static auto ProcessParseNodes(Context& context,
  178. ErrorTrackingDiagnosticConsumer& err_tracker)
  179. -> bool {
  180. for (auto parse_node : context.parse_tree().postorder()) {
  181. switch (auto parse_kind = context.parse_tree().node_kind(parse_node)) {
  182. #define CARBON_PARSE_NODE_KIND(Name) \
  183. case Parse::NodeKind::Name: { \
  184. if (!Check::Handle##Name(context, Parse::Name##Id(parse_node))) { \
  185. CARBON_CHECK(err_tracker.seen_error()) \
  186. << "Handle" #Name " returned false without printing a diagnostic"; \
  187. return false; \
  188. } \
  189. break; \
  190. }
  191. #include "toolchain/parse/node_kind.def"
  192. }
  193. }
  194. return true;
  195. }
  196. // Produces and checks the IR for the provided Parse::Tree.
  197. static auto CheckParseTree(
  198. llvm::DenseMap<const SemIR::File*, Parse::NodeLocationTranslator*>*
  199. node_translators,
  200. const SemIR::File& builtin_ir, UnitInfo& unit_info,
  201. llvm::raw_ostream* vlog_stream) -> void {
  202. unit_info.unit->sem_ir->emplace(
  203. *unit_info.unit->value_stores,
  204. unit_info.unit->tokens->source().filename().str(), &builtin_ir);
  205. // For ease-of-access.
  206. SemIR::File& sem_ir = **unit_info.unit->sem_ir;
  207. CARBON_CHECK(
  208. node_translators->insert({&sem_ir, &unit_info.translator}).second);
  209. SemIRLocationTranslator translator(node_translators, &sem_ir);
  210. Context::DiagnosticEmitter emitter(translator, unit_info.err_tracker);
  211. Context context(*unit_info.unit->tokens, emitter, *unit_info.unit->parse_tree,
  212. sem_ir, vlog_stream);
  213. PrettyStackTraceFunction context_dumper(
  214. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  215. // Add a block for the file.
  216. context.inst_block_stack().Push();
  217. InitPackageScopeAndImports(context, unit_info);
  218. if (!ProcessParseNodes(context, unit_info.err_tracker)) {
  219. context.sem_ir().set_has_errors(true);
  220. return;
  221. }
  222. // Pop information for the file-level scope.
  223. sem_ir.set_top_inst_block_id(context.inst_block_stack().Pop());
  224. context.PopScope();
  225. context.FinalizeExports();
  226. context.VerifyOnFinish();
  227. sem_ir.set_has_errors(unit_info.err_tracker.seen_error());
  228. #ifndef NDEBUG
  229. if (auto verify = sem_ir.Verify(); !verify.ok()) {
  230. CARBON_FATAL() << sem_ir << "Built invalid semantics IR: " << verify.error()
  231. << "\n";
  232. }
  233. #endif
  234. }
  235. // The package and library names, used as map keys.
  236. using ImportKey = std::pair<llvm::StringRef, llvm::StringRef>;
  237. // Returns a key form of the package object. file_package_id is only used for
  238. // imports, not the main package directive; as a consequence, it will be invalid
  239. // for the main package directive.
  240. static auto GetImportKey(UnitInfo& unit_info, IdentifierId file_package_id,
  241. Parse::Tree::PackagingNames names) -> ImportKey {
  242. auto* stores = unit_info.unit->value_stores;
  243. llvm::StringRef package_name =
  244. names.package_id.is_valid() ? stores->identifiers().Get(names.package_id)
  245. : file_package_id.is_valid() ? stores->identifiers().Get(file_package_id)
  246. : "";
  247. llvm::StringRef library_name =
  248. names.library_id.is_valid()
  249. ? stores->string_literal_values().Get(names.library_id)
  250. : "";
  251. return {package_name, library_name};
  252. }
  253. static constexpr llvm::StringLiteral ExplicitMainName = "Main";
  254. // Marks an import as required on both the source and target file.
  255. //
  256. // The ID comparisons between the import and unit are okay because they both
  257. // come from the same file.
  258. static auto TrackImport(
  259. llvm::DenseMap<ImportKey, UnitInfo*>& api_map,
  260. llvm::DenseMap<ImportKey, Parse::NodeId>* explicit_import_map,
  261. UnitInfo& unit_info, Parse::Tree::PackagingNames import) -> void {
  262. const auto& packaging = unit_info.unit->parse_tree->packaging_directive();
  263. IdentifierId file_package_id =
  264. packaging ? packaging->names.package_id : IdentifierId::Invalid;
  265. auto import_key = GetImportKey(unit_info, file_package_id, import);
  266. // True if the import has `Main` as the package name, even if it comes from
  267. // the file's packaging (diagnostics may differentiate).
  268. bool is_explicit_main = import_key.first == ExplicitMainName;
  269. // Explicit imports need more validation than implicit ones. We try to do
  270. // these in an order of imports that should be removed, followed by imports
  271. // that might be valid with syntax fixes.
  272. if (explicit_import_map) {
  273. // Diagnose redundant imports.
  274. if (auto [insert_it, success] =
  275. explicit_import_map->insert({import_key, import.node});
  276. !success) {
  277. CARBON_DIAGNOSTIC(RepeatedImport, Error,
  278. "Library imported more than once.");
  279. CARBON_DIAGNOSTIC(FirstImported, Note, "First import here.");
  280. unit_info.emitter.Build(import.node, RepeatedImport)
  281. .Note(insert_it->second, FirstImported)
  282. .Emit();
  283. return;
  284. }
  285. // True if the file's package is implicitly `Main` (by omitting an explicit
  286. // package name).
  287. bool is_file_implicit_main =
  288. !packaging || !packaging->names.package_id.is_valid();
  289. // True if the import is using implicit "current package" syntax (by
  290. // omitting an explicit package name).
  291. bool is_import_implicit_current_package = !import.package_id.is_valid();
  292. // True if the import is using `default` library syntax.
  293. bool is_import_default_library = !import.library_id.is_valid();
  294. // True if the import and file point at the same package, even by
  295. // incorrectly specifying the current package name to `import`.
  296. bool is_same_package = is_import_implicit_current_package ||
  297. import.package_id == file_package_id;
  298. // True if the import points at the same library as the file's library.
  299. bool is_same_library =
  300. is_same_package &&
  301. (packaging ? import.library_id == packaging->names.library_id
  302. : is_import_default_library);
  303. // Diagnose explicit imports of the same library, whether from `api` or
  304. // `impl`.
  305. if (is_same_library) {
  306. CARBON_DIAGNOSTIC(ExplicitImportApi, Error,
  307. "Explicit import of `api` from `impl` file is "
  308. "redundant with implicit import.");
  309. CARBON_DIAGNOSTIC(ImportSelf, Error, "File cannot import itself.");
  310. bool is_impl =
  311. !packaging || packaging->api_or_impl == Parse::Tree::ApiOrImpl::Impl;
  312. unit_info.emitter.Emit(import.node,
  313. is_impl ? ExplicitImportApi : ImportSelf);
  314. return;
  315. }
  316. // Diagnose explicit imports of `Main//default`. There is no `api` for it.
  317. // This lets other diagnostics handle explicit `Main` package naming.
  318. if (is_file_implicit_main && is_import_implicit_current_package &&
  319. is_import_default_library) {
  320. CARBON_DIAGNOSTIC(ImportMainDefaultLibrary, Error,
  321. "Cannot import `Main//default`.");
  322. unit_info.emitter.Emit(import.node, ImportMainDefaultLibrary);
  323. return;
  324. }
  325. if (!is_import_implicit_current_package) {
  326. // Diagnose explicit imports of the same package that use the package
  327. // name.
  328. if (is_same_package || (is_file_implicit_main && is_explicit_main)) {
  329. CARBON_DIAGNOSTIC(
  330. ImportCurrentPackageByName, Error,
  331. "Imports from the current package must omit the package name.");
  332. unit_info.emitter.Emit(import.node, ImportCurrentPackageByName);
  333. return;
  334. }
  335. // Diagnose explicit imports from `Main`.
  336. if (is_explicit_main) {
  337. CARBON_DIAGNOSTIC(ImportMainPackage, Error,
  338. "Cannot import `Main` from other packages.");
  339. unit_info.emitter.Emit(import.node, ImportMainPackage);
  340. return;
  341. }
  342. }
  343. } else if (is_explicit_main) {
  344. // An implicit import with an explicit `Main` occurs when a `package` rule
  345. // has bad syntax, which will have been diagnosed when building the API map.
  346. // As a consequence, we return silently.
  347. return;
  348. }
  349. // Get the package imports.
  350. auto package_imports_it =
  351. unit_info.package_imports_map.try_emplace(import.package_id, import.node)
  352. .first;
  353. if (auto api = api_map.find(import_key); api != api_map.end()) {
  354. // Add references between the file and imported api.
  355. package_imports_it->second.imports.push_back({import, api->second});
  356. ++unit_info.imports_remaining;
  357. api->second->incoming_imports.push_back(&unit_info);
  358. } else {
  359. // The imported api is missing.
  360. package_imports_it->second.has_load_error = true;
  361. CARBON_DIAGNOSTIC(LibraryApiNotFound, Error,
  362. "Corresponding API not found.");
  363. CARBON_DIAGNOSTIC(ImportNotFound, Error, "Imported API not found.");
  364. unit_info.emitter.Emit(
  365. import.node, explicit_import_map ? ImportNotFound : LibraryApiNotFound);
  366. }
  367. }
  368. // Builds a map of `api` files which might be imported. Also diagnoses issues
  369. // related to the packaging because the strings are loaded as part of getting
  370. // the ImportKey (which we then do for `impl` files too).
  371. static auto BuildApiMapAndDiagnosePackaging(
  372. llvm::SmallVector<UnitInfo, 0>& unit_infos)
  373. -> llvm::DenseMap<ImportKey, UnitInfo*> {
  374. llvm::DenseMap<ImportKey, UnitInfo*> api_map;
  375. for (auto& unit_info : unit_infos) {
  376. const auto& packaging = unit_info.unit->parse_tree->packaging_directive();
  377. // An import key formed from the `package` or `library` directive. Or, for
  378. // Main//default, a placeholder key.
  379. auto import_key = packaging ? GetImportKey(unit_info, IdentifierId::Invalid,
  380. packaging->names)
  381. // Construct a boring key for Main//default.
  382. : ImportKey{"", ""};
  383. // Diagnose explicit `Main` uses before they become marked as possible
  384. // APIs.
  385. if (import_key.first == ExplicitMainName) {
  386. CARBON_DIAGNOSTIC(ExplicitMainPackage, Error,
  387. "`Main//default` must omit `package` directive.");
  388. CARBON_DIAGNOSTIC(ExplicitMainLibrary, Error,
  389. "Use `library` directive in `Main` package libraries.");
  390. unit_info.emitter.Emit(packaging->names.node, import_key.second.empty()
  391. ? ExplicitMainPackage
  392. : ExplicitMainLibrary);
  393. continue;
  394. }
  395. bool is_impl =
  396. packaging && packaging->api_or_impl == Parse::Tree::ApiOrImpl::Impl;
  397. // Add to the `api` map and diagnose duplicates. This occurs before the
  398. // file extension check because we might emit both diagnostics in situations
  399. // where the user forgets (or has syntax errors with) a package line
  400. // multiple times.
  401. if (!is_impl) {
  402. auto [entry, success] = api_map.insert({import_key, &unit_info});
  403. if (!success) {
  404. llvm::StringRef prev_filename =
  405. entry->second->unit->tokens->source().filename();
  406. if (packaging) {
  407. CARBON_DIAGNOSTIC(DuplicateLibraryApi, Error,
  408. "Library's API previously provided by `{0}`.",
  409. std::string);
  410. unit_info.emitter.Emit(packaging->names.node, DuplicateLibraryApi,
  411. prev_filename.str());
  412. } else {
  413. CARBON_DIAGNOSTIC(DuplicateMainApi, Error,
  414. "Main//default previously provided by `{0}`.",
  415. std::string);
  416. // Use the invalid node because there's no node to associate with.
  417. unit_info.emitter.Emit(Parse::NodeId::Invalid, DuplicateMainApi,
  418. prev_filename.str());
  419. }
  420. }
  421. }
  422. // Validate file extensions. Note imports rely the packaging directive, not
  423. // the extension. If the input is not a regular file, for example because it
  424. // is stdin, no filename checking is performed.
  425. if (unit_info.unit->tokens->source().is_regular_file()) {
  426. auto filename = unit_info.unit->tokens->source().filename();
  427. static constexpr llvm::StringLiteral ApiExt = ".carbon";
  428. static constexpr llvm::StringLiteral ImplExt = ".impl.carbon";
  429. bool is_api_with_impl_ext = !is_impl && filename.ends_with(ImplExt);
  430. auto want_ext = is_impl ? ImplExt : ApiExt;
  431. if (is_api_with_impl_ext || !filename.ends_with(want_ext)) {
  432. CARBON_DIAGNOSTIC(IncorrectExtension, Error,
  433. "File extension of `{0}` required for `{1}`.",
  434. llvm::StringLiteral, Lex::TokenKind);
  435. auto diag = unit_info.emitter.Build(
  436. packaging ? packaging->names.node : Parse::NodeId::Invalid,
  437. IncorrectExtension, want_ext,
  438. is_impl ? Lex::TokenKind::Impl : Lex::TokenKind::Api);
  439. if (is_api_with_impl_ext) {
  440. CARBON_DIAGNOSTIC(IncorrectExtensionImplNote, Note,
  441. "File extension of `{0}` only allowed for `{1}`.",
  442. llvm::StringLiteral, Lex::TokenKind);
  443. diag.Note(Parse::NodeId::Invalid, IncorrectExtensionImplNote, ImplExt,
  444. Lex::TokenKind::Impl);
  445. }
  446. diag.Emit();
  447. }
  448. }
  449. }
  450. return api_map;
  451. }
  452. auto CheckParseTrees(const SemIR::File& builtin_ir,
  453. llvm::MutableArrayRef<Unit> units,
  454. llvm::raw_ostream* vlog_stream) -> void {
  455. // Prepare diagnostic emitters in case we run into issues during package
  456. // checking.
  457. //
  458. // UnitInfo is big due to its SmallVectors, so we default to 0 on the stack.
  459. llvm::SmallVector<UnitInfo, 0> unit_infos;
  460. unit_infos.reserve(units.size());
  461. for (auto& unit : units) {
  462. unit_infos.emplace_back(unit);
  463. }
  464. llvm::DenseMap<ImportKey, UnitInfo*> api_map =
  465. BuildApiMapAndDiagnosePackaging(unit_infos);
  466. // Mark down imports for all files.
  467. llvm::SmallVector<UnitInfo*> ready_to_check;
  468. ready_to_check.reserve(units.size());
  469. for (auto& unit_info : unit_infos) {
  470. if (const auto& packaging =
  471. unit_info.unit->parse_tree->packaging_directive()) {
  472. if (packaging->api_or_impl == Parse::Tree::ApiOrImpl::Impl) {
  473. // An `impl` has an implicit import of its `api`.
  474. auto implicit_names = packaging->names;
  475. implicit_names.package_id = IdentifierId::Invalid;
  476. TrackImport(api_map, nullptr, unit_info, implicit_names);
  477. }
  478. }
  479. llvm::DenseMap<ImportKey, Parse::NodeId> explicit_import_map;
  480. for (const auto& import : unit_info.unit->parse_tree->imports()) {
  481. TrackImport(api_map, &explicit_import_map, unit_info, import);
  482. }
  483. // If there were no imports, mark the file as ready to check for below.
  484. if (unit_info.imports_remaining == 0) {
  485. ready_to_check.push_back(&unit_info);
  486. }
  487. }
  488. llvm::DenseMap<const SemIR::File*, Parse::NodeLocationTranslator*>
  489. node_translators;
  490. // Check everything with no dependencies. Earlier entries with dependencies
  491. // will be checked as soon as all their dependencies have been checked.
  492. for (int check_index = 0;
  493. check_index < static_cast<int>(ready_to_check.size()); ++check_index) {
  494. auto* unit_info = ready_to_check[check_index];
  495. CheckParseTree(&node_translators, builtin_ir, *unit_info, vlog_stream);
  496. for (auto* incoming_import : unit_info->incoming_imports) {
  497. --incoming_import->imports_remaining;
  498. if (incoming_import->imports_remaining == 0) {
  499. ready_to_check.push_back(incoming_import);
  500. }
  501. }
  502. }
  503. // If there are still units with remaining imports, it means there's a
  504. // dependency loop.
  505. if (ready_to_check.size() < unit_infos.size()) {
  506. // Go through units and mask out unevaluated imports. This breaks everything
  507. // associated with a loop equivalently, whether it's part of it or depending
  508. // on a part of it.
  509. // TODO: Better identify cycles, maybe try to untangle them.
  510. for (auto& unit_info : unit_infos) {
  511. if (unit_info.imports_remaining > 0) {
  512. for (auto& [package_id, package_imports] :
  513. unit_info.package_imports_map) {
  514. for (auto* import_it = package_imports.imports.begin();
  515. import_it != package_imports.imports.end();) {
  516. if (*import_it->unit_info->unit->sem_ir) {
  517. // The import is checked, so continue.
  518. ++import_it;
  519. } else {
  520. // The import hasn't been checked, indicating a cycle.
  521. CARBON_DIAGNOSTIC(ImportCycleDetected, Error,
  522. "Import cannot be used due to a cycle. Cycle "
  523. "must be fixed to import.");
  524. unit_info.emitter.Emit(import_it->names.node,
  525. ImportCycleDetected);
  526. // Make this look the same as an import which wasn't found.
  527. package_imports.has_load_error = true;
  528. import_it = package_imports.imports.erase(import_it);
  529. }
  530. }
  531. }
  532. }
  533. }
  534. // Check the remaining file contents, which are probably broken due to
  535. // incomplete imports.
  536. for (auto& unit_info : unit_infos) {
  537. if (unit_info.imports_remaining > 0) {
  538. CheckParseTree(&node_translators, builtin_ir, unit_info, vlog_stream);
  539. }
  540. }
  541. }
  542. }
  543. } // namespace Carbon::Check