check.cpp 46 KB

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