context.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572
  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/context.h"
  5. #include <optional>
  6. #include <string>
  7. #include <utility>
  8. #include "common/check.h"
  9. #include "common/vlog.h"
  10. #include "llvm/ADT/Sequence.h"
  11. #include "toolchain/base/kind_switch.h"
  12. #include "toolchain/check/decl_name_stack.h"
  13. #include "toolchain/check/eval.h"
  14. #include "toolchain/check/generic.h"
  15. #include "toolchain/check/generic_region_stack.h"
  16. #include "toolchain/check/import.h"
  17. #include "toolchain/check/import_ref.h"
  18. #include "toolchain/check/inst_block_stack.h"
  19. #include "toolchain/check/merge.h"
  20. #include "toolchain/diagnostics/diagnostic_emitter.h"
  21. #include "toolchain/diagnostics/format_providers.h"
  22. #include "toolchain/lex/tokenized_buffer.h"
  23. #include "toolchain/parse/node_ids.h"
  24. #include "toolchain/parse/node_kind.h"
  25. #include "toolchain/sem_ir/file.h"
  26. #include "toolchain/sem_ir/formatter.h"
  27. #include "toolchain/sem_ir/generic.h"
  28. #include "toolchain/sem_ir/ids.h"
  29. #include "toolchain/sem_ir/import_ir.h"
  30. #include "toolchain/sem_ir/inst.h"
  31. #include "toolchain/sem_ir/inst_kind.h"
  32. #include "toolchain/sem_ir/name_scope.h"
  33. #include "toolchain/sem_ir/type_info.h"
  34. #include "toolchain/sem_ir/typed_insts.h"
  35. namespace Carbon::Check {
  36. Context::Context(DiagnosticEmitter* emitter,
  37. llvm::function_ref<const Parse::TreeAndSubtrees&()>
  38. get_parse_tree_and_subtrees,
  39. SemIR::File* sem_ir, int imported_ir_count, int total_ir_count,
  40. llvm::raw_ostream* vlog_stream)
  41. : emitter_(emitter),
  42. get_parse_tree_and_subtrees_(get_parse_tree_and_subtrees),
  43. sem_ir_(sem_ir),
  44. vlog_stream_(vlog_stream),
  45. node_stack_(sem_ir->parse_tree(), vlog_stream),
  46. inst_block_stack_("inst_block_stack_", *sem_ir, vlog_stream),
  47. pattern_block_stack_("pattern_block_stack_", *sem_ir, vlog_stream),
  48. param_and_arg_refs_stack_(*sem_ir, vlog_stream, node_stack_),
  49. args_type_info_stack_("args_type_info_stack_", *sem_ir, vlog_stream),
  50. decl_name_stack_(this),
  51. scope_stack_(sem_ir_->identifiers()),
  52. global_init_(this) {
  53. // Prepare fields which relate to the number of IRs available for import.
  54. import_irs().Reserve(imported_ir_count);
  55. import_ir_constant_values_.reserve(imported_ir_count);
  56. check_ir_map_.resize(total_ir_count, SemIR::ImportIRId::Invalid);
  57. // Map the builtin `<error>` and `type` type constants to their corresponding
  58. // special `TypeId` values.
  59. type_ids_for_type_constants_.Insert(
  60. SemIR::ConstantId::ForTemplateConstant(SemIR::ErrorInst::SingletonInstId),
  61. SemIR::ErrorInst::SingletonTypeId);
  62. type_ids_for_type_constants_.Insert(
  63. SemIR::ConstantId::ForTemplateConstant(SemIR::TypeType::SingletonInstId),
  64. SemIR::TypeType::SingletonTypeId);
  65. // TODO: Remove this and add a `VerifyOnFinish` once we properly push and pop
  66. // in the right places.
  67. generic_region_stack().Push();
  68. }
  69. auto Context::TODO(SemIRLoc loc, std::string label) -> bool {
  70. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "semantics TODO: `{0}`", std::string);
  71. emitter_->Emit(loc, SemanticsTodo, std::move(label));
  72. return false;
  73. }
  74. auto Context::VerifyOnFinish() -> void {
  75. // Information in all the various context objects should be cleaned up as
  76. // various pieces of context go out of scope. At this point, nothing should
  77. // remain.
  78. // node_stack_ will still contain top-level entities.
  79. inst_block_stack_.VerifyOnFinish();
  80. pattern_block_stack_.VerifyOnFinish();
  81. param_and_arg_refs_stack_.VerifyOnFinish();
  82. args_type_info_stack_.VerifyOnFinish();
  83. CARBON_CHECK(struct_type_fields_stack_.empty());
  84. // TODO: Add verification for decl_name_stack_ and
  85. // decl_introducer_state_stack_.
  86. scope_stack_.VerifyOnFinish();
  87. // TODO: Add verification for generic_region_stack_.
  88. }
  89. auto Context::GetOrAddInst(SemIR::LocIdAndInst loc_id_and_inst)
  90. -> SemIR::InstId {
  91. if (loc_id_and_inst.loc_id.is_implicit()) {
  92. auto const_id =
  93. TryEvalInst(*this, SemIR::InstId::Invalid, loc_id_and_inst.inst);
  94. if (const_id.is_valid()) {
  95. CARBON_VLOG("GetOrAddInst: constant: {0}\n", loc_id_and_inst.inst);
  96. return constant_values().GetInstId(const_id);
  97. }
  98. }
  99. // TODO: For an implicit instruction, this reattempts evaluation.
  100. return AddInst(loc_id_and_inst);
  101. }
  102. // Finish producing an instruction. Set its constant value, and register it in
  103. // any applicable instruction lists.
  104. auto Context::FinishInst(SemIR::InstId inst_id, SemIR::Inst inst) -> void {
  105. GenericRegionStack::DependencyKind dep_kind =
  106. GenericRegionStack::DependencyKind::None;
  107. // If the instruction has a symbolic constant type, track that we need to
  108. // substitute into it.
  109. if (constant_values().DependsOnGenericParameter(
  110. types().GetConstantId(inst.type_id()))) {
  111. dep_kind |= GenericRegionStack::DependencyKind::SymbolicType;
  112. }
  113. // If the instruction has a constant value, compute it.
  114. auto const_id = TryEvalInst(*this, inst_id, inst);
  115. constant_values().Set(inst_id, const_id);
  116. if (const_id.is_constant()) {
  117. CARBON_VLOG("Constant: {0} -> {1}\n", inst,
  118. constant_values().GetInstId(const_id));
  119. // If the constant value is symbolic, track that we need to substitute into
  120. // it.
  121. if (constant_values().DependsOnGenericParameter(const_id)) {
  122. dep_kind |= GenericRegionStack::DependencyKind::SymbolicConstant;
  123. }
  124. }
  125. // Keep track of dependent instructions.
  126. if (dep_kind != GenericRegionStack::DependencyKind::None) {
  127. // TODO: Also check for template-dependent instructions.
  128. generic_region_stack().AddDependentInst(
  129. {.inst_id = inst_id, .kind = dep_kind});
  130. }
  131. }
  132. // Returns whether a parse node associated with an imported instruction of kind
  133. // `imported_kind` is usable as the location of a corresponding local
  134. // instruction of kind `local_kind`.
  135. static auto HasCompatibleImportedNodeKind(SemIR::InstKind imported_kind,
  136. SemIR::InstKind local_kind) -> bool {
  137. if (imported_kind == local_kind) {
  138. return true;
  139. }
  140. if (imported_kind == SemIR::ImportDecl::Kind &&
  141. local_kind == SemIR::Namespace::Kind) {
  142. static_assert(
  143. std::is_convertible_v<decltype(SemIR::ImportDecl::Kind)::TypedNodeId,
  144. decltype(SemIR::Namespace::Kind)::TypedNodeId>);
  145. return true;
  146. }
  147. return false;
  148. }
  149. auto Context::CheckCompatibleImportedNodeKind(
  150. SemIR::ImportIRInstId imported_loc_id, SemIR::InstKind kind) -> void {
  151. auto& import_ir_inst = import_ir_insts().Get(imported_loc_id);
  152. const auto* import_ir = import_irs().Get(import_ir_inst.ir_id).sem_ir;
  153. auto imported_kind = import_ir->insts().Get(import_ir_inst.inst_id).kind();
  154. CARBON_CHECK(
  155. HasCompatibleImportedNodeKind(imported_kind, kind),
  156. "Node of kind {0} created with location of imported node of kind {1}",
  157. kind, imported_kind);
  158. }
  159. auto Context::AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst)
  160. -> SemIR::InstId {
  161. auto inst_id = sem_ir().insts().AddInNoBlock(loc_id_and_inst);
  162. CARBON_VLOG("AddPlaceholderInst: {0}\n", loc_id_and_inst.inst);
  163. constant_values().Set(inst_id, SemIR::ConstantId::Invalid);
  164. return inst_id;
  165. }
  166. auto Context::AddPlaceholderInst(SemIR::LocIdAndInst loc_id_and_inst)
  167. -> SemIR::InstId {
  168. auto inst_id = AddPlaceholderInstInNoBlock(loc_id_and_inst);
  169. inst_block_stack_.AddInstId(inst_id);
  170. return inst_id;
  171. }
  172. auto Context::ReplaceLocIdAndInstBeforeConstantUse(
  173. SemIR::InstId inst_id, SemIR::LocIdAndInst loc_id_and_inst) -> void {
  174. sem_ir().insts().SetLocIdAndInst(inst_id, loc_id_and_inst);
  175. CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, loc_id_and_inst.inst);
  176. FinishInst(inst_id, loc_id_and_inst.inst);
  177. }
  178. auto Context::ReplaceInstBeforeConstantUse(SemIR::InstId inst_id,
  179. SemIR::Inst inst) -> void {
  180. sem_ir().insts().Set(inst_id, inst);
  181. CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, inst);
  182. FinishInst(inst_id, inst);
  183. }
  184. auto Context::ReplaceInstPreservingConstantValue(SemIR::InstId inst_id,
  185. SemIR::Inst inst) -> void {
  186. auto old_const_id = sem_ir().constant_values().Get(inst_id);
  187. sem_ir().insts().Set(inst_id, inst);
  188. CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, inst);
  189. auto new_const_id = TryEvalInst(*this, inst_id, inst);
  190. CARBON_CHECK(old_const_id == new_const_id);
  191. }
  192. auto Context::DiagnoseDuplicateName(SemIRLoc dup_def, SemIRLoc prev_def)
  193. -> void {
  194. CARBON_DIAGNOSTIC(NameDeclDuplicate, Error,
  195. "duplicate name being declared in the same scope");
  196. CARBON_DIAGNOSTIC(NameDeclPrevious, Note, "name is previously declared here");
  197. emitter_->Build(dup_def, NameDeclDuplicate)
  198. .Note(prev_def, NameDeclPrevious)
  199. .Emit();
  200. }
  201. auto Context::DiagnosePoisonedName(SemIRLoc loc) -> void {
  202. // TODO: Improve the diagnostic to replace NodeId::Invalid with the location
  203. // where the name was poisoned. See discussion in
  204. // https://github.com/carbon-language/carbon-lang/pull/4654#discussion_r1876607172
  205. CARBON_DIAGNOSTIC(NameUseBeforeDecl, Error,
  206. "name used before it was declared");
  207. CARBON_DIAGNOSTIC(NameUseBeforeDeclNote, Note, "declared here");
  208. emitter_->Build(SemIR::LocId::Invalid, NameUseBeforeDecl)
  209. .Note(loc, NameUseBeforeDeclNote)
  210. .Emit();
  211. }
  212. auto Context::DiagnoseNameNotFound(SemIRLoc loc, SemIR::NameId name_id)
  213. -> void {
  214. CARBON_DIAGNOSTIC(NameNotFound, Error, "name `{0}` not found", SemIR::NameId);
  215. emitter_->Emit(loc, NameNotFound, name_id);
  216. }
  217. auto Context::DiagnoseMemberNameNotFound(
  218. SemIRLoc loc, SemIR::NameId name_id,
  219. llvm::ArrayRef<LookupScope> lookup_scopes) -> void {
  220. if (lookup_scopes.size() == 1 &&
  221. lookup_scopes.front().name_scope_id.is_valid()) {
  222. auto specific_id = lookup_scopes.front().specific_id;
  223. auto scope_inst_id =
  224. specific_id.is_valid()
  225. ? GetInstForSpecific(*this, specific_id)
  226. : name_scopes().Get(lookup_scopes.front().name_scope_id).inst_id();
  227. CARBON_DIAGNOSTIC(MemberNameNotFoundInScope, Error,
  228. "member name `{0}` not found in {1}", SemIR::NameId,
  229. InstIdAsType);
  230. emitter_->Emit(loc, MemberNameNotFoundInScope, name_id, scope_inst_id);
  231. return;
  232. }
  233. CARBON_DIAGNOSTIC(MemberNameNotFound, Error, "member name `{0}` not found",
  234. SemIR::NameId);
  235. emitter_->Emit(loc, MemberNameNotFound, name_id);
  236. }
  237. auto Context::NoteAbstractClass(SemIR::ClassId class_id,
  238. DiagnosticBuilder& builder) -> void {
  239. const auto& class_info = classes().Get(class_id);
  240. CARBON_CHECK(
  241. class_info.inheritance_kind == SemIR::Class::InheritanceKind::Abstract,
  242. "Class is not abstract");
  243. CARBON_DIAGNOSTIC(ClassAbstractHere, Note,
  244. "class was declared abstract here");
  245. builder.Note(class_info.definition_id, ClassAbstractHere);
  246. }
  247. auto Context::NoteIncompleteClass(SemIR::ClassId class_id,
  248. DiagnosticBuilder& builder) -> void {
  249. const auto& class_info = classes().Get(class_id);
  250. CARBON_CHECK(!class_info.is_defined(), "Class is not incomplete");
  251. if (class_info.has_definition_started()) {
  252. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Note,
  253. "class is incomplete within its definition");
  254. builder.Note(class_info.definition_id, ClassIncompleteWithinDefinition);
  255. } else {
  256. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  257. "class was forward declared here");
  258. builder.Note(class_info.latest_decl_id(), ClassForwardDeclaredHere);
  259. }
  260. }
  261. auto Context::NoteUndefinedInterface(SemIR::InterfaceId interface_id,
  262. DiagnosticBuilder& builder) -> void {
  263. const auto& interface_info = interfaces().Get(interface_id);
  264. CARBON_CHECK(!interface_info.is_defined(), "Interface is not incomplete");
  265. if (interface_info.is_being_defined()) {
  266. CARBON_DIAGNOSTIC(InterfaceUndefinedWithinDefinition, Note,
  267. "interface is currently being defined");
  268. builder.Note(interface_info.definition_id,
  269. InterfaceUndefinedWithinDefinition);
  270. } else {
  271. CARBON_DIAGNOSTIC(InterfaceForwardDeclaredHere, Note,
  272. "interface was forward declared here");
  273. builder.Note(interface_info.latest_decl_id(), InterfaceForwardDeclaredHere);
  274. }
  275. }
  276. auto Context::AddNameToLookup(SemIR::NameId name_id, SemIR::InstId target_id)
  277. -> void {
  278. if (auto existing = scope_stack().LookupOrAddName(name_id, target_id);
  279. existing.is_valid()) {
  280. DiagnoseDuplicateName(target_id, existing);
  281. }
  282. }
  283. auto Context::LookupNameInDecl(SemIR::LocId loc_id, SemIR::NameId name_id,
  284. SemIR::NameScopeId scope_id) -> SemIR::InstId {
  285. if (!scope_id.is_valid()) {
  286. // Look for a name in the current scope only. There are two cases where the
  287. // name would be in an outer scope:
  288. //
  289. // - The name is the sole component of the declared name:
  290. //
  291. // class A;
  292. // fn F() {
  293. // class A;
  294. // }
  295. //
  296. // In this case, the inner A is not the same class as the outer A, so
  297. // lookup should not find the outer A.
  298. //
  299. // - The name is a qualifier of some larger declared name:
  300. //
  301. // class A { class B; }
  302. // fn F() {
  303. // class A.B {}
  304. // }
  305. //
  306. // In this case, we're not in the correct scope to define a member of
  307. // class A, so we should reject, and we achieve this by not finding the
  308. // name A from the outer scope.
  309. return scope_stack().LookupInCurrentScope(name_id);
  310. } else {
  311. // We do not look into `extend`ed scopes here. A qualified name in a
  312. // declaration must specify the exact scope in which the name was originally
  313. // introduced:
  314. //
  315. // base class A { fn F(); }
  316. // class B { extend base: A; }
  317. //
  318. // // Error, no `F` in `B`.
  319. // fn B.F() {}
  320. return LookupNameInExactScope(loc_id, name_id, scope_id,
  321. name_scopes().Get(scope_id))
  322. .first;
  323. }
  324. }
  325. auto Context::LookupUnqualifiedName(Parse::NodeId node_id,
  326. SemIR::NameId name_id, bool required)
  327. -> LookupResult {
  328. // TODO: Check for shadowed lookup results.
  329. // Find the results from ancestor lexical scopes. These will be combined with
  330. // results from non-lexical scopes such as namespaces and classes.
  331. auto [lexical_result, non_lexical_scopes] =
  332. scope_stack().LookupInLexicalScopes(name_id);
  333. // Walk the non-lexical scopes and perform lookups into each of them.
  334. // Collect scopes to poison this name when it's found.
  335. llvm::SmallVector<LookupScope> scopes_to_poison;
  336. for (auto [index, lookup_scope_id, specific_id] :
  337. llvm::reverse(non_lexical_scopes)) {
  338. if (auto non_lexical_result =
  339. LookupQualifiedName(node_id, name_id,
  340. LookupScope{.name_scope_id = lookup_scope_id,
  341. .specific_id = specific_id},
  342. /*required=*/false);
  343. !non_lexical_result.inst_id.is_poisoned()) {
  344. if (non_lexical_result.inst_id.is_valid()) {
  345. // Poison the scopes for this name.
  346. for (const auto [scope_id, specific_id] : scopes_to_poison) {
  347. name_scopes().Get(scope_id).AddPoison(name_id);
  348. }
  349. return non_lexical_result;
  350. }
  351. scopes_to_poison.push_back(
  352. {.name_scope_id = lookup_scope_id, .specific_id = specific_id});
  353. }
  354. }
  355. if (lexical_result.is_valid()) {
  356. // A lexical scope never needs an associated specific. If there's a
  357. // lexically enclosing generic, then it also encloses the point of use of
  358. // the name.
  359. return {.specific_id = SemIR::SpecificId::Invalid,
  360. .inst_id = lexical_result};
  361. }
  362. // We didn't find anything at all.
  363. if (required) {
  364. DiagnoseNameNotFound(node_id, name_id);
  365. }
  366. return {.specific_id = SemIR::SpecificId::Invalid,
  367. .inst_id = SemIR::ErrorInst::SingletonInstId};
  368. }
  369. auto Context::LookupNameInExactScope(SemIRLoc loc, SemIR::NameId name_id,
  370. SemIR::NameScopeId scope_id,
  371. const SemIR::NameScope& scope)
  372. -> std::pair<SemIR::InstId, SemIR::AccessKind> {
  373. if (auto entry_id = scope.Lookup(name_id)) {
  374. auto entry = scope.GetEntry(*entry_id);
  375. LoadImportRef(*this, entry.inst_id);
  376. return {entry.inst_id, entry.access_kind};
  377. }
  378. if (!scope.import_ir_scopes().empty()) {
  379. // TODO: Enforce other access modifiers for imports.
  380. return {ImportNameFromOtherPackage(*this, loc, scope_id,
  381. scope.import_ir_scopes(), name_id),
  382. SemIR::AccessKind::Public};
  383. }
  384. return {SemIR::InstId::Invalid, SemIR::AccessKind::Public};
  385. }
  386. // Prints diagnostics on invalid qualified name access.
  387. static auto DiagnoseInvalidQualifiedNameAccess(Context& context, SemIRLoc loc,
  388. SemIR::InstId scope_result_id,
  389. SemIR::NameId name_id,
  390. SemIR::AccessKind access_kind,
  391. bool is_parent_access,
  392. AccessInfo access_info) -> void {
  393. auto class_type = context.insts().TryGetAs<SemIR::ClassType>(
  394. context.constant_values().GetInstId(access_info.constant_id));
  395. if (!class_type) {
  396. return;
  397. }
  398. // TODO: Support scoped entities other than just classes.
  399. const auto& class_info = context.classes().Get(class_type->class_id);
  400. auto parent_type_id = class_info.self_type_id;
  401. if (access_kind == SemIR::AccessKind::Private && is_parent_access) {
  402. if (auto base_type_id =
  403. class_info.GetBaseType(context.sem_ir(), class_type->specific_id);
  404. base_type_id.is_valid()) {
  405. parent_type_id = base_type_id;
  406. } else if (auto adapted_type_id = class_info.GetAdaptedType(
  407. context.sem_ir(), class_type->specific_id);
  408. adapted_type_id.is_valid()) {
  409. parent_type_id = adapted_type_id;
  410. } else {
  411. CARBON_FATAL("Expected parent for parent access");
  412. }
  413. }
  414. CARBON_DIAGNOSTIC(
  415. ClassInvalidMemberAccess, Error,
  416. "cannot access {0:private|protected} member `{1}` of type {2}",
  417. BoolAsSelect, SemIR::NameId, SemIR::TypeId);
  418. CARBON_DIAGNOSTIC(ClassMemberDeclaration, Note, "declared here");
  419. context.emitter()
  420. .Build(loc, ClassInvalidMemberAccess,
  421. access_kind == SemIR::AccessKind::Private, name_id, parent_type_id)
  422. .Note(scope_result_id, ClassMemberDeclaration)
  423. .Emit();
  424. }
  425. // Returns whether the access is prohibited by the access modifiers.
  426. static auto IsAccessProhibited(std::optional<AccessInfo> access_info,
  427. SemIR::AccessKind access_kind,
  428. bool is_parent_access) -> bool {
  429. if (!access_info) {
  430. return false;
  431. }
  432. switch (access_kind) {
  433. case SemIR::AccessKind::Public:
  434. return false;
  435. case SemIR::AccessKind::Protected:
  436. return access_info->highest_allowed_access == SemIR::AccessKind::Public;
  437. case SemIR::AccessKind::Private:
  438. return access_info->highest_allowed_access !=
  439. SemIR::AccessKind::Private ||
  440. is_parent_access;
  441. }
  442. }
  443. // Information regarding a prohibited access.
  444. struct ProhibitedAccessInfo {
  445. // The resulting inst of the lookup.
  446. SemIR::InstId scope_result_id;
  447. // The access kind of the lookup.
  448. SemIR::AccessKind access_kind;
  449. // If the lookup is from an extended scope. For example, if this is a base
  450. // class member access from a class that extends it.
  451. bool is_parent_access;
  452. };
  453. auto Context::AppendLookupScopesForConstant(
  454. SemIR::LocId loc_id, SemIR::ConstantId base_const_id,
  455. llvm::SmallVector<LookupScope>* scopes) -> bool {
  456. auto base_id = constant_values().GetInstId(base_const_id);
  457. auto base = insts().Get(base_id);
  458. if (auto base_as_namespace = base.TryAs<SemIR::Namespace>()) {
  459. scopes->push_back(
  460. LookupScope{.name_scope_id = base_as_namespace->name_scope_id,
  461. .specific_id = SemIR::SpecificId::Invalid});
  462. return true;
  463. }
  464. if (auto base_as_class = base.TryAs<SemIR::ClassType>()) {
  465. RequireDefinedType(GetTypeIdForTypeConstant(base_const_id), loc_id, [&] {
  466. CARBON_DIAGNOSTIC(QualifiedExprInIncompleteClassScope, Error,
  467. "member access into incomplete class {0}",
  468. InstIdAsType);
  469. return emitter().Build(loc_id, QualifiedExprInIncompleteClassScope,
  470. base_id);
  471. });
  472. auto& class_info = classes().Get(base_as_class->class_id);
  473. scopes->push_back(LookupScope{.name_scope_id = class_info.scope_id,
  474. .specific_id = base_as_class->specific_id});
  475. return true;
  476. }
  477. if (auto base_as_facet_type = base.TryAs<SemIR::FacetType>()) {
  478. RequireDefinedType(GetTypeIdForTypeConstant(base_const_id), loc_id, [&] {
  479. CARBON_DIAGNOSTIC(QualifiedExprInUndefinedInterfaceScope, Error,
  480. "member access into undefined interface {0}",
  481. InstIdAsType);
  482. return emitter().Build(loc_id, QualifiedExprInUndefinedInterfaceScope,
  483. base_id);
  484. });
  485. const auto& facet_type_info =
  486. facet_types().Get(base_as_facet_type->facet_type_id);
  487. for (auto interface : facet_type_info.impls_constraints) {
  488. auto& interface_info = interfaces().Get(interface.interface_id);
  489. scopes->push_back(LookupScope{.name_scope_id = interface_info.scope_id,
  490. .specific_id = interface.specific_id});
  491. }
  492. return true;
  493. }
  494. if (base_const_id == SemIR::ErrorInst::SingletonConstantId) {
  495. // Lookup into this scope should fail without producing an error.
  496. scopes->push_back(LookupScope{.name_scope_id = SemIR::NameScopeId::Invalid,
  497. .specific_id = SemIR::SpecificId::Invalid});
  498. return true;
  499. }
  500. // TODO: Per the design, if `base_id` is any kind of type, then lookup should
  501. // treat it as a name scope, even if it doesn't have members. For example,
  502. // `(i32*).X` should fail because there's no name `X` in `i32*`, not because
  503. // there's no name `X` in `type`.
  504. return false;
  505. }
  506. auto Context::LookupQualifiedName(SemIR::LocId loc_id, SemIR::NameId name_id,
  507. llvm::ArrayRef<LookupScope> lookup_scopes,
  508. bool required,
  509. std::optional<AccessInfo> access_info)
  510. -> LookupResult {
  511. llvm::SmallVector<LookupScope> scopes(lookup_scopes);
  512. // TODO: Support reporting of multiple prohibited access.
  513. llvm::SmallVector<ProhibitedAccessInfo> prohibited_accesses;
  514. LookupResult result = {.specific_id = SemIR::SpecificId::Invalid,
  515. .inst_id = SemIR::InstId::Invalid};
  516. bool has_error = false;
  517. bool is_parent_access = false;
  518. // Walk this scope and, if nothing is found here, the scopes it extends.
  519. while (!scopes.empty()) {
  520. auto [scope_id, specific_id] = scopes.pop_back_val();
  521. if (!scope_id.is_valid()) {
  522. has_error = true;
  523. continue;
  524. }
  525. const auto& name_scope = name_scopes().Get(scope_id);
  526. has_error |= name_scope.has_error();
  527. auto [scope_result_id, access_kind] =
  528. LookupNameInExactScope(loc_id, name_id, scope_id, name_scope);
  529. auto is_access_prohibited =
  530. IsAccessProhibited(access_info, access_kind, is_parent_access);
  531. // Keep track of prohibited accesses, this will be useful for reporting
  532. // multiple prohibited accesses if we can't find a suitable lookup.
  533. if (is_access_prohibited) {
  534. prohibited_accesses.push_back({
  535. .scope_result_id = scope_result_id,
  536. .access_kind = access_kind,
  537. .is_parent_access = is_parent_access,
  538. });
  539. }
  540. if (!scope_result_id.is_valid() || is_access_prohibited) {
  541. // If nothing is found in this scope or if we encountered an invalid
  542. // access, look in its extended scopes.
  543. const auto& extended = name_scope.extended_scopes();
  544. scopes.reserve(scopes.size() + extended.size());
  545. for (auto extended_id : llvm::reverse(extended)) {
  546. // Substitute into the constant describing the extended scope to
  547. // determine its corresponding specific.
  548. CARBON_CHECK(extended_id.is_valid());
  549. LoadImportRef(*this, extended_id);
  550. SemIR::ConstantId const_id =
  551. GetConstantValueInSpecific(sem_ir(), specific_id, extended_id);
  552. DiagnosticAnnotationScope annotate_diagnostics(
  553. &emitter(), [&](auto& builder) {
  554. CARBON_DIAGNOSTIC(FromExtendHere, Note,
  555. "declared as an extended scope here");
  556. builder.Note(extended_id, FromExtendHere);
  557. });
  558. if (!AppendLookupScopesForConstant(loc_id, const_id, &scopes)) {
  559. // TODO: Handle case where we have a symbolic type and instead should
  560. // look in its type.
  561. }
  562. }
  563. is_parent_access |= !extended.empty();
  564. continue;
  565. }
  566. // If this is our second lookup result, diagnose an ambiguity.
  567. if (result.inst_id.is_valid()) {
  568. CARBON_DIAGNOSTIC(
  569. NameAmbiguousDueToExtend, Error,
  570. "ambiguous use of name `{0}` found in multiple extended scopes",
  571. SemIR::NameId);
  572. emitter_->Emit(loc_id, NameAmbiguousDueToExtend, name_id);
  573. // TODO: Add notes pointing to the scopes.
  574. return {.specific_id = SemIR::SpecificId::Invalid,
  575. .inst_id = SemIR::ErrorInst::SingletonInstId};
  576. }
  577. result.inst_id = scope_result_id;
  578. result.specific_id = specific_id;
  579. }
  580. if (required &&
  581. (!result.inst_id.is_valid() || result.inst_id.is_poisoned())) {
  582. if (!has_error) {
  583. if (prohibited_accesses.empty()) {
  584. DiagnoseMemberNameNotFound(loc_id, name_id, lookup_scopes);
  585. } else {
  586. // TODO: We should report multiple prohibited accesses in case we don't
  587. // find a valid lookup. Reporting the last one should suffice for now.
  588. auto [scope_result_id, access_kind, is_parent_access] =
  589. prohibited_accesses.back();
  590. // Note, `access_info` is guaranteed to have a value here, since
  591. // `prohibited_accesses` is non-empty.
  592. DiagnoseInvalidQualifiedNameAccess(*this, loc_id, scope_result_id,
  593. name_id, access_kind,
  594. is_parent_access, *access_info);
  595. }
  596. }
  597. return {.specific_id = SemIR::SpecificId::Invalid,
  598. .inst_id = SemIR::ErrorInst::SingletonInstId};
  599. }
  600. return result;
  601. }
  602. // Returns the scope of the Core package, or Invalid if it's not found.
  603. //
  604. // TODO: Consider tracking the Core package in SemIR so we don't need to use
  605. // name lookup to find it.
  606. static auto GetCorePackage(Context& context, SemIRLoc loc, llvm::StringRef name)
  607. -> SemIR::NameScopeId {
  608. auto core_ident_id = context.identifiers().Add("Core");
  609. auto packaging = context.parse_tree().packaging_decl();
  610. if (packaging && packaging->names.package_id == core_ident_id) {
  611. return SemIR::NameScopeId::Package;
  612. }
  613. auto core_name_id = SemIR::NameId::ForIdentifier(core_ident_id);
  614. // Look up `package.Core`.
  615. auto [core_inst_id, _] = context.LookupNameInExactScope(
  616. loc, core_name_id, SemIR::NameScopeId::Package,
  617. context.name_scopes().Get(SemIR::NameScopeId::Package));
  618. if (core_inst_id.is_valid()) {
  619. // We expect it to be a namespace.
  620. if (auto namespace_inst =
  621. context.insts().TryGetAs<SemIR::Namespace>(core_inst_id)) {
  622. // TODO: Decide whether to allow the case where `Core` is not a package.
  623. return namespace_inst->name_scope_id;
  624. }
  625. }
  626. CARBON_DIAGNOSTIC(
  627. CoreNotFound, Error,
  628. "`Core.{0}` implicitly referenced here, but package `Core` not found",
  629. std::string);
  630. context.emitter().Emit(loc, CoreNotFound, name.str());
  631. return SemIR::NameScopeId::Invalid;
  632. }
  633. auto Context::LookupNameInCore(SemIRLoc loc, llvm::StringRef name)
  634. -> SemIR::InstId {
  635. auto core_package_id = GetCorePackage(*this, loc, name);
  636. if (!core_package_id.is_valid()) {
  637. return SemIR::ErrorInst::SingletonInstId;
  638. }
  639. auto name_id = SemIR::NameId::ForIdentifier(identifiers().Add(name));
  640. auto [inst_id, _] = LookupNameInExactScope(
  641. loc, name_id, core_package_id, name_scopes().Get(core_package_id));
  642. if (!inst_id.is_valid()) {
  643. CARBON_DIAGNOSTIC(
  644. CoreNameNotFound, Error,
  645. "name `Core.{0}` implicitly referenced here, but not found",
  646. SemIR::NameId);
  647. emitter_->Emit(loc, CoreNameNotFound, name_id);
  648. return SemIR::ErrorInst::SingletonInstId;
  649. }
  650. // Look through import_refs and aliases.
  651. return constant_values().GetConstantInstId(inst_id);
  652. }
  653. template <typename BranchNode, typename... Args>
  654. static auto AddDominatedBlockAndBranchImpl(Context& context,
  655. Parse::NodeId node_id, Args... args)
  656. -> SemIR::InstBlockId {
  657. if (!context.inst_block_stack().is_current_block_reachable()) {
  658. return SemIR::InstBlockId::Unreachable;
  659. }
  660. auto block_id = context.inst_blocks().AddDefaultValue();
  661. context.AddInst<BranchNode>(node_id, {block_id, args...});
  662. return block_id;
  663. }
  664. auto Context::AddDominatedBlockAndBranch(Parse::NodeId node_id)
  665. -> SemIR::InstBlockId {
  666. return AddDominatedBlockAndBranchImpl<SemIR::Branch>(*this, node_id);
  667. }
  668. auto Context::AddDominatedBlockAndBranchWithArg(Parse::NodeId node_id,
  669. SemIR::InstId arg_id)
  670. -> SemIR::InstBlockId {
  671. return AddDominatedBlockAndBranchImpl<SemIR::BranchWithArg>(*this, node_id,
  672. arg_id);
  673. }
  674. auto Context::AddDominatedBlockAndBranchIf(Parse::NodeId node_id,
  675. SemIR::InstId cond_id)
  676. -> SemIR::InstBlockId {
  677. return AddDominatedBlockAndBranchImpl<SemIR::BranchIf>(*this, node_id,
  678. cond_id);
  679. }
  680. auto Context::AddConvergenceBlockAndPush(Parse::NodeId node_id, int num_blocks)
  681. -> void {
  682. CARBON_CHECK(num_blocks >= 2, "no convergence");
  683. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  684. for ([[maybe_unused]] auto _ : llvm::seq(num_blocks)) {
  685. if (inst_block_stack().is_current_block_reachable()) {
  686. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  687. new_block_id = inst_blocks().AddDefaultValue();
  688. }
  689. AddInst<SemIR::Branch>(node_id, {.target_id = new_block_id});
  690. }
  691. inst_block_stack().Pop();
  692. }
  693. inst_block_stack().Push(new_block_id);
  694. AddToRegion(new_block_id, node_id);
  695. }
  696. auto Context::AddConvergenceBlockWithArgAndPush(
  697. Parse::NodeId node_id, std::initializer_list<SemIR::InstId> block_args)
  698. -> SemIR::InstId {
  699. CARBON_CHECK(block_args.size() >= 2, "no convergence");
  700. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  701. for (auto arg_id : block_args) {
  702. if (inst_block_stack().is_current_block_reachable()) {
  703. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  704. new_block_id = inst_blocks().AddDefaultValue();
  705. }
  706. AddInst<SemIR::BranchWithArg>(
  707. node_id, {.target_id = new_block_id, .arg_id = arg_id});
  708. }
  709. inst_block_stack().Pop();
  710. }
  711. inst_block_stack().Push(new_block_id);
  712. AddToRegion(new_block_id, node_id);
  713. // Acquire the result value.
  714. SemIR::TypeId result_type_id = insts().Get(*block_args.begin()).type_id();
  715. return AddInst<SemIR::BlockArg>(
  716. node_id, {.type_id = result_type_id, .block_id = new_block_id});
  717. }
  718. auto Context::SetBlockArgResultBeforeConstantUse(SemIR::InstId select_id,
  719. SemIR::InstId cond_id,
  720. SemIR::InstId if_true,
  721. SemIR::InstId if_false)
  722. -> void {
  723. CARBON_CHECK(insts().Is<SemIR::BlockArg>(select_id));
  724. // Determine the constant result based on the condition value.
  725. SemIR::ConstantId const_id = SemIR::ConstantId::NotConstant;
  726. auto cond_const_id = constant_values().Get(cond_id);
  727. if (!cond_const_id.is_template()) {
  728. // Symbolic or non-constant condition means a non-constant result.
  729. } else if (auto literal = insts().TryGetAs<SemIR::BoolLiteral>(
  730. constant_values().GetInstId(cond_const_id))) {
  731. const_id = constant_values().Get(literal.value().value.ToBool() ? if_true
  732. : if_false);
  733. } else {
  734. CARBON_CHECK(cond_const_id == SemIR::ErrorInst::SingletonConstantId,
  735. "Unexpected constant branch condition.");
  736. const_id = SemIR::ErrorInst::SingletonConstantId;
  737. }
  738. if (const_id.is_constant()) {
  739. CARBON_VLOG("Constant: {0} -> {1}\n", insts().Get(select_id),
  740. constant_values().GetInstId(const_id));
  741. constant_values().Set(select_id, const_id);
  742. }
  743. }
  744. auto Context::AddToRegion(SemIR::InstBlockId block_id, SemIR::LocId loc_id)
  745. -> void {
  746. if (region_stack_.empty()) {
  747. TODO(loc_id,
  748. "Control flow expressions are currently only supported inside "
  749. "functions.");
  750. return;
  751. }
  752. if (block_id == SemIR::InstBlockId::Unreachable) {
  753. return;
  754. }
  755. region_stack_.AppendToTop(block_id);
  756. }
  757. auto Context::BeginSubpattern() -> void {
  758. inst_block_stack().Push();
  759. PushRegion(inst_block_stack().PeekOrAdd());
  760. }
  761. auto Context::EndSubpatternAsExpr(SemIR::InstId result_id)
  762. -> SemIR::ExprRegionId {
  763. if (region_stack_.PeekArray().size() > 1) {
  764. // End the exit block with a branch to a successor block, whose contents
  765. // will be determined later.
  766. AddInst(SemIR::LocIdAndInst::NoLoc<SemIR::Branch>(
  767. {.target_id = inst_blocks().AddDefaultValue()}));
  768. } else {
  769. // This single-block region will be inserted as a SpliceBlock, so we don't
  770. // need control flow out of it.
  771. }
  772. auto block_id = inst_block_stack().Pop();
  773. CARBON_CHECK(block_id == region_stack_.PeekArray().back());
  774. // TODO: Is it possible to validate that this region is genuinely
  775. // single-entry, single-exit?
  776. return sem_ir().expr_regions().Add(
  777. {.block_ids = PopRegion(), .result_id = result_id});
  778. }
  779. auto Context::EndSubpatternAsEmpty() -> void {
  780. auto block_id = inst_block_stack().Pop();
  781. CARBON_CHECK(block_id == region_stack_.PeekArray().front());
  782. CARBON_CHECK(inst_blocks().Get(block_id).empty());
  783. region_stack_.PopArray();
  784. }
  785. auto Context::InsertHere(SemIR::ExprRegionId region_id) -> SemIR::InstId {
  786. auto region = sem_ir_->expr_regions().Get(region_id);
  787. auto loc_id = insts().GetLocId(region.result_id);
  788. auto exit_block = inst_blocks().Get(region.block_ids.back());
  789. if (region.block_ids.size() == 1) {
  790. // TODO: Is it possible to avoid leaving an "orphan" block in the IR in the
  791. // first two cases?
  792. if (exit_block.empty()) {
  793. return region.result_id;
  794. }
  795. if (exit_block.size() == 1) {
  796. inst_block_stack_.AddInstId(exit_block.front());
  797. return region.result_id;
  798. }
  799. return AddInst<SemIR::SpliceBlock>(
  800. loc_id, {.type_id = insts().Get(region.result_id).type_id(),
  801. .block_id = region.block_ids.front(),
  802. .result_id = region.result_id});
  803. }
  804. if (region_stack_.empty()) {
  805. TODO(loc_id,
  806. "Control flow expressions are currently only supported inside "
  807. "functions.");
  808. return SemIR::ErrorInst::SingletonInstId;
  809. }
  810. AddInst(SemIR::LocIdAndInst::NoLoc<SemIR::Branch>(
  811. {.target_id = region.block_ids.front()}));
  812. inst_block_stack_.Pop();
  813. // TODO: this will cumulatively cost O(MN) running time for M blocks
  814. // at the Nth level of the stack. Figure out how to do better.
  815. region_stack_.AppendToTop(region.block_ids);
  816. auto resume_with_block_id =
  817. insts().GetAs<SemIR::Branch>(exit_block.back()).target_id;
  818. CARBON_CHECK(inst_blocks().GetOrEmpty(resume_with_block_id).empty());
  819. inst_block_stack_.Push(resume_with_block_id);
  820. AddToRegion(resume_with_block_id, loc_id);
  821. return region.result_id;
  822. }
  823. auto Context::is_current_position_reachable() -> bool {
  824. if (!inst_block_stack().is_current_block_reachable()) {
  825. return false;
  826. }
  827. // Our current position is at the end of a reachable block. That position is
  828. // reachable unless the previous instruction is a terminator instruction.
  829. auto block_contents = inst_block_stack().PeekCurrentBlockContents();
  830. if (block_contents.empty()) {
  831. return true;
  832. }
  833. const auto& last_inst = insts().Get(block_contents.back());
  834. return last_inst.kind().terminator_kind() !=
  835. SemIR::TerminatorKind::Terminator;
  836. }
  837. auto Context::Finalize() -> void {
  838. // Pop information for the file-level scope.
  839. sem_ir().set_top_inst_block_id(inst_block_stack().Pop());
  840. scope_stack().Pop();
  841. // Finalizes the list of exports on the IR.
  842. inst_blocks().Set(SemIR::InstBlockId::Exports, exports_);
  843. // Finalizes the ImportRef inst block.
  844. inst_blocks().Set(SemIR::InstBlockId::ImportRefs, import_ref_ids_);
  845. // Finalizes __global_init.
  846. global_init_.Finalize();
  847. }
  848. namespace {
  849. // Worklist-based type completion mechanism.
  850. //
  851. // When attempting to complete a type, we may find other types that also need to
  852. // be completed: types nested within that type, and the value representation of
  853. // the type. In order to complete a type without recursing arbitrarily deeply,
  854. // we use a worklist of tasks:
  855. //
  856. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  857. // nested within a type to the work list.
  858. // - A `BuildValueRepr` step computes the value representation for a
  859. // type, once all of its nested types are complete, and marks the type as
  860. // complete.
  861. class TypeCompleter {
  862. public:
  863. TypeCompleter(Context& context, SemIRLoc loc,
  864. Context::BuildDiagnosticFn diagnoser)
  865. : context_(context), loc_(loc), diagnoser_(diagnoser) {}
  866. // Attempts to complete the given type. Returns true if it is now complete,
  867. // false if it could not be completed.
  868. auto Complete(SemIR::TypeId type_id) -> bool {
  869. Push(type_id);
  870. while (!work_list_.empty()) {
  871. if (!ProcessStep()) {
  872. return false;
  873. }
  874. }
  875. return true;
  876. }
  877. private:
  878. // Adds `type_id` to the work list, if it's not already complete.
  879. auto Push(SemIR::TypeId type_id) -> void {
  880. if (!context_.types().IsComplete(type_id)) {
  881. work_list_.push_back(
  882. {.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
  883. }
  884. }
  885. // Runs the next step.
  886. auto ProcessStep() -> bool {
  887. auto [type_id, phase] = work_list_.back();
  888. // We might have enqueued the same type more than once. Just skip the
  889. // type if it's already complete.
  890. if (context_.types().IsComplete(type_id)) {
  891. work_list_.pop_back();
  892. return true;
  893. }
  894. auto inst_id = context_.types().GetInstId(type_id);
  895. auto inst = context_.insts().Get(inst_id);
  896. auto old_work_list_size = work_list_.size();
  897. switch (phase) {
  898. case Phase::AddNestedIncompleteTypes:
  899. if (!AddNestedIncompleteTypes(inst)) {
  900. return false;
  901. }
  902. CARBON_CHECK(work_list_.size() >= old_work_list_size,
  903. "AddNestedIncompleteTypes should not remove work items");
  904. work_list_[old_work_list_size - 1].phase = Phase::BuildValueRepr;
  905. break;
  906. case Phase::BuildValueRepr: {
  907. auto value_rep = BuildValueRepr(type_id, inst);
  908. context_.types().SetValueRepr(type_id, value_rep);
  909. CARBON_CHECK(old_work_list_size == work_list_.size(),
  910. "BuildValueRepr should not change work items");
  911. work_list_.pop_back();
  912. // Also complete the value representation type, if necessary. This
  913. // should never fail: the value representation shouldn't require any
  914. // additional nested types to be complete.
  915. if (!context_.types().IsComplete(value_rep.type_id)) {
  916. work_list_.push_back(
  917. {.type_id = value_rep.type_id, .phase = Phase::BuildValueRepr});
  918. }
  919. // For a pointer representation, the pointee also needs to be complete.
  920. if (value_rep.kind == SemIR::ValueRepr::Pointer) {
  921. if (value_rep.type_id == SemIR::ErrorInst::SingletonTypeId) {
  922. break;
  923. }
  924. auto pointee_type_id =
  925. context_.sem_ir().GetPointeeType(value_rep.type_id);
  926. if (!context_.types().IsComplete(pointee_type_id)) {
  927. work_list_.push_back(
  928. {.type_id = pointee_type_id, .phase = Phase::BuildValueRepr});
  929. }
  930. }
  931. break;
  932. }
  933. }
  934. return true;
  935. }
  936. // Adds any types nested within `type_inst` that need to be complete for
  937. // `type_inst` to be complete to our work list.
  938. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  939. CARBON_KIND_SWITCH(type_inst) {
  940. case CARBON_KIND(SemIR::ArrayType inst): {
  941. Push(inst.element_type_id);
  942. break;
  943. }
  944. case CARBON_KIND(SemIR::StructType inst): {
  945. for (auto field : context_.struct_type_fields().Get(inst.fields_id)) {
  946. Push(field.type_id);
  947. }
  948. break;
  949. }
  950. case CARBON_KIND(SemIR::TupleType inst): {
  951. for (auto element_type_id :
  952. context_.type_blocks().Get(inst.elements_id)) {
  953. Push(element_type_id);
  954. }
  955. break;
  956. }
  957. case CARBON_KIND(SemIR::ClassType inst): {
  958. auto& class_info = context_.classes().Get(inst.class_id);
  959. if (!class_info.is_defined()) {
  960. if (diagnoser_) {
  961. auto builder = diagnoser_();
  962. context_.NoteIncompleteClass(inst.class_id, builder);
  963. builder.Emit();
  964. }
  965. return false;
  966. }
  967. if (inst.specific_id.is_valid()) {
  968. ResolveSpecificDefinition(context_, loc_, inst.specific_id);
  969. }
  970. if (auto adapted_type_id =
  971. class_info.GetAdaptedType(context_.sem_ir(), inst.specific_id);
  972. adapted_type_id.is_valid()) {
  973. Push(adapted_type_id);
  974. } else {
  975. Push(class_info.GetObjectRepr(context_.sem_ir(), inst.specific_id));
  976. }
  977. break;
  978. }
  979. case CARBON_KIND(SemIR::ConstType inst): {
  980. Push(inst.inner_id);
  981. break;
  982. }
  983. default:
  984. break;
  985. }
  986. return true;
  987. }
  988. // Makes an empty value representation, which is used for types that have no
  989. // state, such as empty structs and tuples.
  990. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  991. return {.kind = SemIR::ValueRepr::None,
  992. .type_id = context_.GetTupleType({})};
  993. }
  994. // Makes a value representation that uses pass-by-copy, copying the given
  995. // type.
  996. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  997. SemIR::ValueRepr::AggregateKind aggregate_kind =
  998. SemIR::ValueRepr::NotAggregate) const
  999. -> SemIR::ValueRepr {
  1000. return {.kind = SemIR::ValueRepr::Copy,
  1001. .aggregate_kind = aggregate_kind,
  1002. .type_id = rep_id};
  1003. }
  1004. // Makes a value representation that uses pass-by-address with the given
  1005. // pointee type.
  1006. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  1007. SemIR::ValueRepr::AggregateKind aggregate_kind =
  1008. SemIR::ValueRepr::NotAggregate) const
  1009. -> SemIR::ValueRepr {
  1010. // TODO: Should we add `const` qualification to `pointee_id`?
  1011. return {.kind = SemIR::ValueRepr::Pointer,
  1012. .aggregate_kind = aggregate_kind,
  1013. .type_id = context_.GetPointerType(pointee_id)};
  1014. }
  1015. // Gets the value representation of a nested type, which should already be
  1016. // complete.
  1017. auto GetNestedValueRepr(SemIR::TypeId nested_type_id) const {
  1018. CARBON_CHECK(context_.types().IsComplete(nested_type_id),
  1019. "Nested type should already be complete");
  1020. auto value_rep = context_.types().GetValueRepr(nested_type_id);
  1021. CARBON_CHECK(value_rep.kind != SemIR::ValueRepr::Unknown,
  1022. "Complete type should have a value representation");
  1023. return value_rep;
  1024. }
  1025. template <typename InstT>
  1026. requires(InstT::Kind.template IsAnyOf<
  1027. SemIR::AutoType, SemIR::BoolType, SemIR::BoundMethodType,
  1028. SemIR::ErrorInst, SemIR::IntLiteralType, SemIR::LegacyFloatType,
  1029. SemIR::NamespaceType, SemIR::SpecificFunctionType, SemIR::TypeType,
  1030. SemIR::VtableType, SemIR::WitnessType>())
  1031. auto BuildValueReprForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  1032. -> SemIR::ValueRepr {
  1033. return MakeCopyValueRepr(type_id);
  1034. }
  1035. auto BuildValueReprForInst(SemIR::TypeId type_id,
  1036. SemIR::StringType /*inst*/) const
  1037. -> SemIR::ValueRepr {
  1038. // TODO: Decide on string value semantics. This should probably be a
  1039. // custom value representation carrying a pointer and size or
  1040. // similar.
  1041. return MakePointerValueRepr(type_id);
  1042. }
  1043. auto BuildStructOrTupleValueRepr(size_t num_elements,
  1044. SemIR::TypeId elementwise_rep,
  1045. bool same_as_object_rep) const
  1046. -> SemIR::ValueRepr {
  1047. SemIR::ValueRepr::AggregateKind aggregate_kind =
  1048. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  1049. : SemIR::ValueRepr::ValueAggregate;
  1050. if (num_elements == 1) {
  1051. // The value representation for a struct or tuple with a single element
  1052. // is a struct or tuple containing the value representation of the
  1053. // element.
  1054. // TODO: Consider doing the same whenever `elementwise_rep` is
  1055. // sufficiently small.
  1056. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  1057. }
  1058. // For a struct or tuple with multiple fields, we use a pointer
  1059. // to the elementwise value representation.
  1060. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  1061. }
  1062. auto BuildValueReprForInst(SemIR::TypeId type_id,
  1063. SemIR::StructType struct_type) const
  1064. -> SemIR::ValueRepr {
  1065. auto fields = context_.struct_type_fields().Get(struct_type.fields_id);
  1066. if (fields.empty()) {
  1067. return MakeEmptyValueRepr();
  1068. }
  1069. // Find the value representation for each field, and construct a struct
  1070. // of value representations.
  1071. llvm::SmallVector<SemIR::StructTypeField> value_rep_fields;
  1072. value_rep_fields.reserve(fields.size());
  1073. bool same_as_object_rep = true;
  1074. for (auto field : fields) {
  1075. auto field_value_rep = GetNestedValueRepr(field.type_id);
  1076. if (!field_value_rep.IsCopyOfObjectRepr(context_.sem_ir(),
  1077. field.type_id)) {
  1078. same_as_object_rep = false;
  1079. field.type_id = field_value_rep.type_id;
  1080. }
  1081. value_rep_fields.push_back(field);
  1082. }
  1083. auto value_rep =
  1084. same_as_object_rep
  1085. ? type_id
  1086. : context_.GetStructType(
  1087. context_.struct_type_fields().AddCanonical(value_rep_fields));
  1088. return BuildStructOrTupleValueRepr(fields.size(), value_rep,
  1089. same_as_object_rep);
  1090. }
  1091. auto BuildValueReprForInst(SemIR::TypeId type_id,
  1092. SemIR::TupleType tuple_type) const
  1093. -> SemIR::ValueRepr {
  1094. // TODO: Share more code with structs.
  1095. auto elements = context_.type_blocks().Get(tuple_type.elements_id);
  1096. if (elements.empty()) {
  1097. return MakeEmptyValueRepr();
  1098. }
  1099. // Find the value representation for each element, and construct a tuple
  1100. // of value representations.
  1101. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  1102. value_rep_elements.reserve(elements.size());
  1103. bool same_as_object_rep = true;
  1104. for (auto element_type_id : elements) {
  1105. auto element_value_rep = GetNestedValueRepr(element_type_id);
  1106. if (!element_value_rep.IsCopyOfObjectRepr(context_.sem_ir(),
  1107. element_type_id)) {
  1108. same_as_object_rep = false;
  1109. }
  1110. value_rep_elements.push_back(element_value_rep.type_id);
  1111. }
  1112. auto value_rep = same_as_object_rep
  1113. ? type_id
  1114. : context_.GetTupleType(value_rep_elements);
  1115. return BuildStructOrTupleValueRepr(elements.size(), value_rep,
  1116. same_as_object_rep);
  1117. }
  1118. auto BuildValueReprForInst(SemIR::TypeId type_id,
  1119. SemIR::ArrayType /*inst*/) const
  1120. -> SemIR::ValueRepr {
  1121. // For arrays, it's convenient to always use a pointer representation,
  1122. // even when the array has zero or one element, in order to support
  1123. // indexing.
  1124. return MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate);
  1125. }
  1126. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/,
  1127. SemIR::ClassType inst) const -> SemIR::ValueRepr {
  1128. auto& class_info = context_.classes().Get(inst.class_id);
  1129. // The value representation of an adapter is the value representation of
  1130. // its adapted type.
  1131. if (auto adapted_type_id =
  1132. class_info.GetAdaptedType(context_.sem_ir(), inst.specific_id);
  1133. adapted_type_id.is_valid()) {
  1134. return GetNestedValueRepr(adapted_type_id);
  1135. }
  1136. // Otherwise, the value representation for a class is a pointer to the
  1137. // object representation.
  1138. // TODO: Support customized value representations for classes.
  1139. // TODO: Pick a better value representation when possible.
  1140. return MakePointerValueRepr(
  1141. class_info.GetObjectRepr(context_.sem_ir(), inst.specific_id),
  1142. SemIR::ValueRepr::ObjectAggregate);
  1143. }
  1144. template <typename InstT>
  1145. requires(InstT::Kind.template IsAnyOf<
  1146. SemIR::AssociatedEntityType, SemIR::FacetAccessType,
  1147. SemIR::FacetType, SemIR::FunctionType, SemIR::GenericClassType,
  1148. SemIR::GenericInterfaceType, SemIR::UnboundElementType,
  1149. SemIR::WhereExpr>())
  1150. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/, InstT /*inst*/) const
  1151. -> SemIR::ValueRepr {
  1152. // These types have no runtime operations, so we use an empty value
  1153. // representation.
  1154. //
  1155. // TODO: There is information we could model here:
  1156. // - For an interface, we could use a witness.
  1157. // - For an associated entity, we could use an index into the witness.
  1158. // - For an unbound element, we could use an index or offset.
  1159. return MakeEmptyValueRepr();
  1160. }
  1161. template <typename InstT>
  1162. requires(InstT::Kind.template IsAnyOf<SemIR::BindSymbolicName,
  1163. SemIR::ImplWitnessAccess>())
  1164. auto BuildValueReprForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  1165. -> SemIR::ValueRepr {
  1166. // For symbolic types, we arbitrarily pick a copy representation.
  1167. return MakeCopyValueRepr(type_id);
  1168. }
  1169. template <typename InstT>
  1170. requires(InstT::Kind.template IsAnyOf<SemIR::FloatType, SemIR::IntType,
  1171. SemIR::PointerType>())
  1172. auto BuildValueReprForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  1173. -> SemIR::ValueRepr {
  1174. return MakeCopyValueRepr(type_id);
  1175. }
  1176. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/,
  1177. SemIR::ConstType inst) const -> SemIR::ValueRepr {
  1178. // The value representation of `const T` is the same as that of `T`.
  1179. // Objects are not modifiable through their value representations.
  1180. return GetNestedValueRepr(inst.inner_id);
  1181. }
  1182. template <typename InstT>
  1183. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  1184. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/, InstT inst) const
  1185. -> SemIR::ValueRepr {
  1186. CARBON_FATAL("Type refers to non-type inst {0}", inst);
  1187. }
  1188. // Builds and returns the value representation for the given type. All nested
  1189. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  1190. auto BuildValueRepr(SemIR::TypeId type_id, SemIR::Inst inst) const
  1191. -> SemIR::ValueRepr {
  1192. // Use overload resolution to select the implementation, producing compile
  1193. // errors when BuildValueReprForInst isn't defined for a given instruction.
  1194. CARBON_KIND_SWITCH(inst) {
  1195. #define CARBON_SEM_IR_INST_KIND(Name) \
  1196. case CARBON_KIND(SemIR::Name typed_inst): { \
  1197. return BuildValueReprForInst(type_id, typed_inst); \
  1198. }
  1199. #include "toolchain/sem_ir/inst_kind.def"
  1200. }
  1201. }
  1202. enum class Phase : int8_t {
  1203. // The next step is to add nested types to the list of types to complete.
  1204. AddNestedIncompleteTypes,
  1205. // The next step is to build the value representation for the type.
  1206. BuildValueRepr,
  1207. };
  1208. struct WorkItem {
  1209. SemIR::TypeId type_id;
  1210. Phase phase;
  1211. };
  1212. Context& context_;
  1213. llvm::SmallVector<WorkItem> work_list_;
  1214. SemIRLoc loc_;
  1215. Context::BuildDiagnosticFn diagnoser_;
  1216. };
  1217. } // namespace
  1218. auto Context::TryToCompleteType(SemIR::TypeId type_id, SemIRLoc loc,
  1219. BuildDiagnosticFn diagnoser) -> bool {
  1220. return TypeCompleter(*this, loc, diagnoser).Complete(type_id);
  1221. }
  1222. auto Context::CompleteTypeOrCheckFail(SemIR::TypeId type_id) -> void {
  1223. bool complete =
  1224. TypeCompleter(*this, SemIR::LocId::Invalid, nullptr).Complete(type_id);
  1225. CARBON_CHECK(complete, "Expected {0} to be a complete type",
  1226. types().GetAsInst(type_id));
  1227. }
  1228. auto Context::RequireCompleteType(SemIR::TypeId type_id, SemIR::LocId loc_id,
  1229. BuildDiagnosticFn diagnoser) -> bool {
  1230. CARBON_CHECK(diagnoser);
  1231. if (!TypeCompleter(*this, loc_id, diagnoser).Complete(type_id)) {
  1232. return false;
  1233. }
  1234. // For a symbolic type, create an instruction to require the corresponding
  1235. // specific type to be complete.
  1236. if (type_id.AsConstantId().is_symbolic()) {
  1237. // TODO: Deduplicate these.
  1238. AddInstInNoBlock(SemIR::LocIdAndInst(
  1239. loc_id,
  1240. SemIR::RequireCompleteType{
  1241. .type_id = GetSingletonType(SemIR::WitnessType::SingletonInstId),
  1242. .complete_type_id = type_id}));
  1243. }
  1244. return true;
  1245. }
  1246. auto Context::RequireConcreteType(SemIR::TypeId type_id, SemIR::LocId loc_id,
  1247. BuildDiagnosticFn diagnoser,
  1248. BuildDiagnosticFn abstract_diagnoser)
  1249. -> bool {
  1250. CARBON_CHECK(abstract_diagnoser);
  1251. if (!RequireCompleteType(type_id, loc_id, diagnoser)) {
  1252. return false;
  1253. }
  1254. if (auto class_type = types().TryGetAs<SemIR::ClassType>(type_id)) {
  1255. auto& class_info = classes().Get(class_type->class_id);
  1256. if (class_info.inheritance_kind !=
  1257. SemIR::Class::InheritanceKind::Abstract) {
  1258. return true;
  1259. }
  1260. auto builder = abstract_diagnoser();
  1261. if (!builder) {
  1262. return false;
  1263. }
  1264. NoteAbstractClass(class_type->class_id, builder);
  1265. builder.Emit();
  1266. return false;
  1267. }
  1268. return true;
  1269. }
  1270. auto Context::RequireDefinedType(SemIR::TypeId type_id, SemIR::LocId loc_id,
  1271. BuildDiagnosticFn diagnoser) -> bool {
  1272. if (!RequireCompleteType(type_id, loc_id, diagnoser)) {
  1273. return false;
  1274. }
  1275. if (auto facet_type = types().TryGetAs<SemIR::FacetType>(type_id)) {
  1276. const auto& facet_type_info = facet_types().Get(facet_type->facet_type_id);
  1277. for (auto interface : facet_type_info.impls_constraints) {
  1278. auto interface_id = interface.interface_id;
  1279. if (!interfaces().Get(interface_id).is_defined()) {
  1280. auto builder = diagnoser();
  1281. NoteUndefinedInterface(interface_id, builder);
  1282. builder.Emit();
  1283. return false;
  1284. }
  1285. if (interface.specific_id.is_valid()) {
  1286. ResolveSpecificDefinition(*this, loc_id, interface.specific_id);
  1287. }
  1288. }
  1289. // TODO: Finish facet type resolution.
  1290. }
  1291. return true;
  1292. }
  1293. auto Context::GetTypeIdForTypeConstant(SemIR::ConstantId constant_id)
  1294. -> SemIR::TypeId {
  1295. CARBON_CHECK(constant_id.is_constant(),
  1296. "Canonicalizing non-constant type: {0}", constant_id);
  1297. auto type_id =
  1298. insts().Get(constant_values().GetInstId(constant_id)).type_id();
  1299. // TODO: For now, we allow values of facet type to be used as types.
  1300. CARBON_CHECK(IsFacetType(type_id) ||
  1301. constant_id == SemIR::ErrorInst::SingletonConstantId,
  1302. "Forming type ID for non-type constant of type {0}",
  1303. types().GetAsInst(type_id));
  1304. return SemIR::TypeId::ForTypeConstant(constant_id);
  1305. }
  1306. auto Context::FacetTypeFromInterface(SemIR::InterfaceId interface_id,
  1307. SemIR::SpecificId specific_id)
  1308. -> SemIR::FacetType {
  1309. SemIR::FacetTypeId facet_type_id = facet_types().Add(
  1310. SemIR::FacetTypeInfo{.impls_constraints = {{interface_id, specific_id}},
  1311. .other_requirements = false});
  1312. return {.type_id = SemIR::TypeType::SingletonTypeId,
  1313. .facet_type_id = facet_type_id};
  1314. }
  1315. // Gets or forms a type_id for a type, given the instruction kind and arguments.
  1316. template <typename InstT, typename... EachArgT>
  1317. static auto GetTypeImpl(Context& context, EachArgT... each_arg)
  1318. -> SemIR::TypeId {
  1319. // TODO: Remove inst_id parameter from TryEvalInst.
  1320. InstT inst = {SemIR::TypeType::SingletonTypeId, each_arg...};
  1321. return context.GetTypeIdForTypeConstant(
  1322. TryEvalInst(context, SemIR::InstId::Invalid, inst));
  1323. }
  1324. // Gets or forms a type_id for a type, given the instruction kind and arguments,
  1325. // and completes the type. This should only be used when type completion cannot
  1326. // fail.
  1327. template <typename InstT, typename... EachArgT>
  1328. static auto GetCompleteTypeImpl(Context& context, EachArgT... each_arg)
  1329. -> SemIR::TypeId {
  1330. auto type_id = GetTypeImpl<InstT>(context, each_arg...);
  1331. context.CompleteTypeOrCheckFail(type_id);
  1332. return type_id;
  1333. }
  1334. auto Context::GetStructType(SemIR::StructTypeFieldsId fields_id)
  1335. -> SemIR::TypeId {
  1336. return GetTypeImpl<SemIR::StructType>(*this, fields_id);
  1337. }
  1338. auto Context::GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids)
  1339. -> SemIR::TypeId {
  1340. return GetTypeImpl<SemIR::TupleType>(*this,
  1341. type_blocks().AddCanonical(type_ids));
  1342. }
  1343. auto Context::GetAssociatedEntityType(SemIR::TypeId interface_type_id,
  1344. SemIR::TypeId entity_type_id)
  1345. -> SemIR::TypeId {
  1346. return GetTypeImpl<SemIR::AssociatedEntityType>(*this, interface_type_id,
  1347. entity_type_id);
  1348. }
  1349. auto Context::GetSingletonType(SemIR::InstId singleton_id) -> SemIR::TypeId {
  1350. CARBON_CHECK(SemIR::IsSingletonInstId(singleton_id));
  1351. auto type_id = GetTypeIdForTypeInst(singleton_id);
  1352. // To keep client code simpler, complete builtin types before returning them.
  1353. CompleteTypeOrCheckFail(type_id);
  1354. return type_id;
  1355. }
  1356. auto Context::GetClassType(SemIR::ClassId class_id,
  1357. SemIR::SpecificId specific_id) -> SemIR::TypeId {
  1358. return GetTypeImpl<SemIR::ClassType>(*this, class_id, specific_id);
  1359. }
  1360. auto Context::GetFunctionType(SemIR::FunctionId fn_id,
  1361. SemIR::SpecificId specific_id) -> SemIR::TypeId {
  1362. return GetCompleteTypeImpl<SemIR::FunctionType>(*this, fn_id, specific_id);
  1363. }
  1364. auto Context::GetGenericClassType(SemIR::ClassId class_id,
  1365. SemIR::SpecificId enclosing_specific_id)
  1366. -> SemIR::TypeId {
  1367. return GetCompleteTypeImpl<SemIR::GenericClassType>(*this, class_id,
  1368. enclosing_specific_id);
  1369. }
  1370. auto Context::GetGenericInterfaceType(SemIR::InterfaceId interface_id,
  1371. SemIR::SpecificId enclosing_specific_id)
  1372. -> SemIR::TypeId {
  1373. return GetCompleteTypeImpl<SemIR::GenericInterfaceType>(
  1374. *this, interface_id, enclosing_specific_id);
  1375. }
  1376. auto Context::GetInterfaceType(SemIR::InterfaceId interface_id,
  1377. SemIR::SpecificId specific_id) -> SemIR::TypeId {
  1378. return GetTypeImpl<SemIR::FacetType>(
  1379. *this, FacetTypeFromInterface(interface_id, specific_id).facet_type_id);
  1380. }
  1381. auto Context::GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  1382. return GetTypeImpl<SemIR::PointerType>(*this, pointee_type_id);
  1383. }
  1384. auto Context::GetUnboundElementType(SemIR::TypeId class_type_id,
  1385. SemIR::TypeId element_type_id)
  1386. -> SemIR::TypeId {
  1387. return GetTypeImpl<SemIR::UnboundElementType>(*this, class_type_id,
  1388. element_type_id);
  1389. }
  1390. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  1391. output << "Check::Context\n";
  1392. // In a stack dump, this is probably indented by a tab. We treat that as 8
  1393. // spaces then add a couple to indent past the Context label.
  1394. constexpr int Indent = 10;
  1395. node_stack_.PrintForStackDump(Indent, output);
  1396. inst_block_stack_.PrintForStackDump(Indent, output);
  1397. pattern_block_stack_.PrintForStackDump(Indent, output);
  1398. param_and_arg_refs_stack_.PrintForStackDump(Indent, output);
  1399. args_type_info_stack_.PrintForStackDump(Indent, output);
  1400. }
  1401. auto Context::DumpFormattedFile() const -> void {
  1402. SemIR::Formatter formatter(sem_ir_);
  1403. formatter.Print(llvm::errs());
  1404. }
  1405. } // namespace Carbon::Check