check.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  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 <variant>
  6. #include "common/check.h"
  7. #include "common/error.h"
  8. #include "common/variant_helpers.h"
  9. #include "common/vlog.h"
  10. #include "toolchain/base/kind_switch.h"
  11. #include "toolchain/base/pretty_stack_trace_function.h"
  12. #include "toolchain/check/context.h"
  13. #include "toolchain/check/diagnostic_helpers.h"
  14. #include "toolchain/check/function.h"
  15. #include "toolchain/check/handle.h"
  16. #include "toolchain/check/import.h"
  17. #include "toolchain/check/import_ref.h"
  18. #include "toolchain/check/sem_ir_diagnostic_converter.h"
  19. #include "toolchain/diagnostics/diagnostic.h"
  20. #include "toolchain/diagnostics/diagnostic_emitter.h"
  21. #include "toolchain/lex/token_kind.h"
  22. #include "toolchain/parse/node_ids.h"
  23. #include "toolchain/parse/tree.h"
  24. #include "toolchain/parse/tree_node_diagnostic_converter.h"
  25. #include "toolchain/sem_ir/file.h"
  26. #include "toolchain/sem_ir/ids.h"
  27. #include "toolchain/sem_ir/typed_insts.h"
  28. namespace Carbon::Check {
  29. namespace {
  30. struct UnitInfo {
  31. // A given import within the file, with its destination.
  32. struct Import {
  33. Parse::Tree::PackagingNames names;
  34. UnitInfo* unit_info;
  35. };
  36. // A file's imports corresponding to a single package, for the map.
  37. struct PackageImports {
  38. // Use the constructor so that the SmallVector is only constructed
  39. // as-needed.
  40. explicit PackageImports(IdentifierId package_id,
  41. Parse::ImportDeclId node_id)
  42. : package_id(package_id), node_id(node_id) {}
  43. // The identifier of the imported package.
  44. IdentifierId package_id;
  45. // The first `import` declaration in the file, which declared the package's
  46. // identifier (even if the import failed). Used for associating diagnostics
  47. // not specific to a single import.
  48. Parse::ImportDeclId node_id;
  49. // Whether there's an import that failed to load.
  50. bool has_load_error = false;
  51. // The list of valid imports.
  52. llvm::SmallVector<Import> imports;
  53. };
  54. explicit UnitInfo(SemIR::CheckIRId check_ir_id, Unit& unit)
  55. : check_ir_id(check_ir_id),
  56. unit(&unit),
  57. converter(unit.tokens, unit.tokens->source().filename(),
  58. unit.parse_tree),
  59. err_tracker(*unit.consumer),
  60. emitter(converter, err_tracker) {}
  61. SemIR::CheckIRId check_ir_id;
  62. Unit* unit;
  63. // Emitter information.
  64. Parse::NodeLocConverter converter;
  65. ErrorTrackingDiagnosticConsumer err_tracker;
  66. DiagnosticEmitter<Parse::NodeLoc> emitter;
  67. // List of the outgoing imports. If a package includes unavailable library
  68. // imports, it has an entry with has_load_error set. Invalid imports (for
  69. // example, `import Main;`) aren't added because they won't add identifiers to
  70. // name lookup.
  71. llvm::SmallVector<PackageImports> package_imports;
  72. // A map of the package names to the outgoing imports above.
  73. llvm::DenseMap<IdentifierId, int32_t> package_imports_map;
  74. // The remaining number of imports which must be checked before this unit can
  75. // be processed.
  76. int32_t imports_remaining = 0;
  77. // A list of incoming imports. This will be empty for `impl` files, because
  78. // imports only touch `api` files.
  79. llvm::SmallVector<UnitInfo*> incoming_imports;
  80. // The corresponding `api` unit if this is an `impl` file. The entry should
  81. // also be in the corresponding `PackageImports`.
  82. UnitInfo* api_for_impl = nullptr;
  83. };
  84. } // namespace
  85. // Collects transitive imports, handling deduplication.
  86. static auto CollectTransitiveImports(const UnitInfo::PackageImports& imports,
  87. int total_ir_count)
  88. -> llvm::SmallVector<SemIR::ImportIR> {
  89. llvm::SmallVector<SemIR::ImportIR> results;
  90. // Track whether an IR was imported in full, including `export import`. This
  91. // distinguishes from IRs that are indirectly added without all names being
  92. // exported to this IR.
  93. llvm::SmallVector<int> ir_to_result_index(total_ir_count, -1);
  94. // First add direct imports. This means that if an entity is imported both
  95. // directly and indirectly, the import path will reflect the direct import.
  96. for (const auto& import : imports.imports) {
  97. const auto& direct_ir = **import.unit_info->unit->sem_ir;
  98. ir_to_result_index[direct_ir.check_ir_id().index] = results.size();
  99. results.push_back({.node_id = import.names.node_id,
  100. .sem_ir = &direct_ir,
  101. .is_export = import.names.is_export});
  102. }
  103. // Loop through direct imports for any indirect exports. The underlying vector
  104. // is appended during iteration, so take the size first.
  105. const int direct_imports = results.size();
  106. for (int direct_index : llvm::seq(direct_imports)) {
  107. bool is_export = results[direct_index].is_export;
  108. for (const auto& indirect_ir :
  109. results[direct_index].sem_ir->import_irs().array_ref()) {
  110. if (!indirect_ir.is_export) {
  111. continue;
  112. }
  113. auto& indirect_index =
  114. ir_to_result_index[indirect_ir.sem_ir->check_ir_id().index];
  115. if (indirect_index == -1) {
  116. indirect_index = results.size();
  117. // TODO: In the case of a recursive `export import`, this only points at
  118. // the outermost import. May want something that better reflects the
  119. // recursion.
  120. results.push_back({.node_id = results[direct_index].node_id,
  121. .sem_ir = indirect_ir.sem_ir,
  122. .is_export = is_export});
  123. } else if (is_export) {
  124. results[indirect_index].is_export = true;
  125. }
  126. }
  127. }
  128. return results;
  129. }
  130. // Imports the current package.
  131. static auto ImportCurrentPackage(Context& context, UnitInfo& unit_info,
  132. int total_ir_count,
  133. SemIR::InstId package_inst_id,
  134. SemIR::TypeId namespace_type_id) -> void {
  135. // Add imports from the current package.
  136. auto self_import_map_it =
  137. unit_info.package_imports_map.find(IdentifierId::Invalid);
  138. if (self_import_map_it == unit_info.package_imports_map.end()) {
  139. // Push the scope; there are no names to add.
  140. context.scope_stack().Push(package_inst_id, SemIR::NameScopeId::Package);
  141. return;
  142. }
  143. UnitInfo::PackageImports& self_import =
  144. unit_info.package_imports[self_import_map_it->second];
  145. if (self_import.has_load_error) {
  146. context.name_scopes().Get(SemIR::NameScopeId::Package).has_error = true;
  147. }
  148. ImportLibrariesFromCurrentPackage(
  149. context, namespace_type_id,
  150. CollectTransitiveImports(self_import, total_ir_count));
  151. context.scope_stack().Push(
  152. package_inst_id, SemIR::NameScopeId::Package,
  153. context.name_scopes().Get(SemIR::NameScopeId::Package).has_error);
  154. }
  155. // Add imports to the root block.
  156. static auto InitPackageScopeAndImports(Context& context, UnitInfo& unit_info,
  157. int total_ir_count) -> void {
  158. // First create the constant values map for all imported IRs. We'll populate
  159. // these with mappings for namespaces as we go.
  160. size_t num_irs = 0;
  161. for (auto& package_imports : unit_info.package_imports) {
  162. num_irs += package_imports.imports.size();
  163. }
  164. if (!unit_info.api_for_impl) {
  165. // Leave an empty slot for ImportIRId::ApiForImpl.
  166. ++num_irs;
  167. }
  168. context.import_irs().Reserve(num_irs);
  169. context.import_ir_constant_values().reserve(num_irs);
  170. context.SetTotalIRCount(total_ir_count);
  171. // Importing makes many namespaces, so only canonicalize the type once.
  172. auto namespace_type_id =
  173. context.GetBuiltinType(SemIR::BuiltinKind::NamespaceType);
  174. // Define the package scope, with an instruction for `package` expressions to
  175. // reference.
  176. auto package_scope_id = context.name_scopes().Add(
  177. SemIR::InstId::PackageNamespace, SemIR::NameId::PackageNamespace,
  178. SemIR::NameScopeId::Invalid);
  179. CARBON_CHECK(package_scope_id == SemIR::NameScopeId::Package);
  180. auto package_inst_id = context.AddInst<SemIR::Namespace>(
  181. Parse::NodeId::Invalid, {.type_id = namespace_type_id,
  182. .name_scope_id = SemIR::NameScopeId::Package,
  183. .import_id = SemIR::InstId::Invalid});
  184. CARBON_CHECK(package_inst_id == SemIR::InstId::PackageNamespace);
  185. // If there is an implicit `api` import, set it first so that it uses the
  186. // ImportIRId::ApiForImpl when processed for imports.
  187. if (unit_info.api_for_impl) {
  188. SetApiImportIR(
  189. context,
  190. {.node_id = context.parse_tree().packaging_decl()->names.node_id,
  191. .sem_ir = &**unit_info.api_for_impl->unit->sem_ir});
  192. } else {
  193. SetApiImportIR(context,
  194. {.node_id = Parse::InvalidNodeId(), .sem_ir = nullptr});
  195. }
  196. ImportCurrentPackage(context, unit_info, total_ir_count, package_inst_id,
  197. namespace_type_id);
  198. CARBON_CHECK(context.scope_stack().PeekIndex() == ScopeIndex::Package);
  199. for (auto& package_imports : unit_info.package_imports) {
  200. if (!package_imports.package_id.is_valid()) {
  201. // Current package is handled above.
  202. continue;
  203. }
  204. ImportLibrariesFromOtherPackage(
  205. context, namespace_type_id, package_imports.node_id,
  206. package_imports.package_id,
  207. CollectTransitiveImports(package_imports, total_ir_count),
  208. package_imports.has_load_error);
  209. }
  210. }
  211. namespace {
  212. // State used to track the next deferred function definition that we will
  213. // encounter and need to reorder.
  214. class NextDeferredDefinitionCache {
  215. public:
  216. explicit NextDeferredDefinitionCache(const Parse::Tree* tree) : tree_(tree) {
  217. SkipTo(Parse::DeferredDefinitionIndex(0));
  218. }
  219. // Set the specified deferred definition index as being the next one that will
  220. // be encountered.
  221. auto SkipTo(Parse::DeferredDefinitionIndex next_index) -> void {
  222. index_ = next_index;
  223. if (static_cast<std::size_t>(index_.index) ==
  224. tree_->deferred_definitions().size()) {
  225. start_id_ = Parse::NodeId::Invalid;
  226. } else {
  227. start_id_ = tree_->deferred_definitions().Get(index_).start_id;
  228. }
  229. }
  230. // Returns the index of the next deferred definition to be encountered.
  231. auto index() const -> Parse::DeferredDefinitionIndex { return index_; }
  232. // Returns the ID of the start node of the next deferred definition.
  233. auto start_id() const -> Parse::NodeId { return start_id_; }
  234. private:
  235. const Parse::Tree* tree_;
  236. Parse::DeferredDefinitionIndex index_ =
  237. Parse::DeferredDefinitionIndex::Invalid;
  238. Parse::NodeId start_id_ = Parse::NodeId::Invalid;
  239. };
  240. } // namespace
  241. // Determines whether this node kind is the start of a deferred definition
  242. // scope.
  243. static auto IsStartOfDeferredDefinitionScope(Parse::NodeKind kind) -> bool {
  244. switch (kind) {
  245. case Parse::NodeKind::ClassDefinitionStart:
  246. case Parse::NodeKind::ImplDefinitionStart:
  247. case Parse::NodeKind::InterfaceDefinitionStart:
  248. case Parse::NodeKind::NamedConstraintDefinitionStart:
  249. // TODO: Mixins.
  250. return true;
  251. default:
  252. return false;
  253. }
  254. }
  255. // Determines whether this node kind is the end of a deferred definition scope.
  256. static auto IsEndOfDeferredDefinitionScope(Parse::NodeKind kind) -> bool {
  257. switch (kind) {
  258. case Parse::NodeKind::ClassDefinition:
  259. case Parse::NodeKind::ImplDefinition:
  260. case Parse::NodeKind::InterfaceDefinition:
  261. case Parse::NodeKind::NamedConstraintDefinition:
  262. // TODO: Mixins.
  263. return true;
  264. default:
  265. return false;
  266. }
  267. }
  268. namespace {
  269. // A worklist of pending tasks to perform to check deferred function definitions
  270. // in the right order.
  271. class DeferredDefinitionWorklist {
  272. public:
  273. // A worklist task that indicates we should check a deferred function
  274. // definition that we previously skipped.
  275. struct CheckSkippedDefinition {
  276. // The definition that we skipped.
  277. Parse::DeferredDefinitionIndex definition_index;
  278. // The suspended function.
  279. SuspendedFunction suspended_fn;
  280. };
  281. // A worklist task that indicates we should enter a nested deferred definition
  282. // scope.
  283. struct EnterDeferredDefinitionScope {
  284. // The suspended scope. This is only set once we reach the end of the scope.
  285. std::optional<DeclNameStack::SuspendedName> suspended_name;
  286. // Whether this scope is itself within an outer deferred definition scope.
  287. // If so, we'll delay processing its contents until we reach the end of the
  288. // parent scope. For example:
  289. //
  290. // ```
  291. // class A {
  292. // class B {
  293. // fn F() -> A { return {}; }
  294. // }
  295. // } // A.B.F is type-checked here, with A complete.
  296. //
  297. // fn F() {
  298. // class C {
  299. // fn G() {}
  300. // } // C.G is type-checked here.
  301. // }
  302. // ```
  303. bool in_deferred_definition_scope;
  304. };
  305. // A worklist task that indicates we should leave a deferred definition scope.
  306. struct LeaveDeferredDefinitionScope {
  307. // Whether this scope is within another deferred definition scope.
  308. bool in_deferred_definition_scope;
  309. };
  310. // A pending type-checking task.
  311. using Task =
  312. std::variant<CheckSkippedDefinition, EnterDeferredDefinitionScope,
  313. LeaveDeferredDefinitionScope>;
  314. explicit DeferredDefinitionWorklist(llvm::raw_ostream* vlog_stream)
  315. : vlog_stream_(vlog_stream) {
  316. // See declaration of `worklist_`.
  317. worklist_.reserve(64);
  318. }
  319. static constexpr llvm::StringLiteral VlogPrefix =
  320. "DeferredDefinitionWorklist ";
  321. // Suspend the current function definition and push a task onto the worklist
  322. // to finish it later.
  323. auto SuspendFunctionAndPush(Context& context,
  324. Parse::DeferredDefinitionIndex index,
  325. Parse::FunctionDefinitionStartId node_id)
  326. -> void {
  327. worklist_.push_back(CheckSkippedDefinition{
  328. index, HandleFunctionDefinitionSuspend(context, node_id)});
  329. CARBON_VLOG() << VlogPrefix << "Push CheckSkippedDefinition " << index.index
  330. << "\n";
  331. }
  332. // Push a task to re-enter a function scope, so that functions defined within
  333. // it are type-checked in the right context.
  334. auto PushEnterDeferredDefinitionScope(Context& context) -> void {
  335. bool nested = !entered_scopes_.empty() &&
  336. entered_scopes_.back().scope_index ==
  337. context.decl_name_stack().PeekInitialScopeIndex();
  338. entered_scopes_.push_back(
  339. {.worklist_start_index = worklist_.size(),
  340. .scope_index = context.scope_stack().PeekIndex()});
  341. worklist_.push_back(
  342. EnterDeferredDefinitionScope{.suspended_name = std::nullopt,
  343. .in_deferred_definition_scope = nested});
  344. CARBON_VLOG() << VlogPrefix << "Push EnterDeferredDefinitionScope "
  345. << (nested ? "(nested)" : "(non-nested)") << "\n";
  346. }
  347. // Suspend the current deferred definition scope, which is finished but still
  348. // on the decl_name_stack, and push a task to leave the scope when we're
  349. // type-checking deferred definitions. Returns `true` if the current list of
  350. // deferred definitions should be type-checked immediately.
  351. auto SuspendFinishedScopeAndPush(Context& context) -> bool;
  352. // Pop the next task off the worklist.
  353. auto Pop() -> Task {
  354. if (vlog_stream_) {
  355. VariantMatch(
  356. worklist_.back(),
  357. [&](CheckSkippedDefinition& definition) {
  358. CARBON_VLOG() << VlogPrefix << "Handle CheckSkippedDefinition "
  359. << definition.definition_index.index << "\n";
  360. },
  361. [&](EnterDeferredDefinitionScope& enter) {
  362. CARBON_CHECK(enter.in_deferred_definition_scope);
  363. CARBON_VLOG() << VlogPrefix
  364. << "Handle EnterDeferredDefinitionScope (nested)\n";
  365. },
  366. [&](LeaveDeferredDefinitionScope& leave) {
  367. bool nested = leave.in_deferred_definition_scope;
  368. CARBON_VLOG() << VlogPrefix
  369. << "Handle LeaveDeferredDefinitionScope "
  370. << (nested ? "(nested)" : "(non-nested)") << "\n";
  371. });
  372. }
  373. return worklist_.pop_back_val();
  374. }
  375. // CHECK that the work list has no further work.
  376. auto VerifyEmpty() {
  377. CARBON_CHECK(worklist_.empty() && entered_scopes_.empty())
  378. << "Tasks left behind on worklist.";
  379. }
  380. private:
  381. llvm::raw_ostream* vlog_stream_;
  382. // A worklist of type-checking tasks we'll need to do later.
  383. //
  384. // Don't allocate any inline storage here. A Task is fairly large, so we never
  385. // want this to live on the stack. Instead, we reserve space in the
  386. // constructor for a fairly large number of deferred definitions.
  387. llvm::SmallVector<Task, 0> worklist_;
  388. // A deferred definition scope that is currently still open.
  389. struct EnteredScope {
  390. // The index in worklist_ of the EnterDeferredDefinitionScope task.
  391. size_t worklist_start_index;
  392. // The corresponding lexical scope index.
  393. ScopeIndex scope_index;
  394. };
  395. // The deferred definition scopes for the current checking actions.
  396. llvm::SmallVector<EnteredScope> entered_scopes_;
  397. };
  398. } // namespace
  399. auto DeferredDefinitionWorklist::SuspendFinishedScopeAndPush(Context& context)
  400. -> bool {
  401. auto start_index = entered_scopes_.pop_back_val().worklist_start_index;
  402. // If we've not found any deferred definitions in this scope, clean up the
  403. // stack.
  404. if (start_index == worklist_.size() - 1) {
  405. context.decl_name_stack().PopScope();
  406. worklist_.pop_back();
  407. CARBON_VLOG() << VlogPrefix << "Pop EnterDeferredDefinitionScope (empty)\n";
  408. return false;
  409. }
  410. // If we're finishing a nested deferred definition scope, keep track of that
  411. // but don't type-check deferred definitions now.
  412. auto& enter_scope = get<EnterDeferredDefinitionScope>(worklist_[start_index]);
  413. if (enter_scope.in_deferred_definition_scope) {
  414. // This is a nested deferred definition scope. Suspend the inner scope so we
  415. // can restore it when we come to type-check the deferred definitions.
  416. enter_scope.suspended_name = context.decl_name_stack().Suspend();
  417. // Enqueue a task to leave the nested scope.
  418. worklist_.push_back(
  419. LeaveDeferredDefinitionScope{.in_deferred_definition_scope = true});
  420. CARBON_VLOG() << VlogPrefix
  421. << "Push LeaveDeferredDefinitionScope (nested)\n";
  422. return false;
  423. }
  424. // We're at the end of a non-nested deferred definition scope. Prepare to
  425. // start checking deferred definitions. Enqueue a task to leave this outer
  426. // scope and end checking deferred definitions.
  427. worklist_.push_back(
  428. LeaveDeferredDefinitionScope{.in_deferred_definition_scope = false});
  429. CARBON_VLOG() << VlogPrefix
  430. << "Push LeaveDeferredDefinitionScope (non-nested)\n";
  431. // We'll process the worklist in reverse index order, so reverse the part of
  432. // it we're about to execute so we run our tasks in the order in which they
  433. // were pushed.
  434. std::reverse(worklist_.begin() + start_index, worklist_.end());
  435. // Pop the `EnterDeferredDefinitionScope` that's now on the end of the
  436. // worklist. We stay in that scope rather than suspending then immediately
  437. // resuming it.
  438. CARBON_CHECK(
  439. holds_alternative<EnterDeferredDefinitionScope>(worklist_.back()))
  440. << "Unexpected task in worklist.";
  441. worklist_.pop_back();
  442. CARBON_VLOG() << VlogPrefix
  443. << "Handle EnterDeferredDefinitionScope (non-nested)\n";
  444. return true;
  445. }
  446. namespace {
  447. // A traversal of the node IDs in the parse tree, in the order in which we need
  448. // to check them.
  449. class NodeIdTraversal {
  450. public:
  451. explicit NodeIdTraversal(Context& context, llvm::raw_ostream* vlog_stream)
  452. : context_(context),
  453. next_deferred_definition_(&context.parse_tree()),
  454. worklist_(vlog_stream) {
  455. chunks_.push_back(
  456. {.it = context.parse_tree().postorder().begin(),
  457. .end = context.parse_tree().postorder().end(),
  458. .next_definition = Parse::DeferredDefinitionIndex::Invalid});
  459. }
  460. // Finds the next `NodeId` to type-check. Returns nullopt if the traversal is
  461. // complete.
  462. auto Next() -> std::optional<Parse::NodeId>;
  463. // Performs any processing necessary after we type-check a node.
  464. auto Handle(Parse::NodeKind parse_kind) -> void {
  465. // When we reach the start of a deferred definition scope, add a task to the
  466. // worklist to check future skipped definitions in the new context.
  467. if (IsStartOfDeferredDefinitionScope(parse_kind)) {
  468. worklist_.PushEnterDeferredDefinitionScope(context_);
  469. }
  470. // When we reach the end of a deferred definition scope, add a task to the
  471. // worklist to leave the scope. If this is not a nested scope, start
  472. // checking the deferred definitions now.
  473. if (IsEndOfDeferredDefinitionScope(parse_kind)) {
  474. chunks_.back().checking_deferred_definitions =
  475. worklist_.SuspendFinishedScopeAndPush(context_);
  476. }
  477. }
  478. private:
  479. // A chunk of the parse tree that we need to type-check.
  480. struct Chunk {
  481. Parse::Tree::PostorderIterator it;
  482. Parse::Tree::PostorderIterator end;
  483. // The next definition that will be encountered after this chunk completes.
  484. Parse::DeferredDefinitionIndex next_definition;
  485. // Whether we are currently checking deferred definitions, rather than the
  486. // tokens of this chunk. If so, we'll pull tasks off `worklist` and execute
  487. // them until we're done with this batch of deferred definitions. Otherwise,
  488. // we'll pull node IDs from `*it` until it reaches `end`.
  489. bool checking_deferred_definitions = false;
  490. };
  491. // Re-enter a nested deferred definition scope.
  492. auto PerformTask(
  493. DeferredDefinitionWorklist::EnterDeferredDefinitionScope&& enter)
  494. -> void {
  495. CARBON_CHECK(enter.suspended_name)
  496. << "Entering a scope with no suspension information.";
  497. context_.decl_name_stack().Restore(std::move(*enter.suspended_name));
  498. }
  499. // Leave a nested or top-level deferred definition scope.
  500. auto PerformTask(
  501. DeferredDefinitionWorklist::LeaveDeferredDefinitionScope&& leave)
  502. -> void {
  503. if (!leave.in_deferred_definition_scope) {
  504. // We're done with checking deferred definitions.
  505. chunks_.back().checking_deferred_definitions = false;
  506. }
  507. context_.decl_name_stack().PopScope();
  508. }
  509. // Resume checking a deferred definition.
  510. auto PerformTask(
  511. DeferredDefinitionWorklist::CheckSkippedDefinition&& parse_definition)
  512. -> void {
  513. auto& [definition_index, suspended_fn] = parse_definition;
  514. const auto& definition_info =
  515. context_.parse_tree().deferred_definitions().Get(definition_index);
  516. HandleFunctionDefinitionResume(context_, definition_info.start_id,
  517. std::move(suspended_fn));
  518. chunks_.push_back(
  519. {.it = context_.parse_tree().postorder(definition_info.start_id).end(),
  520. .end = context_.parse_tree()
  521. .postorder(definition_info.definition_id)
  522. .end(),
  523. .next_definition = next_deferred_definition_.index()});
  524. ++definition_index.index;
  525. next_deferred_definition_.SkipTo(definition_index);
  526. }
  527. Context& context_;
  528. NextDeferredDefinitionCache next_deferred_definition_;
  529. DeferredDefinitionWorklist worklist_;
  530. llvm::SmallVector<Chunk> chunks_;
  531. };
  532. } // namespace
  533. auto NodeIdTraversal::Next() -> std::optional<Parse::NodeId> {
  534. while (true) {
  535. // If we're checking deferred definitions, find the next definition we
  536. // should check, restore its suspended state, and add a corresponding
  537. // `Chunk` to the top of the chunk list.
  538. if (chunks_.back().checking_deferred_definitions) {
  539. std::visit(
  540. [&](auto&& task) { PerformTask(std::forward<decltype(task)>(task)); },
  541. worklist_.Pop());
  542. continue;
  543. }
  544. // If we're not checking deferred definitions, produce the next parse node
  545. // for this chunk. If we've run out of parse nodes, we're done with this
  546. // chunk of the parse tree.
  547. if (chunks_.back().it == chunks_.back().end) {
  548. auto old_chunk = chunks_.pop_back_val();
  549. // If we're out of chunks, then we're done entirely.
  550. if (chunks_.empty()) {
  551. worklist_.VerifyEmpty();
  552. return std::nullopt;
  553. }
  554. next_deferred_definition_.SkipTo(old_chunk.next_definition);
  555. continue;
  556. }
  557. auto node_id = *chunks_.back().it;
  558. // If we've reached the start of a deferred definition, skip to the end of
  559. // it, and track that we need to check it later.
  560. if (node_id == next_deferred_definition_.start_id()) {
  561. const auto& definition_info =
  562. context_.parse_tree().deferred_definitions().Get(
  563. next_deferred_definition_.index());
  564. worklist_.SuspendFunctionAndPush(context_,
  565. next_deferred_definition_.index(),
  566. definition_info.start_id);
  567. // Continue type-checking the parse tree after the end of the definition.
  568. chunks_.back().it =
  569. context_.parse_tree().postorder(definition_info.definition_id).end();
  570. next_deferred_definition_.SkipTo(definition_info.next_definition_index);
  571. continue;
  572. }
  573. ++chunks_.back().it;
  574. return node_id;
  575. }
  576. }
  577. // Emits a diagnostic for each declaration in context.definitions_required()
  578. // that doesn't have a definition.
  579. static auto DiagnoseMissingDefinitions(Context& context,
  580. Context::DiagnosticEmitter& emitter)
  581. -> void {
  582. CARBON_DIAGNOSTIC(MissingDefinitionInImpl, Error,
  583. "No definition found for declaration in impl file");
  584. for (SemIR::InstId decl_inst_id : context.definitions_required()) {
  585. SemIR::Inst decl_inst = context.insts().Get(decl_inst_id);
  586. CARBON_KIND_SWITCH(context.insts().Get(decl_inst_id)) {
  587. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  588. if (!context.classes().Get(class_decl.class_id).is_defined()) {
  589. emitter.Emit(decl_inst_id, MissingDefinitionInImpl);
  590. }
  591. break;
  592. }
  593. case CARBON_KIND(SemIR::FunctionDecl function_decl): {
  594. if (context.functions().Get(function_decl.function_id).definition_id ==
  595. SemIR::InstId::Invalid) {
  596. emitter.Emit(decl_inst_id, MissingDefinitionInImpl);
  597. }
  598. break;
  599. }
  600. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  601. if (!context.impls().Get(impl_decl.impl_id).is_defined()) {
  602. emitter.Emit(decl_inst_id, MissingDefinitionInImpl);
  603. }
  604. break;
  605. }
  606. case SemIR::InterfaceDecl::Kind: {
  607. // TODO: handle `interface` as well, once we can test it without
  608. // triggering https://github.com/carbon-language/carbon-lang/issues/4071
  609. CARBON_FATAL()
  610. << "TODO: Support interfaces in DiagnoseMissingDefinitions";
  611. }
  612. default: {
  613. CARBON_FATAL() << "Unexpected inst in definitions_required: "
  614. << decl_inst;
  615. }
  616. }
  617. }
  618. }
  619. // Loops over all nodes in the tree. On some errors, this may return early,
  620. // for example if an unrecoverable state is encountered.
  621. // NOLINTNEXTLINE(readability-function-size)
  622. static auto ProcessNodeIds(Context& context, llvm::raw_ostream* vlog_stream,
  623. ErrorTrackingDiagnosticConsumer& err_tracker,
  624. Parse::NodeLocConverter* converter) -> bool {
  625. NodeIdTraversal traversal(context, vlog_stream);
  626. Parse::NodeId node_id = Parse::NodeId::Invalid;
  627. // On crash, report which token we were handling.
  628. PrettyStackTraceFunction node_dumper([&](llvm::raw_ostream& output) {
  629. auto loc = converter->ConvertLoc(
  630. node_id, [](DiagnosticLoc, const Internal::DiagnosticBase<>&) {});
  631. loc.FormatLocation(output);
  632. output << ": Check::Handle" << context.parse_tree().node_kind(node_id)
  633. << "\n";
  634. loc.FormatSnippet(output);
  635. });
  636. while (auto maybe_node_id = traversal.Next()) {
  637. node_id = *maybe_node_id;
  638. auto parse_kind = context.parse_tree().node_kind(node_id);
  639. switch (parse_kind) {
  640. #define CARBON_PARSE_NODE_KIND(Name) \
  641. case Parse::NodeKind::Name: { \
  642. if (!Check::Handle##Name(context, Parse::Name##Id(node_id))) { \
  643. CARBON_CHECK(err_tracker.seen_error()) \
  644. << "Handle" #Name " returned false without printing a diagnostic"; \
  645. return false; \
  646. } \
  647. break; \
  648. }
  649. #include "toolchain/parse/node_kind.def"
  650. }
  651. traversal.Handle(parse_kind);
  652. }
  653. return true;
  654. }
  655. // Produces and checks the IR for the provided Parse::Tree.
  656. static auto CheckParseTree(
  657. llvm::MutableArrayRef<Parse::NodeLocConverter*> node_converters,
  658. UnitInfo& unit_info, int total_ir_count, llvm::raw_ostream* vlog_stream)
  659. -> void {
  660. unit_info.unit->sem_ir->emplace(
  661. unit_info.check_ir_id, *unit_info.unit->value_stores,
  662. unit_info.unit->tokens->source().filename().str());
  663. SemIR::File& sem_ir = **unit_info.unit->sem_ir;
  664. SemIRDiagnosticConverter converter(node_converters, &sem_ir);
  665. Context::DiagnosticEmitter emitter(converter, unit_info.err_tracker);
  666. Context context(*unit_info.unit->tokens, emitter, *unit_info.unit->parse_tree,
  667. sem_ir, vlog_stream);
  668. PrettyStackTraceFunction context_dumper(
  669. [&](llvm::raw_ostream& output) { context.PrintForStackDump(output); });
  670. // Add a block for the file.
  671. context.inst_block_stack().Push();
  672. InitPackageScopeAndImports(context, unit_info, total_ir_count);
  673. // Import all impls declared in imports.
  674. // TODO: Do this selectively when we see an impl query.
  675. ImportImpls(context);
  676. if (!ProcessNodeIds(context, vlog_stream, unit_info.err_tracker,
  677. &unit_info.converter)) {
  678. context.sem_ir().set_has_errors(true);
  679. return;
  680. }
  681. // Pop information for the file-level scope.
  682. sem_ir.set_top_inst_block_id(context.inst_block_stack().Pop());
  683. context.scope_stack().Pop();
  684. context.FinalizeExports();
  685. context.FinalizeGlobalInit();
  686. DiagnoseMissingDefinitions(context, emitter);
  687. context.VerifyOnFinish();
  688. sem_ir.set_has_errors(unit_info.err_tracker.seen_error());
  689. #ifndef NDEBUG
  690. if (auto verify = sem_ir.Verify(); !verify.ok()) {
  691. CARBON_FATAL() << sem_ir << "Built invalid semantics IR: " << verify.error()
  692. << "\n";
  693. }
  694. #endif
  695. }
  696. // The package and library names, used as map keys.
  697. using ImportKey = std::pair<llvm::StringRef, llvm::StringRef>;
  698. // Returns a key form of the package object. file_package_id is only used for
  699. // imports, not the main package declaration; as a consequence, it will be
  700. // invalid for the main package declaration.
  701. static auto GetImportKey(UnitInfo& unit_info, IdentifierId file_package_id,
  702. Parse::Tree::PackagingNames names) -> ImportKey {
  703. auto* stores = unit_info.unit->value_stores;
  704. llvm::StringRef package_name =
  705. names.package_id.is_valid() ? stores->identifiers().Get(names.package_id)
  706. : file_package_id.is_valid() ? stores->identifiers().Get(file_package_id)
  707. : "";
  708. llvm::StringRef library_name =
  709. names.library_id.is_valid()
  710. ? stores->string_literal_values().Get(names.library_id)
  711. : "";
  712. return {package_name, library_name};
  713. }
  714. static constexpr llvm::StringLiteral ExplicitMainName = "Main";
  715. static auto RenderImportKey(ImportKey import_key) -> std::string {
  716. if (import_key.first.empty()) {
  717. import_key.first = ExplicitMainName;
  718. }
  719. if (import_key.second.empty()) {
  720. return import_key.first.str();
  721. }
  722. return llvm::formatv("{0}//{1}", import_key.first, import_key.second).str();
  723. }
  724. // Marks an import as required on both the source and target file.
  725. //
  726. // The ID comparisons between the import and unit are okay because they both
  727. // come from the same file.
  728. static auto TrackImport(
  729. llvm::DenseMap<ImportKey, UnitInfo*>& api_map,
  730. llvm::DenseMap<ImportKey, Parse::NodeId>* explicit_import_map,
  731. UnitInfo& unit_info, Parse::Tree::PackagingNames import) -> void {
  732. const auto& packaging = unit_info.unit->parse_tree->packaging_decl();
  733. IdentifierId file_package_id =
  734. packaging ? packaging->names.package_id : IdentifierId::Invalid;
  735. auto import_key = GetImportKey(unit_info, file_package_id, import);
  736. // True if the import has `Main` as the package name, even if it comes from
  737. // the file's packaging (diagnostics may differentiate).
  738. bool is_explicit_main = import_key.first == ExplicitMainName;
  739. // Explicit imports need more validation than implicit ones. We try to do
  740. // these in an order of imports that should be removed, followed by imports
  741. // that might be valid with syntax fixes.
  742. if (explicit_import_map) {
  743. // Diagnose redundant imports.
  744. if (auto [insert_it, success] =
  745. explicit_import_map->insert({import_key, import.node_id});
  746. !success) {
  747. CARBON_DIAGNOSTIC(RepeatedImport, Error,
  748. "Library imported more than once.");
  749. CARBON_DIAGNOSTIC(FirstImported, Note, "First import here.");
  750. unit_info.emitter.Build(import.node_id, RepeatedImport)
  751. .Note(insert_it->second, FirstImported)
  752. .Emit();
  753. return;
  754. }
  755. // True if the file's package is implicitly `Main` (by omitting an explicit
  756. // package name).
  757. bool is_file_implicit_main =
  758. !packaging || !packaging->names.package_id.is_valid();
  759. // True if the import is using implicit "current package" syntax (by
  760. // omitting an explicit package name).
  761. bool is_import_implicit_current_package = !import.package_id.is_valid();
  762. // True if the import is using `default` library syntax.
  763. bool is_import_default_library = !import.library_id.is_valid();
  764. // True if the import and file point at the same package, even by
  765. // incorrectly specifying the current package name to `import`.
  766. bool is_same_package = is_import_implicit_current_package ||
  767. import.package_id == file_package_id;
  768. // True if the import points at the same library as the file's library.
  769. bool is_same_library =
  770. is_same_package &&
  771. (packaging ? import.library_id == packaging->names.library_id
  772. : is_import_default_library);
  773. // Diagnose explicit imports of the same library, whether from `api` or
  774. // `impl`.
  775. if (is_same_library) {
  776. CARBON_DIAGNOSTIC(ExplicitImportApi, Error,
  777. "Explicit import of `api` from `impl` file is "
  778. "redundant with implicit import.");
  779. CARBON_DIAGNOSTIC(ImportSelf, Error, "File cannot import itself.");
  780. bool is_impl = !packaging || packaging->is_impl;
  781. unit_info.emitter.Emit(import.node_id,
  782. is_impl ? ExplicitImportApi : ImportSelf);
  783. return;
  784. }
  785. // Diagnose explicit imports of `Main//default`. There is no `api` for it.
  786. // This lets other diagnostics handle explicit `Main` package naming.
  787. if (is_file_implicit_main && is_import_implicit_current_package &&
  788. is_import_default_library) {
  789. CARBON_DIAGNOSTIC(ImportMainDefaultLibrary, Error,
  790. "Cannot import `Main//default`.");
  791. unit_info.emitter.Emit(import.node_id, ImportMainDefaultLibrary);
  792. return;
  793. }
  794. if (!is_import_implicit_current_package) {
  795. // Diagnose explicit imports of the same package that use the package
  796. // name.
  797. if (is_same_package || (is_file_implicit_main && is_explicit_main)) {
  798. CARBON_DIAGNOSTIC(
  799. ImportCurrentPackageByName, Error,
  800. "Imports from the current package must omit the package name.");
  801. unit_info.emitter.Emit(import.node_id, ImportCurrentPackageByName);
  802. return;
  803. }
  804. // Diagnose explicit imports from `Main`.
  805. if (is_explicit_main) {
  806. CARBON_DIAGNOSTIC(ImportMainPackage, Error,
  807. "Cannot import `Main` from other packages.");
  808. unit_info.emitter.Emit(import.node_id, ImportMainPackage);
  809. return;
  810. }
  811. }
  812. } else if (is_explicit_main) {
  813. // An implicit import with an explicit `Main` occurs when a `package` rule
  814. // has bad syntax, which will have been diagnosed when building the API map.
  815. // As a consequence, we return silently.
  816. return;
  817. }
  818. // Get the package imports, or create them if this is the first.
  819. auto [package_imports_map_it, is_inserted] =
  820. unit_info.package_imports_map.insert(
  821. {import.package_id, unit_info.package_imports.size()});
  822. if (is_inserted) {
  823. unit_info.package_imports.push_back(
  824. UnitInfo::PackageImports(import.package_id, import.node_id));
  825. }
  826. UnitInfo::PackageImports& package_imports =
  827. unit_info.package_imports[package_imports_map_it->second];
  828. if (auto api = api_map.find(import_key); api != api_map.end()) {
  829. // Add references between the file and imported api.
  830. package_imports.imports.push_back({import, api->second});
  831. ++unit_info.imports_remaining;
  832. api->second->incoming_imports.push_back(&unit_info);
  833. // If this is the implicit import, note we have it.
  834. if (!explicit_import_map) {
  835. CARBON_CHECK(!unit_info.api_for_impl);
  836. unit_info.api_for_impl = api->second;
  837. }
  838. } else {
  839. // The imported api is missing.
  840. package_imports.has_load_error = true;
  841. CARBON_DIAGNOSTIC(LibraryApiNotFound, Error,
  842. "Corresponding API for '{0}' not found.", std::string);
  843. CARBON_DIAGNOSTIC(ImportNotFound, Error, "Imported API '{0}' not found.",
  844. std::string);
  845. unit_info.emitter.Emit(
  846. import.node_id,
  847. explicit_import_map ? ImportNotFound : LibraryApiNotFound,
  848. RenderImportKey(import_key));
  849. }
  850. }
  851. // Builds a map of `api` files which might be imported. Also diagnoses issues
  852. // related to the packaging because the strings are loaded as part of getting
  853. // the ImportKey (which we then do for `impl` files too).
  854. static auto BuildApiMapAndDiagnosePackaging(
  855. llvm::MutableArrayRef<UnitInfo> unit_infos)
  856. -> llvm::DenseMap<ImportKey, UnitInfo*> {
  857. llvm::DenseMap<ImportKey, UnitInfo*> api_map;
  858. for (auto& unit_info : unit_infos) {
  859. const auto& packaging = unit_info.unit->parse_tree->packaging_decl();
  860. // An import key formed from the `package` or `library` declaration. Or, for
  861. // Main//default, a placeholder key.
  862. auto import_key = packaging ? GetImportKey(unit_info, IdentifierId::Invalid,
  863. packaging->names)
  864. // Construct a boring key for Main//default.
  865. : ImportKey{"", ""};
  866. // Diagnose explicit `Main` uses before they become marked as possible
  867. // APIs.
  868. if (import_key.first == ExplicitMainName) {
  869. CARBON_DIAGNOSTIC(ExplicitMainPackage, Error,
  870. "`Main//default` must omit `package` declaration.");
  871. CARBON_DIAGNOSTIC(
  872. ExplicitMainLibrary, Error,
  873. "Use `library` declaration in `Main` package libraries.");
  874. unit_info.emitter.Emit(packaging->names.node_id,
  875. import_key.second.empty() ? ExplicitMainPackage
  876. : ExplicitMainLibrary);
  877. continue;
  878. }
  879. bool is_impl = packaging && packaging->is_impl;
  880. // Add to the `api` map and diagnose duplicates. This occurs before the
  881. // file extension check because we might emit both diagnostics in situations
  882. // where the user forgets (or has syntax errors with) a package line
  883. // multiple times.
  884. if (!is_impl) {
  885. auto [entry, success] = api_map.insert({import_key, &unit_info});
  886. if (!success) {
  887. llvm::StringRef prev_filename =
  888. entry->second->unit->tokens->source().filename();
  889. if (packaging) {
  890. CARBON_DIAGNOSTIC(DuplicateLibraryApi, Error,
  891. "Library's API previously provided by `{0}`.",
  892. std::string);
  893. unit_info.emitter.Emit(packaging->names.node_id, DuplicateLibraryApi,
  894. prev_filename.str());
  895. } else {
  896. CARBON_DIAGNOSTIC(DuplicateMainApi, Error,
  897. "Main//default previously provided by `{0}`.",
  898. std::string);
  899. // Use the invalid node because there's no node to associate with.
  900. unit_info.emitter.Emit(Parse::NodeId::Invalid, DuplicateMainApi,
  901. prev_filename.str());
  902. }
  903. }
  904. }
  905. // Validate file extensions. Note imports rely the packaging declaration,
  906. // not the extension. If the input is not a regular file, for example
  907. // because it is stdin, no filename checking is performed.
  908. if (unit_info.unit->tokens->source().is_regular_file()) {
  909. auto filename = unit_info.unit->tokens->source().filename();
  910. static constexpr llvm::StringLiteral ApiExt = ".carbon";
  911. static constexpr llvm::StringLiteral ImplExt = ".impl.carbon";
  912. bool is_api_with_impl_ext = !is_impl && filename.ends_with(ImplExt);
  913. auto want_ext = is_impl ? ImplExt : ApiExt;
  914. if (is_api_with_impl_ext || !filename.ends_with(want_ext)) {
  915. CARBON_DIAGNOSTIC(IncorrectExtension, Error,
  916. "File extension of `{0}` required for `{1}`.",
  917. llvm::StringLiteral, Lex::TokenKind);
  918. auto diag = unit_info.emitter.Build(
  919. packaging ? packaging->names.node_id : Parse::NodeId::Invalid,
  920. IncorrectExtension, want_ext,
  921. is_impl ? Lex::TokenKind::Impl : Lex::TokenKind::Api);
  922. if (is_api_with_impl_ext) {
  923. CARBON_DIAGNOSTIC(IncorrectExtensionImplNote, Note,
  924. "File extension of `{0}` only allowed for `{1}`.",
  925. llvm::StringLiteral, Lex::TokenKind);
  926. diag.Note(Parse::NodeId::Invalid, IncorrectExtensionImplNote, ImplExt,
  927. Lex::TokenKind::Impl);
  928. }
  929. diag.Emit();
  930. }
  931. }
  932. }
  933. return api_map;
  934. }
  935. auto CheckParseTrees(llvm::MutableArrayRef<Unit> units, bool prelude_import,
  936. llvm::raw_ostream* vlog_stream) -> void {
  937. // Prepare diagnostic emitters in case we run into issues during package
  938. // checking.
  939. //
  940. // UnitInfo is big due to its SmallVectors, so we default to 0 on the stack.
  941. llvm::SmallVector<UnitInfo, 0> unit_infos;
  942. unit_infos.reserve(units.size());
  943. llvm::SmallVector<Parse::NodeLocConverter*> node_converters;
  944. node_converters.reserve(units.size());
  945. for (auto [i, unit] : llvm::enumerate(units)) {
  946. unit_infos.emplace_back(SemIR::CheckIRId(i), unit);
  947. node_converters.push_back(&unit_infos.back().converter);
  948. }
  949. llvm::DenseMap<ImportKey, UnitInfo*> api_map =
  950. BuildApiMapAndDiagnosePackaging(unit_infos);
  951. // Mark down imports for all files.
  952. llvm::SmallVector<UnitInfo*> ready_to_check;
  953. ready_to_check.reserve(units.size());
  954. for (auto& unit_info : unit_infos) {
  955. const auto& packaging = unit_info.unit->parse_tree->packaging_decl();
  956. if (packaging && packaging->is_impl) {
  957. // An `impl` has an implicit import of its `api`.
  958. auto implicit_names = packaging->names;
  959. implicit_names.package_id = IdentifierId::Invalid;
  960. TrackImport(api_map, nullptr, unit_info, implicit_names);
  961. }
  962. llvm::DenseMap<ImportKey, Parse::NodeId> explicit_import_map;
  963. // Add the prelude import. It's added to explicit_import_map so that it can
  964. // conflict with an explicit import of the prelude.
  965. // TODO: Add --no-prelude-import for `/no_prelude/` subdirs.
  966. IdentifierId core_ident_id =
  967. unit_info.unit->value_stores->identifiers().Add("Core");
  968. if (prelude_import &&
  969. !(packaging && packaging->names.package_id == core_ident_id)) {
  970. auto prelude_id =
  971. unit_info.unit->value_stores->string_literal_values().Add("prelude");
  972. TrackImport(api_map, &explicit_import_map, unit_info,
  973. {.node_id = Parse::InvalidNodeId(),
  974. .package_id = core_ident_id,
  975. .library_id = prelude_id});
  976. }
  977. for (const auto& import : unit_info.unit->parse_tree->imports()) {
  978. TrackImport(api_map, &explicit_import_map, unit_info, import);
  979. }
  980. // If there were no imports, mark the file as ready to check for below.
  981. if (unit_info.imports_remaining == 0) {
  982. ready_to_check.push_back(&unit_info);
  983. }
  984. }
  985. // Check everything with no dependencies. Earlier entries with dependencies
  986. // will be checked as soon as all their dependencies have been checked.
  987. for (int check_index = 0;
  988. check_index < static_cast<int>(ready_to_check.size()); ++check_index) {
  989. auto* unit_info = ready_to_check[check_index];
  990. CheckParseTree(node_converters, *unit_info, units.size(), vlog_stream);
  991. for (auto* incoming_import : unit_info->incoming_imports) {
  992. --incoming_import->imports_remaining;
  993. if (incoming_import->imports_remaining == 0) {
  994. ready_to_check.push_back(incoming_import);
  995. }
  996. }
  997. }
  998. // If there are still units with remaining imports, it means there's a
  999. // dependency loop.
  1000. if (ready_to_check.size() < unit_infos.size()) {
  1001. // Go through units and mask out unevaluated imports. This breaks everything
  1002. // associated with a loop equivalently, whether it's part of it or depending
  1003. // on a part of it.
  1004. // TODO: Better identify cycles, maybe try to untangle them.
  1005. for (auto& unit_info : unit_infos) {
  1006. if (unit_info.imports_remaining > 0) {
  1007. for (auto& package_imports : unit_info.package_imports) {
  1008. for (auto* import_it = package_imports.imports.begin();
  1009. import_it != package_imports.imports.end();) {
  1010. if (*import_it->unit_info->unit->sem_ir) {
  1011. // The import is checked, so continue.
  1012. ++import_it;
  1013. } else {
  1014. // The import hasn't been checked, indicating a cycle.
  1015. CARBON_DIAGNOSTIC(ImportCycleDetected, Error,
  1016. "Import cannot be used due to a cycle. Cycle "
  1017. "must be fixed to import.");
  1018. unit_info.emitter.Emit(import_it->names.node_id,
  1019. ImportCycleDetected);
  1020. // Make this look the same as an import which wasn't found.
  1021. package_imports.has_load_error = true;
  1022. if (unit_info.api_for_impl == import_it->unit_info) {
  1023. unit_info.api_for_impl = nullptr;
  1024. }
  1025. import_it = package_imports.imports.erase(import_it);
  1026. }
  1027. }
  1028. }
  1029. }
  1030. }
  1031. // Check the remaining file contents, which are probably broken due to
  1032. // incomplete imports.
  1033. for (auto& unit_info : unit_infos) {
  1034. if (unit_info.imports_remaining > 0) {
  1035. CheckParseTree(node_converters, unit_info, units.size(), vlog_stream);
  1036. }
  1037. }
  1038. }
  1039. }
  1040. } // namespace Carbon::Check