check.cpp 46 KB

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