check.cpp 26 KB

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