check.cpp 49 KB

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