check.cpp 46 KB

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