context.cpp 62 KB

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