check.cpp 24 KB

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