check.cpp 26 KB

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