check.cpp 49 KB

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