check.cpp 53 KB

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