check.cpp 52 KB

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