check.cpp 45 KB

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