check.cpp 26 KB

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