check.cpp 53 KB

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