check.cpp 26 KB

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