check.cpp 51 KB

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