check.cpp 52 KB

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