context.cpp 61 KB

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