check.cpp 49 KB

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