check.cpp 24 KB

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