context.cpp 62 KB

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