check.cpp 26 KB

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