context.cpp 61 KB

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