check.cpp 52 KB

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