check.cpp 25 KB

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