context.cpp 60 KB

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