check.cpp 23 KB

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