check.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  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 = !packaging || packaging->is_impl;
  848. unit_info.emitter.Emit(import.node_id,
  849. is_impl ? ExplicitImportApi : ImportSelf);
  850. return;
  851. }
  852. // Diagnose explicit imports of `Main//default`. There is no `api` for it.
  853. // This lets other diagnostics handle explicit `Main` package naming.
  854. if (is_file_implicit_main && is_import_implicit_current_package &&
  855. is_import_default_library) {
  856. CARBON_DIAGNOSTIC(ImportMainDefaultLibrary, Error,
  857. "Cannot import `Main//default`.");
  858. unit_info.emitter.Emit(import.node_id, ImportMainDefaultLibrary);
  859. return;
  860. }
  861. if (!is_import_implicit_current_package) {
  862. // Diagnose explicit imports of the same package that use the package
  863. // name.
  864. if (is_same_package || (is_file_implicit_main && is_explicit_main)) {
  865. CARBON_DIAGNOSTIC(
  866. ImportCurrentPackageByName, Error,
  867. "Imports from the current package must omit the package name.");
  868. unit_info.emitter.Emit(import.node_id, ImportCurrentPackageByName);
  869. return;
  870. }
  871. // Diagnose explicit imports from `Main`.
  872. if (is_explicit_main) {
  873. CARBON_DIAGNOSTIC(ImportMainPackage, Error,
  874. "Cannot import `Main` from other packages.");
  875. unit_info.emitter.Emit(import.node_id, ImportMainPackage);
  876. return;
  877. }
  878. }
  879. } else if (is_explicit_main) {
  880. // An implicit import with an explicit `Main` occurs when a `package` rule
  881. // has bad syntax, which will have been diagnosed when building the API map.
  882. // As a consequence, we return silently.
  883. return;
  884. }
  885. // Get the package imports, or create them if this is the first.
  886. auto [package_imports_map_it, is_inserted] =
  887. unit_info.package_imports_map.insert(
  888. {import.package_id, unit_info.package_imports.size()});
  889. if (is_inserted) {
  890. unit_info.package_imports.push_back(
  891. UnitInfo::PackageImports(import.package_id, import.node_id));
  892. }
  893. UnitInfo::PackageImports& package_imports =
  894. unit_info.package_imports[package_imports_map_it->second];
  895. if (auto api = api_map.find(import_key); api != api_map.end()) {
  896. // Add references between the file and imported api.
  897. package_imports.imports.push_back({import, api->second});
  898. ++unit_info.imports_remaining;
  899. api->second->incoming_imports.push_back(&unit_info);
  900. // If this is the implicit import, note we have it.
  901. if (!explicit_import_map) {
  902. CARBON_CHECK(!unit_info.api_for_impl);
  903. unit_info.api_for_impl = api->second;
  904. }
  905. } else {
  906. // The imported api is missing.
  907. package_imports.has_load_error = true;
  908. CARBON_DIAGNOSTIC(LibraryApiNotFound, Error,
  909. "Corresponding API for '{0}' not found.", std::string);
  910. CARBON_DIAGNOSTIC(ImportNotFound, Error, "Imported API '{0}' not found.",
  911. std::string);
  912. unit_info.emitter.Emit(
  913. import.node_id,
  914. explicit_import_map ? ImportNotFound : LibraryApiNotFound,
  915. RenderImportKey(import_key));
  916. }
  917. }
  918. // Builds a map of `api` files which might be imported. Also diagnoses issues
  919. // related to the packaging because the strings are loaded as part of getting
  920. // the ImportKey (which we then do for `impl` files too).
  921. static auto BuildApiMapAndDiagnosePackaging(
  922. llvm::SmallVector<UnitInfo, 0>& unit_infos)
  923. -> llvm::DenseMap<ImportKey, UnitInfo*> {
  924. llvm::DenseMap<ImportKey, UnitInfo*> api_map;
  925. for (auto& unit_info : unit_infos) {
  926. const auto& packaging = unit_info.unit->parse_tree->packaging_decl();
  927. // An import key formed from the `package` or `library` declaration. Or, for
  928. // Main//default, a placeholder key.
  929. auto import_key = packaging ? GetImportKey(unit_info, IdentifierId::Invalid,
  930. packaging->names)
  931. // Construct a boring key for Main//default.
  932. : ImportKey{"", ""};
  933. // Diagnose explicit `Main` uses before they become marked as possible
  934. // APIs.
  935. if (import_key.first == ExplicitMainName) {
  936. CARBON_DIAGNOSTIC(ExplicitMainPackage, Error,
  937. "`Main//default` must omit `package` declaration.");
  938. CARBON_DIAGNOSTIC(
  939. ExplicitMainLibrary, Error,
  940. "Use `library` declaration in `Main` package libraries.");
  941. unit_info.emitter.Emit(packaging->names.node_id,
  942. import_key.second.empty() ? ExplicitMainPackage
  943. : ExplicitMainLibrary);
  944. continue;
  945. }
  946. bool is_impl = packaging && packaging->is_impl;
  947. // Add to the `api` map and diagnose duplicates. This occurs before the
  948. // file extension check because we might emit both diagnostics in situations
  949. // where the user forgets (or has syntax errors with) a package line
  950. // multiple times.
  951. if (!is_impl) {
  952. auto [entry, success] = api_map.insert({import_key, &unit_info});
  953. if (!success) {
  954. llvm::StringRef prev_filename =
  955. entry->second->unit->tokens->source().filename();
  956. if (packaging) {
  957. CARBON_DIAGNOSTIC(DuplicateLibraryApi, Error,
  958. "Library's API previously provided by `{0}`.",
  959. std::string);
  960. unit_info.emitter.Emit(packaging->names.node_id, DuplicateLibraryApi,
  961. prev_filename.str());
  962. } else {
  963. CARBON_DIAGNOSTIC(DuplicateMainApi, Error,
  964. "Main//default previously provided by `{0}`.",
  965. std::string);
  966. // Use the invalid node because there's no node to associate with.
  967. unit_info.emitter.Emit(Parse::NodeId::Invalid, DuplicateMainApi,
  968. prev_filename.str());
  969. }
  970. }
  971. }
  972. // Validate file extensions. Note imports rely the packaging declaration,
  973. // not the extension. If the input is not a regular file, for example
  974. // because it is stdin, no filename checking is performed.
  975. if (unit_info.unit->tokens->source().is_regular_file()) {
  976. auto filename = unit_info.unit->tokens->source().filename();
  977. static constexpr llvm::StringLiteral ApiExt = ".carbon";
  978. static constexpr llvm::StringLiteral ImplExt = ".impl.carbon";
  979. bool is_api_with_impl_ext = !is_impl && filename.ends_with(ImplExt);
  980. auto want_ext = is_impl ? ImplExt : ApiExt;
  981. if (is_api_with_impl_ext || !filename.ends_with(want_ext)) {
  982. CARBON_DIAGNOSTIC(IncorrectExtension, Error,
  983. "File extension of `{0}` required for `{1}`.",
  984. llvm::StringLiteral, Lex::TokenKind);
  985. auto diag = unit_info.emitter.Build(
  986. packaging ? packaging->names.node_id : Parse::NodeId::Invalid,
  987. IncorrectExtension, want_ext,
  988. is_impl ? Lex::TokenKind::Impl : Lex::TokenKind::Api);
  989. if (is_api_with_impl_ext) {
  990. CARBON_DIAGNOSTIC(IncorrectExtensionImplNote, Note,
  991. "File extension of `{0}` only allowed for `{1}`.",
  992. llvm::StringLiteral, Lex::TokenKind);
  993. diag.Note(Parse::NodeId::Invalid, IncorrectExtensionImplNote, ImplExt,
  994. Lex::TokenKind::Impl);
  995. }
  996. diag.Emit();
  997. }
  998. }
  999. }
  1000. return api_map;
  1001. }
  1002. auto CheckParseTrees(llvm::MutableArrayRef<Unit> units, bool prelude_import,
  1003. llvm::raw_ostream* vlog_stream) -> void {
  1004. // Prepare diagnostic emitters in case we run into issues during package
  1005. // checking.
  1006. //
  1007. // UnitInfo is big due to its SmallVectors, so we default to 0 on the stack.
  1008. llvm::SmallVector<UnitInfo, 0> unit_infos;
  1009. unit_infos.reserve(units.size());
  1010. for (auto [i, unit] : llvm::enumerate(units)) {
  1011. unit_infos.emplace_back(SemIR::CheckIRId(i), unit);
  1012. }
  1013. llvm::DenseMap<ImportKey, UnitInfo*> api_map =
  1014. BuildApiMapAndDiagnosePackaging(unit_infos);
  1015. // Mark down imports for all files.
  1016. llvm::SmallVector<UnitInfo*> ready_to_check;
  1017. ready_to_check.reserve(units.size());
  1018. for (auto& unit_info : unit_infos) {
  1019. const auto& packaging = unit_info.unit->parse_tree->packaging_decl();
  1020. if (packaging && packaging->is_impl) {
  1021. // An `impl` has an implicit import of its `api`.
  1022. auto implicit_names = packaging->names;
  1023. implicit_names.package_id = IdentifierId::Invalid;
  1024. TrackImport(api_map, nullptr, unit_info, implicit_names);
  1025. }
  1026. llvm::DenseMap<ImportKey, Parse::NodeId> explicit_import_map;
  1027. // Add the prelude import. It's added to explicit_import_map so that it can
  1028. // conflict with an explicit import of the prelude.
  1029. // TODO: Add --no-prelude-import for `/no_prelude/` subdirs.
  1030. IdentifierId core_ident_id =
  1031. unit_info.unit->value_stores->identifiers().Add("Core");
  1032. if (prelude_import &&
  1033. !(packaging && packaging->names.package_id == core_ident_id)) {
  1034. auto prelude_id =
  1035. unit_info.unit->value_stores->string_literal_values().Add("prelude");
  1036. TrackImport(api_map, &explicit_import_map, unit_info,
  1037. {.node_id = Parse::InvalidNodeId(),
  1038. .package_id = core_ident_id,
  1039. .library_id = prelude_id});
  1040. }
  1041. for (const auto& import : unit_info.unit->parse_tree->imports()) {
  1042. TrackImport(api_map, &explicit_import_map, unit_info, import);
  1043. }
  1044. // If there were no imports, mark the file as ready to check for below.
  1045. if (unit_info.imports_remaining == 0) {
  1046. ready_to_check.push_back(&unit_info);
  1047. }
  1048. }
  1049. llvm::DenseMap<const SemIR::File*, Parse::NodeLocConverter*> node_converters;
  1050. // Check everything with no dependencies. Earlier entries with dependencies
  1051. // will be checked as soon as all their dependencies have been checked.
  1052. for (int check_index = 0;
  1053. check_index < static_cast<int>(ready_to_check.size()); ++check_index) {
  1054. auto* unit_info = ready_to_check[check_index];
  1055. CheckParseTree(&node_converters, *unit_info, units.size(), vlog_stream);
  1056. for (auto* incoming_import : unit_info->incoming_imports) {
  1057. --incoming_import->imports_remaining;
  1058. if (incoming_import->imports_remaining == 0) {
  1059. ready_to_check.push_back(incoming_import);
  1060. }
  1061. }
  1062. }
  1063. // If there are still units with remaining imports, it means there's a
  1064. // dependency loop.
  1065. if (ready_to_check.size() < unit_infos.size()) {
  1066. // Go through units and mask out unevaluated imports. This breaks everything
  1067. // associated with a loop equivalently, whether it's part of it or depending
  1068. // on a part of it.
  1069. // TODO: Better identify cycles, maybe try to untangle them.
  1070. for (auto& unit_info : unit_infos) {
  1071. if (unit_info.imports_remaining > 0) {
  1072. for (auto& package_imports : unit_info.package_imports) {
  1073. for (auto* import_it = package_imports.imports.begin();
  1074. import_it != package_imports.imports.end();) {
  1075. if (*import_it->unit_info->unit->sem_ir) {
  1076. // The import is checked, so continue.
  1077. ++import_it;
  1078. } else {
  1079. // The import hasn't been checked, indicating a cycle.
  1080. CARBON_DIAGNOSTIC(ImportCycleDetected, Error,
  1081. "Import cannot be used due to a cycle. Cycle "
  1082. "must be fixed to import.");
  1083. unit_info.emitter.Emit(import_it->names.node_id,
  1084. ImportCycleDetected);
  1085. // Make this look the same as an import which wasn't found.
  1086. package_imports.has_load_error = true;
  1087. if (unit_info.api_for_impl == import_it->unit_info) {
  1088. unit_info.api_for_impl = nullptr;
  1089. }
  1090. import_it = package_imports.imports.erase(import_it);
  1091. }
  1092. }
  1093. }
  1094. }
  1095. }
  1096. // Check the remaining file contents, which are probably broken due to
  1097. // incomplete imports.
  1098. for (auto& unit_info : unit_infos) {
  1099. if (unit_info.imports_remaining > 0) {
  1100. CheckParseTree(&node_converters, unit_info, units.size(), vlog_stream);
  1101. }
  1102. }
  1103. }
  1104. }
  1105. } // namespace Carbon::Check