check.cpp 49 KB

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