context.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  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/lex/tokenized_buffer.h"
  22. #include "toolchain/parse/node_ids.h"
  23. #include "toolchain/parse/node_kind.h"
  24. #include "toolchain/sem_ir/builtin_inst_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/typed_insts.h"
  34. namespace Carbon::Check {
  35. Context::Context(const Lex::TokenizedBuffer& tokens, DiagnosticEmitter& emitter,
  36. const Parse::Tree& parse_tree,
  37. llvm::function_ref<const Parse::TreeAndSubtrees&()>
  38. get_parse_tree_and_subtrees,
  39. SemIR::File& sem_ir, llvm::raw_ostream* vlog_stream)
  40. : tokens_(&tokens),
  41. emitter_(&emitter),
  42. parse_tree_(&parse_tree),
  43. get_parse_tree_and_subtrees_(get_parse_tree_and_subtrees),
  44. sem_ir_(&sem_ir),
  45. vlog_stream_(vlog_stream),
  46. node_stack_(parse_tree, vlog_stream),
  47. inst_block_stack_("inst_block_stack_", sem_ir, vlog_stream),
  48. pattern_block_stack_("pattern_block_stack_", sem_ir, vlog_stream),
  49. param_and_arg_refs_stack_(sem_ir, vlog_stream, node_stack_),
  50. args_type_info_stack_("args_type_info_stack_", sem_ir, vlog_stream),
  51. decl_name_stack_(this),
  52. scope_stack_(sem_ir_->identifiers()),
  53. global_init_(this) {
  54. // Map the builtin `<error>` and `type` type constants to their corresponding
  55. // special `TypeId` values.
  56. type_ids_for_type_constants_.Insert(
  57. SemIR::ConstantId::ForTemplateConstant(SemIR::InstId::BuiltinError),
  58. SemIR::TypeId::Error);
  59. type_ids_for_type_constants_.Insert(
  60. SemIR::ConstantId::ForTemplateConstant(SemIR::InstId::BuiltinTypeType),
  61. SemIR::TypeId::TypeType);
  62. // TODO: Remove this and add a `VerifyOnFinish` once we properly push and pop
  63. // in the right places.
  64. generic_region_stack().Push();
  65. }
  66. auto Context::TODO(SemIRLoc loc, std::string label) -> bool {
  67. CARBON_DIAGNOSTIC(SemanticsTodo, Error, "semantics TODO: `{0}`", std::string);
  68. emitter_->Emit(loc, SemanticsTodo, std::move(label));
  69. return false;
  70. }
  71. auto Context::VerifyOnFinish() -> void {
  72. // Information in all the various context objects should be cleaned up as
  73. // various pieces of context go out of scope. At this point, nothing should
  74. // remain.
  75. // node_stack_ will still contain top-level entities.
  76. scope_stack_.VerifyOnFinish();
  77. inst_block_stack_.VerifyOnFinish();
  78. pattern_block_stack_.VerifyOnFinish();
  79. param_and_arg_refs_stack_.VerifyOnFinish();
  80. }
  81. // Finish producing an instruction. Set its constant value, and register it in
  82. // any applicable instruction lists.
  83. auto Context::FinishInst(SemIR::InstId inst_id, SemIR::Inst inst) -> void {
  84. GenericRegionStack::DependencyKind dep_kind =
  85. GenericRegionStack::DependencyKind::None;
  86. // If the instruction has a symbolic constant type, track that we need to
  87. // substitute into it.
  88. if (types().GetConstantId(inst.type_id()).is_symbolic()) {
  89. dep_kind |= GenericRegionStack::DependencyKind::SymbolicType;
  90. }
  91. // If the instruction has a constant value, compute it.
  92. auto const_id = TryEvalInst(*this, inst_id, inst);
  93. constant_values().Set(inst_id, const_id);
  94. if (const_id.is_constant()) {
  95. CARBON_VLOG("Constant: {0} -> {1}\n", inst,
  96. constant_values().GetInstId(const_id));
  97. // If the constant value is symbolic, track that we need to substitute into
  98. // it.
  99. if (const_id.is_symbolic()) {
  100. dep_kind |= GenericRegionStack::DependencyKind::SymbolicConstant;
  101. }
  102. }
  103. // Keep track of dependent instructions.
  104. if (dep_kind != GenericRegionStack::DependencyKind::None) {
  105. // TODO: Also check for template-dependent instructions.
  106. generic_region_stack().AddDependentInst(
  107. {.inst_id = inst_id, .kind = dep_kind});
  108. }
  109. }
  110. // Returns whether a parse node associated with an imported instruction of kind
  111. // `imported_kind` is usable as the location of a corresponding local
  112. // instruction of kind `local_kind`.
  113. static auto HasCompatibleImportedNodeKind(SemIR::InstKind imported_kind,
  114. SemIR::InstKind local_kind) -> bool {
  115. if (imported_kind == local_kind) {
  116. return true;
  117. }
  118. if (imported_kind == SemIR::ImportDecl::Kind &&
  119. local_kind == SemIR::Namespace::Kind) {
  120. static_assert(
  121. std::is_convertible_v<decltype(SemIR::ImportDecl::Kind)::TypedNodeId,
  122. decltype(SemIR::Namespace::Kind)::TypedNodeId>);
  123. return true;
  124. }
  125. return false;
  126. }
  127. auto Context::CheckCompatibleImportedNodeKind(
  128. SemIR::ImportIRInstId imported_loc_id, SemIR::InstKind kind) -> void {
  129. auto& import_ir_inst = import_ir_insts().Get(imported_loc_id);
  130. const auto* import_ir = import_irs().Get(import_ir_inst.ir_id).sem_ir;
  131. auto imported_kind = import_ir->insts().Get(import_ir_inst.inst_id).kind();
  132. CARBON_CHECK(
  133. HasCompatibleImportedNodeKind(imported_kind, kind),
  134. "Node of kind {0} created with location of imported node of kind {1}",
  135. kind, imported_kind);
  136. }
  137. auto Context::AddInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst)
  138. -> SemIR::InstId {
  139. auto inst_id = sem_ir().insts().AddInNoBlock(loc_id_and_inst);
  140. CARBON_VLOG("AddInst: {0}\n", loc_id_and_inst.inst);
  141. FinishInst(inst_id, loc_id_and_inst.inst);
  142. return inst_id;
  143. }
  144. auto Context::AddInst(SemIR::LocIdAndInst loc_id_and_inst) -> SemIR::InstId {
  145. auto inst_id = AddInstInNoBlock(loc_id_and_inst);
  146. inst_block_stack_.AddInstId(inst_id);
  147. return inst_id;
  148. }
  149. auto Context::AddPlaceholderInstInNoBlock(SemIR::LocIdAndInst loc_id_and_inst)
  150. -> SemIR::InstId {
  151. auto inst_id = sem_ir().insts().AddInNoBlock(loc_id_and_inst);
  152. CARBON_VLOG("AddPlaceholderInst: {0}\n", loc_id_and_inst.inst);
  153. constant_values().Set(inst_id, SemIR::ConstantId::Invalid);
  154. return inst_id;
  155. }
  156. auto Context::AddPlaceholderInst(SemIR::LocIdAndInst loc_id_and_inst)
  157. -> SemIR::InstId {
  158. auto inst_id = AddPlaceholderInstInNoBlock(loc_id_and_inst);
  159. inst_block_stack_.AddInstId(inst_id);
  160. return inst_id;
  161. }
  162. auto Context::AddPatternInst(SemIR::LocIdAndInst loc_id_and_inst)
  163. -> SemIR::InstId {
  164. auto inst_id = AddInstInNoBlock(loc_id_and_inst);
  165. pattern_block_stack_.AddInstId(inst_id);
  166. return inst_id;
  167. }
  168. auto Context::AddConstant(SemIR::Inst inst, bool is_symbolic)
  169. -> SemIR::ConstantId {
  170. auto const_id = constants().GetOrAdd(inst, is_symbolic);
  171. CARBON_VLOG("AddConstant: {0}\n", inst);
  172. return const_id;
  173. }
  174. auto Context::ReplaceLocIdAndInstBeforeConstantUse(
  175. SemIR::InstId inst_id, SemIR::LocIdAndInst loc_id_and_inst) -> void {
  176. sem_ir().insts().SetLocIdAndInst(inst_id, loc_id_and_inst);
  177. CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, loc_id_and_inst.inst);
  178. FinishInst(inst_id, loc_id_and_inst.inst);
  179. }
  180. auto Context::ReplaceInstBeforeConstantUse(SemIR::InstId inst_id,
  181. SemIR::Inst inst) -> void {
  182. sem_ir().insts().Set(inst_id, inst);
  183. CARBON_VLOG("ReplaceInst: {0} -> {1}\n", inst_id, inst);
  184. FinishInst(inst_id, inst);
  185. }
  186. auto Context::DiagnoseDuplicateName(SemIRLoc dup_def, SemIRLoc prev_def)
  187. -> void {
  188. CARBON_DIAGNOSTIC(NameDeclDuplicate, Error,
  189. "duplicate name being declared in the same scope");
  190. CARBON_DIAGNOSTIC(NameDeclPrevious, Note, "name is previously declared here");
  191. emitter_->Build(dup_def, NameDeclDuplicate)
  192. .Note(prev_def, NameDeclPrevious)
  193. .Emit();
  194. }
  195. auto Context::DiagnoseNameNotFound(SemIRLoc loc, SemIR::NameId name_id)
  196. -> void {
  197. CARBON_DIAGNOSTIC(NameNotFound, Error, "name `{0}` not found", SemIR::NameId);
  198. emitter_->Emit(loc, NameNotFound, name_id);
  199. }
  200. auto Context::NoteIncompleteClass(SemIR::ClassId class_id,
  201. DiagnosticBuilder& builder) -> void {
  202. const auto& class_info = classes().Get(class_id);
  203. CARBON_CHECK(!class_info.is_defined(), "Class is not incomplete");
  204. if (class_info.definition_id.is_valid()) {
  205. CARBON_DIAGNOSTIC(ClassIncompleteWithinDefinition, Note,
  206. "class is incomplete within its definition");
  207. builder.Note(class_info.definition_id, ClassIncompleteWithinDefinition);
  208. } else {
  209. CARBON_DIAGNOSTIC(ClassForwardDeclaredHere, Note,
  210. "class was forward declared here");
  211. builder.Note(class_info.latest_decl_id(), ClassForwardDeclaredHere);
  212. }
  213. }
  214. auto Context::NoteUndefinedInterface(SemIR::InterfaceId interface_id,
  215. DiagnosticBuilder& builder) -> void {
  216. const auto& interface_info = interfaces().Get(interface_id);
  217. CARBON_CHECK(!interface_info.is_defined(), "Interface is not incomplete");
  218. if (interface_info.is_being_defined()) {
  219. CARBON_DIAGNOSTIC(InterfaceUndefinedWithinDefinition, Note,
  220. "interface is currently being defined");
  221. builder.Note(interface_info.definition_id,
  222. InterfaceUndefinedWithinDefinition);
  223. } else {
  224. CARBON_DIAGNOSTIC(InterfaceForwardDeclaredHere, Note,
  225. "interface was forward declared here");
  226. builder.Note(interface_info.latest_decl_id(), InterfaceForwardDeclaredHere);
  227. }
  228. }
  229. auto Context::AddNameToLookup(SemIR::NameId name_id, SemIR::InstId target_id)
  230. -> void {
  231. if (auto existing = scope_stack().LookupOrAddName(name_id, target_id);
  232. existing.is_valid()) {
  233. DiagnoseDuplicateName(target_id, existing);
  234. }
  235. }
  236. auto Context::LookupNameInDecl(SemIR::LocId loc_id, SemIR::NameId name_id,
  237. SemIR::NameScopeId scope_id) -> SemIR::InstId {
  238. if (!scope_id.is_valid()) {
  239. // Look for a name in the current scope only. There are two cases where the
  240. // name would be in an outer scope:
  241. //
  242. // - The name is the sole component of the declared name:
  243. //
  244. // class A;
  245. // fn F() {
  246. // class A;
  247. // }
  248. //
  249. // In this case, the inner A is not the same class as the outer A, so
  250. // lookup should not find the outer A.
  251. //
  252. // - The name is a qualifier of some larger declared name:
  253. //
  254. // class A { class B; }
  255. // fn F() {
  256. // class A.B {}
  257. // }
  258. //
  259. // In this case, we're not in the correct scope to define a member of
  260. // class A, so we should reject, and we achieve this by not finding the
  261. // name A from the outer scope.
  262. return scope_stack().LookupInCurrentScope(name_id);
  263. } else {
  264. // We do not look into `extend`ed scopes here. A qualified name in a
  265. // declaration must specify the exact scope in which the name was originally
  266. // introduced:
  267. //
  268. // base class A { fn F(); }
  269. // class B { extend base: A; }
  270. //
  271. // // Error, no `F` in `B`.
  272. // fn B.F() {}
  273. return LookupNameInExactScope(loc_id, name_id, scope_id,
  274. name_scopes().Get(scope_id))
  275. .first;
  276. }
  277. }
  278. auto Context::LookupUnqualifiedName(Parse::NodeId node_id,
  279. SemIR::NameId name_id, bool required)
  280. -> LookupResult {
  281. // TODO: Check for shadowed lookup results.
  282. // Find the results from ancestor lexical scopes. These will be combined with
  283. // results from non-lexical scopes such as namespaces and classes.
  284. auto [lexical_result, non_lexical_scopes] =
  285. scope_stack().LookupInLexicalScopes(name_id);
  286. // Walk the non-lexical scopes and perform lookups into each of them.
  287. for (auto [index, lookup_scope_id, specific_id] :
  288. llvm::reverse(non_lexical_scopes)) {
  289. if (auto non_lexical_result = LookupQualifiedName(
  290. node_id, name_id,
  291. {.name_scope_id = lookup_scope_id, .specific_id = specific_id},
  292. /*required=*/false);
  293. non_lexical_result.inst_id.is_valid()) {
  294. return non_lexical_result;
  295. }
  296. }
  297. if (lexical_result.is_valid()) {
  298. // A lexical scope never needs an associated specific. If there's a
  299. // lexically enclosing generic, then it also encloses the point of use of
  300. // the name.
  301. return {.specific_id = SemIR::SpecificId::Invalid,
  302. .inst_id = lexical_result};
  303. }
  304. // We didn't find anything at all.
  305. if (required) {
  306. DiagnoseNameNotFound(node_id, name_id);
  307. }
  308. return {.specific_id = SemIR::SpecificId::Invalid,
  309. .inst_id = SemIR::InstId::BuiltinError};
  310. }
  311. auto Context::LookupNameInExactScope(SemIRLoc loc, SemIR::NameId name_id,
  312. SemIR::NameScopeId scope_id,
  313. const SemIR::NameScope& scope)
  314. -> std::pair<SemIR::InstId, SemIR::AccessKind> {
  315. if (auto lookup = scope.name_map.Lookup(name_id)) {
  316. auto entry = scope.names[lookup.value()];
  317. LoadImportRef(*this, entry.inst_id);
  318. return {entry.inst_id, entry.access_kind};
  319. }
  320. if (!scope.import_ir_scopes.empty()) {
  321. // TODO: Enforce other access modifiers for imports.
  322. return {ImportNameFromOtherPackage(*this, loc, scope_id,
  323. scope.import_ir_scopes, name_id),
  324. SemIR::AccessKind::Public};
  325. }
  326. return {SemIR::InstId::Invalid, SemIR::AccessKind::Public};
  327. }
  328. // Prints diagnostics on invalid qualified name access.
  329. static auto DiagnoseInvalidQualifiedNameAccess(Context& context, SemIRLoc loc,
  330. SemIR::InstId scope_result_id,
  331. SemIR::NameId name_id,
  332. SemIR::AccessKind access_kind,
  333. bool is_parent_access,
  334. AccessInfo access_info) -> void {
  335. auto class_type = context.insts().TryGetAs<SemIR::ClassType>(
  336. context.constant_values().GetInstId(access_info.constant_id));
  337. if (!class_type) {
  338. return;
  339. }
  340. // TODO: Support scoped entities other than just classes.
  341. auto class_info = context.classes().Get(class_type->class_id);
  342. CARBON_DIAGNOSTIC(ClassInvalidMemberAccess, Error,
  343. "cannot access {0} member `{1}` of type `{2}`",
  344. SemIR::AccessKind, SemIR::NameId, SemIR::TypeId);
  345. CARBON_DIAGNOSTIC(ClassMemberDefinition, Note,
  346. "the {0} member `{1}` is defined here", SemIR::AccessKind,
  347. SemIR::NameId);
  348. auto parent_type_id = class_info.self_type_id;
  349. if (access_kind == SemIR::AccessKind::Private && is_parent_access) {
  350. if (auto base_decl = context.insts().TryGetAsIfValid<SemIR::BaseDecl>(
  351. class_info.base_id)) {
  352. parent_type_id = base_decl->base_type_id;
  353. } else if (auto adapt_decl =
  354. context.insts().TryGetAsIfValid<SemIR::AdaptDecl>(
  355. class_info.adapt_id)) {
  356. parent_type_id = adapt_decl->adapted_type_id;
  357. } else {
  358. CARBON_FATAL("Expected parent for parent access");
  359. }
  360. }
  361. context.emitter()
  362. .Build(loc, ClassInvalidMemberAccess, access_kind, name_id,
  363. parent_type_id)
  364. .Note(scope_result_id, ClassMemberDefinition, access_kind, name_id)
  365. .Emit();
  366. }
  367. // Returns whether the access is prohibited by the access modifiers.
  368. static auto IsAccessProhibited(std::optional<AccessInfo> access_info,
  369. SemIR::AccessKind access_kind,
  370. bool is_parent_access) -> bool {
  371. if (!access_info) {
  372. return false;
  373. }
  374. switch (access_kind) {
  375. case SemIR::AccessKind::Public:
  376. return false;
  377. case SemIR::AccessKind::Protected:
  378. return access_info->highest_allowed_access == SemIR::AccessKind::Public;
  379. case SemIR::AccessKind::Private:
  380. return access_info->highest_allowed_access !=
  381. SemIR::AccessKind::Private ||
  382. is_parent_access;
  383. }
  384. }
  385. // Information regarding a prohibited access.
  386. struct ProhibitedAccessInfo {
  387. // The resulting inst of the lookup.
  388. SemIR::InstId scope_result_id;
  389. // The access kind of the lookup.
  390. SemIR::AccessKind access_kind;
  391. // If the lookup is from an extended scope. For example, if this is a base
  392. // class member access from a class that extends it.
  393. bool is_parent_access;
  394. };
  395. auto Context::LookupQualifiedName(SemIRLoc loc, SemIR::NameId name_id,
  396. LookupScope scope, bool required,
  397. std::optional<AccessInfo> access_info)
  398. -> LookupResult {
  399. llvm::SmallVector<LookupScope> scopes = {scope};
  400. // TODO: Support reporting of multiple prohibited access.
  401. llvm::SmallVector<ProhibitedAccessInfo> prohibited_accesses;
  402. LookupResult result = {.specific_id = SemIR::SpecificId::Invalid,
  403. .inst_id = SemIR::InstId::Invalid};
  404. bool has_error = false;
  405. bool is_parent_access = false;
  406. // Walk this scope and, if nothing is found here, the scopes it extends.
  407. while (!scopes.empty()) {
  408. auto [scope_id, specific_id] = scopes.pop_back_val();
  409. const auto& name_scope = name_scopes().Get(scope_id);
  410. has_error |= name_scope.has_error;
  411. auto [scope_result_id, access_kind] =
  412. LookupNameInExactScope(loc, name_id, scope_id, name_scope);
  413. auto is_access_prohibited =
  414. IsAccessProhibited(access_info, access_kind, is_parent_access);
  415. // Keep track of prohibited accesses, this will be useful for reporting
  416. // multiple prohibited accesses if we can't find a suitable lookup.
  417. if (is_access_prohibited) {
  418. prohibited_accesses.push_back({
  419. .scope_result_id = scope_result_id,
  420. .access_kind = access_kind,
  421. .is_parent_access = is_parent_access,
  422. });
  423. }
  424. if (!scope_result_id.is_valid() || is_access_prohibited) {
  425. // If nothing is found in this scope or if we encountered an invalid
  426. // access, look in its extended scopes.
  427. auto extended = name_scope.extended_scopes;
  428. scopes.reserve(scopes.size() + extended.size());
  429. for (auto extended_id : llvm::reverse(extended)) {
  430. // TODO: Track a constant describing the extended scope, and substitute
  431. // into it to determine its corresponding specific.
  432. scopes.push_back({.name_scope_id = extended_id,
  433. .specific_id = SemIR::SpecificId::Invalid});
  434. }
  435. is_parent_access |= !extended.empty();
  436. continue;
  437. }
  438. // If this is our second lookup result, diagnose an ambiguity.
  439. if (result.inst_id.is_valid()) {
  440. // TODO: This is currently not reachable because the only scope that can
  441. // extend is a class scope, and it can only extend a single base class.
  442. // Add test coverage once this is possible.
  443. CARBON_DIAGNOSTIC(
  444. NameAmbiguousDueToExtend, Error,
  445. "ambiguous use of name `{0}` found in multiple extended scopes",
  446. SemIR::NameId);
  447. emitter_->Emit(loc, NameAmbiguousDueToExtend, name_id);
  448. // TODO: Add notes pointing to the scopes.
  449. return {.specific_id = SemIR::SpecificId::Invalid,
  450. .inst_id = SemIR::InstId::BuiltinError};
  451. }
  452. result.inst_id = scope_result_id;
  453. result.specific_id = specific_id;
  454. }
  455. if (required && !result.inst_id.is_valid()) {
  456. if (!has_error) {
  457. if (prohibited_accesses.empty()) {
  458. DiagnoseNameNotFound(loc, name_id);
  459. } else {
  460. // TODO: We should report multiple prohibited accesses in case we don't
  461. // find a valid lookup. Reporting the last one should suffice for now.
  462. auto [scope_result_id, access_kind, is_parent_access] =
  463. prohibited_accesses.back();
  464. // Note, `access_info` is guaranteed to have a value here, since
  465. // `prohibited_accesses` is non-empty.
  466. DiagnoseInvalidQualifiedNameAccess(*this, loc, scope_result_id, name_id,
  467. access_kind, is_parent_access,
  468. *access_info);
  469. }
  470. }
  471. return {.specific_id = SemIR::SpecificId::Invalid,
  472. .inst_id = SemIR::InstId::BuiltinError};
  473. }
  474. return result;
  475. }
  476. // Returns the scope of the Core package, or Invalid if it's not found.
  477. //
  478. // TODO: Consider tracking the Core package in SemIR so we don't need to use
  479. // name lookup to find it.
  480. static auto GetCorePackage(Context& context, SemIRLoc loc)
  481. -> SemIR::NameScopeId {
  482. auto core_ident_id = context.identifiers().Add("Core");
  483. auto packaging = context.parse_tree().packaging_decl();
  484. if (packaging && packaging->names.package_id == core_ident_id) {
  485. return SemIR::NameScopeId::Package;
  486. }
  487. auto core_name_id = SemIR::NameId::ForIdentifier(core_ident_id);
  488. // Look up `package.Core`.
  489. auto [core_inst_id, _] = context.LookupNameInExactScope(
  490. loc, core_name_id, SemIR::NameScopeId::Package,
  491. context.name_scopes().Get(SemIR::NameScopeId::Package));
  492. if (core_inst_id.is_valid()) {
  493. // We expect it to be a namespace.
  494. if (auto namespace_inst =
  495. context.insts().TryGetAs<SemIR::Namespace>(core_inst_id)) {
  496. // TODO: Decide whether to allow the case where `Core` is not a package.
  497. return namespace_inst->name_scope_id;
  498. }
  499. }
  500. CARBON_DIAGNOSTIC(CoreNotFound, Error,
  501. "package `Core` implicitly referenced here, but not found");
  502. context.emitter().Emit(loc, CoreNotFound);
  503. return SemIR::NameScopeId::Invalid;
  504. }
  505. auto Context::LookupNameInCore(SemIRLoc loc, llvm::StringRef name)
  506. -> SemIR::InstId {
  507. auto core_package_id = GetCorePackage(*this, loc);
  508. if (!core_package_id.is_valid()) {
  509. return SemIR::InstId::BuiltinError;
  510. }
  511. auto name_id = SemIR::NameId::ForIdentifier(identifiers().Add(name));
  512. auto [inst_id, _] = LookupNameInExactScope(
  513. loc, name_id, core_package_id, name_scopes().Get(core_package_id));
  514. if (!inst_id.is_valid()) {
  515. CARBON_DIAGNOSTIC(
  516. CoreNameNotFound, Error,
  517. "name `Core.{0}` implicitly referenced here, but not found",
  518. SemIR::NameId);
  519. emitter_->Emit(loc, CoreNameNotFound, name_id);
  520. return SemIR::InstId::BuiltinError;
  521. }
  522. // Look through import_refs and aliases.
  523. return constant_values().GetConstantInstId(inst_id);
  524. }
  525. template <typename BranchNode, typename... Args>
  526. static auto AddDominatedBlockAndBranchImpl(Context& context,
  527. Parse::NodeId node_id, Args... args)
  528. -> SemIR::InstBlockId {
  529. if (!context.inst_block_stack().is_current_block_reachable()) {
  530. return SemIR::InstBlockId::Unreachable;
  531. }
  532. auto block_id = context.inst_blocks().AddDefaultValue();
  533. context.AddInst<BranchNode>(node_id, {block_id, args...});
  534. return block_id;
  535. }
  536. auto Context::AddDominatedBlockAndBranch(Parse::NodeId node_id)
  537. -> SemIR::InstBlockId {
  538. return AddDominatedBlockAndBranchImpl<SemIR::Branch>(*this, node_id);
  539. }
  540. auto Context::AddDominatedBlockAndBranchWithArg(Parse::NodeId node_id,
  541. SemIR::InstId arg_id)
  542. -> SemIR::InstBlockId {
  543. return AddDominatedBlockAndBranchImpl<SemIR::BranchWithArg>(*this, node_id,
  544. arg_id);
  545. }
  546. auto Context::AddDominatedBlockAndBranchIf(Parse::NodeId node_id,
  547. SemIR::InstId cond_id)
  548. -> SemIR::InstBlockId {
  549. return AddDominatedBlockAndBranchImpl<SemIR::BranchIf>(*this, node_id,
  550. cond_id);
  551. }
  552. auto Context::AddConvergenceBlockAndPush(Parse::NodeId node_id, int num_blocks)
  553. -> void {
  554. CARBON_CHECK(num_blocks >= 2, "no convergence");
  555. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  556. for ([[maybe_unused]] auto _ : llvm::seq(num_blocks)) {
  557. if (inst_block_stack().is_current_block_reachable()) {
  558. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  559. new_block_id = inst_blocks().AddDefaultValue();
  560. }
  561. AddInst<SemIR::Branch>(node_id, {.target_id = new_block_id});
  562. }
  563. inst_block_stack().Pop();
  564. }
  565. inst_block_stack().Push(new_block_id);
  566. }
  567. auto Context::AddConvergenceBlockWithArgAndPush(
  568. Parse::NodeId node_id, std::initializer_list<SemIR::InstId> block_args)
  569. -> SemIR::InstId {
  570. CARBON_CHECK(block_args.size() >= 2, "no convergence");
  571. SemIR::InstBlockId new_block_id = SemIR::InstBlockId::Unreachable;
  572. for (auto arg_id : block_args) {
  573. if (inst_block_stack().is_current_block_reachable()) {
  574. if (new_block_id == SemIR::InstBlockId::Unreachable) {
  575. new_block_id = inst_blocks().AddDefaultValue();
  576. }
  577. AddInst<SemIR::BranchWithArg>(
  578. node_id, {.target_id = new_block_id, .arg_id = arg_id});
  579. }
  580. inst_block_stack().Pop();
  581. }
  582. inst_block_stack().Push(new_block_id);
  583. // Acquire the result value.
  584. SemIR::TypeId result_type_id = insts().Get(*block_args.begin()).type_id();
  585. return AddInst<SemIR::BlockArg>(
  586. node_id, {.type_id = result_type_id, .block_id = new_block_id});
  587. }
  588. auto Context::SetBlockArgResultBeforeConstantUse(SemIR::InstId select_id,
  589. SemIR::InstId cond_id,
  590. SemIR::InstId if_true,
  591. SemIR::InstId if_false)
  592. -> void {
  593. CARBON_CHECK(insts().Is<SemIR::BlockArg>(select_id));
  594. // Determine the constant result based on the condition value.
  595. SemIR::ConstantId const_id = SemIR::ConstantId::NotConstant;
  596. auto cond_const_id = constant_values().Get(cond_id);
  597. if (!cond_const_id.is_template()) {
  598. // Symbolic or non-constant condition means a non-constant result.
  599. } else if (auto literal = insts().TryGetAs<SemIR::BoolLiteral>(
  600. constant_values().GetInstId(cond_const_id))) {
  601. const_id = constant_values().Get(literal.value().value.ToBool() ? if_true
  602. : if_false);
  603. } else {
  604. CARBON_CHECK(cond_const_id == SemIR::ConstantId::Error,
  605. "Unexpected constant branch condition.");
  606. const_id = SemIR::ConstantId::Error;
  607. }
  608. if (const_id.is_constant()) {
  609. CARBON_VLOG("Constant: {0} -> {1}\n", insts().Get(select_id),
  610. constant_values().GetInstId(const_id));
  611. constant_values().Set(select_id, const_id);
  612. }
  613. }
  614. auto Context::AddCurrentCodeBlockToFunction(Parse::NodeId node_id) -> void {
  615. CARBON_CHECK(!inst_block_stack().empty(), "no current code block");
  616. if (return_scope_stack().empty()) {
  617. CARBON_CHECK(node_id.is_valid(),
  618. "No current function, but node_id not provided");
  619. TODO(node_id,
  620. "Control flow expressions are currently only supported inside "
  621. "functions.");
  622. return;
  623. }
  624. if (!inst_block_stack().is_current_block_reachable()) {
  625. // Don't include unreachable blocks in the function.
  626. return;
  627. }
  628. auto function_id =
  629. insts()
  630. .GetAs<SemIR::FunctionDecl>(return_scope_stack().back().decl_id)
  631. .function_id;
  632. functions()
  633. .Get(function_id)
  634. .body_block_ids.push_back(inst_block_stack().PeekOrAdd());
  635. }
  636. auto Context::is_current_position_reachable() -> bool {
  637. if (!inst_block_stack().is_current_block_reachable()) {
  638. return false;
  639. }
  640. // Our current position is at the end of a reachable block. That position is
  641. // reachable unless the previous instruction is a terminator instruction.
  642. auto block_contents = inst_block_stack().PeekCurrentBlockContents();
  643. if (block_contents.empty()) {
  644. return true;
  645. }
  646. const auto& last_inst = insts().Get(block_contents.back());
  647. return last_inst.kind().terminator_kind() !=
  648. SemIR::TerminatorKind::Terminator;
  649. }
  650. auto Context::Finalize() -> void {
  651. // Pop information for the file-level scope.
  652. sem_ir().set_top_inst_block_id(inst_block_stack().Pop());
  653. scope_stack().Pop();
  654. // Finalizes the list of exports on the IR.
  655. inst_blocks().Set(SemIR::InstBlockId::Exports, exports_);
  656. // Finalizes the ImportRef inst block.
  657. inst_blocks().Set(SemIR::InstBlockId::ImportRefs, import_ref_ids_);
  658. // Finalizes __global_init.
  659. global_init_.Finalize();
  660. }
  661. namespace {
  662. // Worklist-based type completion mechanism.
  663. //
  664. // When attempting to complete a type, we may find other types that also need to
  665. // be completed: types nested within that type, and the value representation of
  666. // the type. In order to complete a type without recursing arbitrarily deeply,
  667. // we use a worklist of tasks:
  668. //
  669. // - An `AddNestedIncompleteTypes` step adds a task for all incomplete types
  670. // nested within a type to the work list.
  671. // - A `BuildValueRepr` step computes the value representation for a
  672. // type, once all of its nested types are complete, and marks the type as
  673. // complete.
  674. class TypeCompleter {
  675. public:
  676. TypeCompleter(Context& context,
  677. std::optional<Context::BuildDiagnosticFn> diagnoser)
  678. : context_(context), diagnoser_(diagnoser) {}
  679. // Attempts to complete the given type. Returns true if it is now complete,
  680. // false if it could not be completed.
  681. auto Complete(SemIR::TypeId type_id) -> bool {
  682. Push(type_id);
  683. while (!work_list_.empty()) {
  684. if (!ProcessStep()) {
  685. return false;
  686. }
  687. }
  688. return true;
  689. }
  690. private:
  691. // Adds `type_id` to the work list, if it's not already complete.
  692. auto Push(SemIR::TypeId type_id) -> void {
  693. if (!context_.types().IsComplete(type_id)) {
  694. work_list_.push_back(
  695. {.type_id = type_id, .phase = Phase::AddNestedIncompleteTypes});
  696. }
  697. }
  698. // Runs the next step.
  699. auto ProcessStep() -> bool {
  700. auto [type_id, phase] = work_list_.back();
  701. // We might have enqueued the same type more than once. Just skip the
  702. // type if it's already complete.
  703. if (context_.types().IsComplete(type_id)) {
  704. work_list_.pop_back();
  705. return true;
  706. }
  707. auto inst_id = context_.types().GetInstId(type_id);
  708. auto inst = context_.insts().Get(inst_id);
  709. auto old_work_list_size = work_list_.size();
  710. switch (phase) {
  711. case Phase::AddNestedIncompleteTypes:
  712. if (!AddNestedIncompleteTypes(inst)) {
  713. return false;
  714. }
  715. CARBON_CHECK(work_list_.size() >= old_work_list_size,
  716. "AddNestedIncompleteTypes should not remove work items");
  717. work_list_[old_work_list_size - 1].phase = Phase::BuildValueRepr;
  718. break;
  719. case Phase::BuildValueRepr: {
  720. auto value_rep = BuildValueRepr(type_id, inst);
  721. context_.types().SetValueRepr(type_id, value_rep);
  722. CARBON_CHECK(old_work_list_size == work_list_.size(),
  723. "BuildValueRepr should not change work items");
  724. work_list_.pop_back();
  725. // Also complete the value representation type, if necessary. This
  726. // should never fail: the value representation shouldn't require any
  727. // additional nested types to be complete.
  728. if (!context_.types().IsComplete(value_rep.type_id)) {
  729. work_list_.push_back(
  730. {.type_id = value_rep.type_id, .phase = Phase::BuildValueRepr});
  731. }
  732. // For a pointer representation, the pointee also needs to be complete.
  733. if (value_rep.kind == SemIR::ValueRepr::Pointer) {
  734. if (value_rep.type_id == SemIR::TypeId::Error) {
  735. break;
  736. }
  737. auto pointee_type_id =
  738. context_.sem_ir().GetPointeeType(value_rep.type_id);
  739. if (!context_.types().IsComplete(pointee_type_id)) {
  740. work_list_.push_back(
  741. {.type_id = pointee_type_id, .phase = Phase::BuildValueRepr});
  742. }
  743. }
  744. break;
  745. }
  746. }
  747. return true;
  748. }
  749. // Adds any types nested within `type_inst` that need to be complete for
  750. // `type_inst` to be complete to our work list.
  751. auto AddNestedIncompleteTypes(SemIR::Inst type_inst) -> bool {
  752. CARBON_KIND_SWITCH(type_inst) {
  753. case CARBON_KIND(SemIR::ArrayType inst): {
  754. Push(inst.element_type_id);
  755. break;
  756. }
  757. case CARBON_KIND(SemIR::StructType inst): {
  758. for (auto field_id : context_.inst_blocks().Get(inst.fields_id)) {
  759. Push(context_.insts()
  760. .GetAs<SemIR::StructTypeField>(field_id)
  761. .field_type_id);
  762. }
  763. break;
  764. }
  765. case CARBON_KIND(SemIR::TupleType inst): {
  766. for (auto element_type_id :
  767. context_.type_blocks().Get(inst.elements_id)) {
  768. Push(element_type_id);
  769. }
  770. break;
  771. }
  772. case CARBON_KIND(SemIR::ClassType inst): {
  773. auto& class_info = context_.classes().Get(inst.class_id);
  774. if (!class_info.is_defined()) {
  775. if (diagnoser_) {
  776. auto builder = (*diagnoser_)();
  777. context_.NoteIncompleteClass(inst.class_id, builder);
  778. builder.Emit();
  779. }
  780. return false;
  781. }
  782. if (inst.specific_id.is_valid()) {
  783. ResolveSpecificDefinition(context_, inst.specific_id);
  784. }
  785. Push(class_info.GetObjectRepr(context_.sem_ir(), inst.specific_id));
  786. break;
  787. }
  788. case CARBON_KIND(SemIR::ConstType inst): {
  789. Push(inst.inner_id);
  790. break;
  791. }
  792. default:
  793. break;
  794. }
  795. return true;
  796. }
  797. // Makes an empty value representation, which is used for types that have no
  798. // state, such as empty structs and tuples.
  799. auto MakeEmptyValueRepr() const -> SemIR::ValueRepr {
  800. return {.kind = SemIR::ValueRepr::None,
  801. .type_id = context_.GetTupleType({})};
  802. }
  803. // Makes a value representation that uses pass-by-copy, copying the given
  804. // type.
  805. auto MakeCopyValueRepr(SemIR::TypeId rep_id,
  806. SemIR::ValueRepr::AggregateKind aggregate_kind =
  807. SemIR::ValueRepr::NotAggregate) const
  808. -> SemIR::ValueRepr {
  809. return {.kind = SemIR::ValueRepr::Copy,
  810. .aggregate_kind = aggregate_kind,
  811. .type_id = rep_id};
  812. }
  813. // Makes a value representation that uses pass-by-address with the given
  814. // pointee type.
  815. auto MakePointerValueRepr(SemIR::TypeId pointee_id,
  816. SemIR::ValueRepr::AggregateKind aggregate_kind =
  817. SemIR::ValueRepr::NotAggregate) const
  818. -> SemIR::ValueRepr {
  819. // TODO: Should we add `const` qualification to `pointee_id`?
  820. return {.kind = SemIR::ValueRepr::Pointer,
  821. .aggregate_kind = aggregate_kind,
  822. .type_id = context_.GetPointerType(pointee_id)};
  823. }
  824. // Gets the value representation of a nested type, which should already be
  825. // complete.
  826. auto GetNestedValueRepr(SemIR::TypeId nested_type_id) const {
  827. CARBON_CHECK(context_.types().IsComplete(nested_type_id),
  828. "Nested type should already be complete");
  829. auto value_rep = context_.types().GetValueRepr(nested_type_id);
  830. CARBON_CHECK(value_rep.kind != SemIR::ValueRepr::Unknown,
  831. "Complete type should have a value representation");
  832. return value_rep;
  833. }
  834. auto BuildValueReprForInst(SemIR::TypeId type_id,
  835. SemIR::BuiltinInst builtin) const
  836. -> SemIR::ValueRepr {
  837. switch (builtin.builtin_inst_kind) {
  838. case SemIR::BuiltinInstKind::TypeType:
  839. case SemIR::BuiltinInstKind::Error:
  840. case SemIR::BuiltinInstKind::Invalid:
  841. case SemIR::BuiltinInstKind::BoolType:
  842. case SemIR::BuiltinInstKind::IntType:
  843. case SemIR::BuiltinInstKind::FloatType:
  844. case SemIR::BuiltinInstKind::NamespaceType:
  845. case SemIR::BuiltinInstKind::BoundMethodType:
  846. case SemIR::BuiltinInstKind::WitnessType:
  847. return MakeCopyValueRepr(type_id);
  848. case SemIR::BuiltinInstKind::StringType:
  849. // TODO: Decide on string value semantics. This should probably be a
  850. // custom value representation carrying a pointer and size or
  851. // similar.
  852. return MakePointerValueRepr(type_id);
  853. }
  854. llvm_unreachable("All builtin kinds were handled above");
  855. }
  856. auto BuildStructOrTupleValueRepr(std::size_t num_elements,
  857. SemIR::TypeId elementwise_rep,
  858. bool same_as_object_rep) const
  859. -> SemIR::ValueRepr {
  860. SemIR::ValueRepr::AggregateKind aggregate_kind =
  861. same_as_object_rep ? SemIR::ValueRepr::ValueAndObjectAggregate
  862. : SemIR::ValueRepr::ValueAggregate;
  863. if (num_elements == 1) {
  864. // The value representation for a struct or tuple with a single element
  865. // is a struct or tuple containing the value representation of the
  866. // element.
  867. // TODO: Consider doing the same whenever `elementwise_rep` is
  868. // sufficiently small.
  869. return MakeCopyValueRepr(elementwise_rep, aggregate_kind);
  870. }
  871. // For a struct or tuple with multiple fields, we use a pointer
  872. // to the elementwise value representation.
  873. return MakePointerValueRepr(elementwise_rep, aggregate_kind);
  874. }
  875. auto BuildValueReprForInst(SemIR::TypeId type_id,
  876. SemIR::StructType struct_type) const
  877. -> SemIR::ValueRepr {
  878. // TODO: Share more code with tuples.
  879. auto fields = context_.inst_blocks().Get(struct_type.fields_id);
  880. if (fields.empty()) {
  881. return MakeEmptyValueRepr();
  882. }
  883. // Find the value representation for each field, and construct a struct
  884. // of value representations.
  885. llvm::SmallVector<SemIR::InstId> value_rep_fields;
  886. value_rep_fields.reserve(fields.size());
  887. bool same_as_object_rep = true;
  888. for (auto field_id : fields) {
  889. auto field = context_.insts().GetAs<SemIR::StructTypeField>(field_id);
  890. auto field_value_rep = GetNestedValueRepr(field.field_type_id);
  891. if (field_value_rep.type_id != field.field_type_id) {
  892. same_as_object_rep = false;
  893. field.field_type_id = field_value_rep.type_id;
  894. field_id = context_.constant_values().GetInstId(
  895. TryEvalInst(context_, SemIR::InstId::Invalid, field));
  896. }
  897. value_rep_fields.push_back(field_id);
  898. }
  899. auto value_rep = same_as_object_rep
  900. ? type_id
  901. : context_.GetStructType(
  902. context_.inst_blocks().Add(value_rep_fields));
  903. return BuildStructOrTupleValueRepr(fields.size(), value_rep,
  904. same_as_object_rep);
  905. }
  906. auto BuildValueReprForInst(SemIR::TypeId type_id,
  907. SemIR::TupleType tuple_type) const
  908. -> SemIR::ValueRepr {
  909. // TODO: Share more code with structs.
  910. auto elements = context_.type_blocks().Get(tuple_type.elements_id);
  911. if (elements.empty()) {
  912. return MakeEmptyValueRepr();
  913. }
  914. // Find the value representation for each element, and construct a tuple
  915. // of value representations.
  916. llvm::SmallVector<SemIR::TypeId> value_rep_elements;
  917. value_rep_elements.reserve(elements.size());
  918. bool same_as_object_rep = true;
  919. for (auto element_type_id : elements) {
  920. auto element_value_rep = GetNestedValueRepr(element_type_id);
  921. if (element_value_rep.type_id != element_type_id) {
  922. same_as_object_rep = false;
  923. }
  924. value_rep_elements.push_back(element_value_rep.type_id);
  925. }
  926. auto value_rep = same_as_object_rep
  927. ? type_id
  928. : context_.GetTupleType(value_rep_elements);
  929. return BuildStructOrTupleValueRepr(elements.size(), value_rep,
  930. same_as_object_rep);
  931. }
  932. auto BuildValueReprForInst(SemIR::TypeId type_id,
  933. SemIR::ArrayType /*inst*/) const
  934. -> SemIR::ValueRepr {
  935. // For arrays, it's convenient to always use a pointer representation,
  936. // even when the array has zero or one element, in order to support
  937. // indexing.
  938. return MakePointerValueRepr(type_id, SemIR::ValueRepr::ObjectAggregate);
  939. }
  940. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/,
  941. SemIR::ClassType inst) const -> SemIR::ValueRepr {
  942. auto& class_info = context_.classes().Get(inst.class_id);
  943. // The value representation of an adapter is the value representation of
  944. // its adapted type.
  945. if (class_info.adapt_id.is_valid()) {
  946. return GetNestedValueRepr(SemIR::GetTypeInSpecific(
  947. context_.sem_ir(), inst.specific_id,
  948. context_.insts()
  949. .GetAs<SemIR::AdaptDecl>(class_info.adapt_id)
  950. .adapted_type_id));
  951. }
  952. // Otherwise, the value representation for a class is a pointer to the
  953. // object representation.
  954. // TODO: Support customized value representations for classes.
  955. // TODO: Pick a better value representation when possible.
  956. return MakePointerValueRepr(
  957. class_info.GetObjectRepr(context_.sem_ir(), inst.specific_id),
  958. SemIR::ValueRepr::ObjectAggregate);
  959. }
  960. template <typename InstT>
  961. requires(
  962. InstT::Kind
  963. .template IsAnyOf<SemIR::AssociatedEntityType, SemIR::FunctionType,
  964. SemIR::GenericClassType,
  965. SemIR::GenericInterfaceType, SemIR::InterfaceType,
  966. SemIR::UnboundElementType, SemIR::WhereExpr>())
  967. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/, InstT /*inst*/) const
  968. -> SemIR::ValueRepr {
  969. // These types have no runtime operations, so we use an empty value
  970. // representation.
  971. //
  972. // TODO: There is information we could model here:
  973. // - For an interface, we could use a witness.
  974. // - For an associated entity, we could use an index into the witness.
  975. // - For an unbound element, we could use an index or offset.
  976. return MakeEmptyValueRepr();
  977. }
  978. template <typename InstT>
  979. requires(InstT::Kind.template IsAnyOf<SemIR::BindSymbolicName,
  980. SemIR::InterfaceWitnessAccess>())
  981. auto BuildValueReprForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  982. -> SemIR::ValueRepr {
  983. // For symbolic types, we arbitrarily pick a copy representation.
  984. return MakeCopyValueRepr(type_id);
  985. }
  986. template <typename InstT>
  987. requires(InstT::Kind.template IsAnyOf<SemIR::FloatType, SemIR::IntType,
  988. SemIR::PointerType>())
  989. auto BuildValueReprForInst(SemIR::TypeId type_id, InstT /*inst*/) const
  990. -> SemIR::ValueRepr {
  991. return MakeCopyValueRepr(type_id);
  992. }
  993. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/,
  994. SemIR::ConstType inst) const -> SemIR::ValueRepr {
  995. // The value representation of `const T` is the same as that of `T`.
  996. // Objects are not modifiable through their value representations.
  997. return GetNestedValueRepr(inst.inner_id);
  998. }
  999. template <typename InstT>
  1000. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  1001. auto BuildValueReprForInst(SemIR::TypeId /*type_id*/, InstT inst) const
  1002. -> SemIR::ValueRepr {
  1003. CARBON_FATAL("Type refers to non-type inst {0}", inst);
  1004. }
  1005. // Builds and returns the value representation for the given type. All nested
  1006. // types, as found by AddNestedIncompleteTypes, are known to be complete.
  1007. auto BuildValueRepr(SemIR::TypeId type_id, SemIR::Inst inst) const
  1008. -> SemIR::ValueRepr {
  1009. // Use overload resolution to select the implementation, producing compile
  1010. // errors when BuildTypeForInst isn't defined for a given instruction.
  1011. CARBON_KIND_SWITCH(inst) {
  1012. #define CARBON_SEM_IR_INST_KIND(Name) \
  1013. case CARBON_KIND(SemIR::Name typed_inst): { \
  1014. return BuildValueReprForInst(type_id, typed_inst); \
  1015. }
  1016. #include "toolchain/sem_ir/inst_kind.def"
  1017. }
  1018. }
  1019. enum class Phase : int8_t {
  1020. // The next step is to add nested types to the list of types to complete.
  1021. AddNestedIncompleteTypes,
  1022. // The next step is to build the value representation for the type.
  1023. BuildValueRepr,
  1024. };
  1025. struct WorkItem {
  1026. SemIR::TypeId type_id;
  1027. Phase phase;
  1028. };
  1029. Context& context_;
  1030. llvm::SmallVector<WorkItem> work_list_;
  1031. std::optional<Context::BuildDiagnosticFn> diagnoser_;
  1032. };
  1033. } // namespace
  1034. auto Context::TryToCompleteType(SemIR::TypeId type_id,
  1035. std::optional<BuildDiagnosticFn> diagnoser)
  1036. -> bool {
  1037. return TypeCompleter(*this, diagnoser).Complete(type_id);
  1038. }
  1039. auto Context::TryToDefineType(SemIR::TypeId type_id,
  1040. std::optional<BuildDiagnosticFn> diagnoser)
  1041. -> bool {
  1042. if (!TryToCompleteType(type_id, diagnoser)) {
  1043. return false;
  1044. }
  1045. if (auto interface = types().TryGetAs<SemIR::InterfaceType>(type_id)) {
  1046. auto interface_id = interface->interface_id;
  1047. if (!interfaces().Get(interface_id).is_defined()) {
  1048. auto builder = (*diagnoser)();
  1049. NoteUndefinedInterface(interface_id, builder);
  1050. builder.Emit();
  1051. return false;
  1052. }
  1053. if (interface->specific_id.is_valid()) {
  1054. ResolveSpecificDefinition(*this, interface->specific_id);
  1055. }
  1056. }
  1057. return true;
  1058. }
  1059. auto Context::GetTypeIdForTypeConstant(SemIR::ConstantId constant_id)
  1060. -> SemIR::TypeId {
  1061. CARBON_CHECK(constant_id.is_constant(),
  1062. "Canonicalizing non-constant type: {0}", constant_id);
  1063. auto type_id =
  1064. insts().Get(constant_values().GetInstId(constant_id)).type_id();
  1065. // TODO: For now, we allow values of facet type to be used as types.
  1066. CARBON_CHECK(type_id == SemIR::TypeId::TypeType ||
  1067. types().Is<SemIR::InterfaceType>(type_id) ||
  1068. constant_id == SemIR::ConstantId::Error,
  1069. "Forming type ID for non-type constant of type {0}",
  1070. types().GetAsInst(type_id));
  1071. return SemIR::TypeId::ForTypeConstant(constant_id);
  1072. }
  1073. // Gets or forms a type_id for a type, given the instruction kind and arguments.
  1074. template <typename InstT, typename... EachArgT>
  1075. static auto GetTypeImpl(Context& context, EachArgT... each_arg)
  1076. -> SemIR::TypeId {
  1077. // TODO: Remove inst_id parameter from TryEvalInst.
  1078. InstT inst = {SemIR::TypeId::TypeType, each_arg...};
  1079. return context.GetTypeIdForTypeConstant(
  1080. TryEvalInst(context, SemIR::InstId::Invalid, inst));
  1081. }
  1082. // Gets or forms a type_id for a type, given the instruction kind and arguments,
  1083. // and completes the type. This should only be used when type completion cannot
  1084. // fail.
  1085. template <typename InstT, typename... EachArgT>
  1086. static auto GetCompleteTypeImpl(Context& context, EachArgT... each_arg)
  1087. -> SemIR::TypeId {
  1088. auto type_id = GetTypeImpl<InstT>(context, each_arg...);
  1089. bool complete = context.TryToCompleteType(type_id);
  1090. CARBON_CHECK(complete, "Type completion should not fail");
  1091. return type_id;
  1092. }
  1093. auto Context::GetStructType(SemIR::InstBlockId refs_id) -> SemIR::TypeId {
  1094. return GetTypeImpl<SemIR::StructType>(*this, refs_id);
  1095. }
  1096. auto Context::GetTupleType(llvm::ArrayRef<SemIR::TypeId> type_ids)
  1097. -> SemIR::TypeId {
  1098. return GetTypeImpl<SemIR::TupleType>(*this,
  1099. type_blocks().AddCanonical(type_ids));
  1100. }
  1101. auto Context::GetAssociatedEntityType(SemIR::TypeId interface_type_id,
  1102. SemIR::TypeId entity_type_id)
  1103. -> SemIR::TypeId {
  1104. return GetTypeImpl<SemIR::AssociatedEntityType>(*this, interface_type_id,
  1105. entity_type_id);
  1106. }
  1107. auto Context::GetBuiltinType(SemIR::BuiltinInstKind kind) -> SemIR::TypeId {
  1108. CARBON_CHECK(kind != SemIR::BuiltinInstKind::Invalid);
  1109. auto type_id = GetTypeIdForTypeInst(SemIR::InstId::ForBuiltin(kind));
  1110. // To keep client code simpler, complete builtin types before returning them.
  1111. bool complete = TryToCompleteType(type_id);
  1112. CARBON_CHECK(complete, "Failed to complete builtin type");
  1113. return type_id;
  1114. }
  1115. auto Context::GetFunctionType(SemIR::FunctionId fn_id,
  1116. SemIR::SpecificId specific_id) -> SemIR::TypeId {
  1117. return GetCompleteTypeImpl<SemIR::FunctionType>(*this, fn_id, specific_id);
  1118. }
  1119. auto Context::GetGenericClassType(SemIR::ClassId class_id,
  1120. SemIR::SpecificId enclosing_specific_id)
  1121. -> SemIR::TypeId {
  1122. return GetCompleteTypeImpl<SemIR::GenericClassType>(*this, class_id,
  1123. enclosing_specific_id);
  1124. }
  1125. auto Context::GetGenericInterfaceType(SemIR::InterfaceId interface_id,
  1126. SemIR::SpecificId enclosing_specific_id)
  1127. -> SemIR::TypeId {
  1128. return GetCompleteTypeImpl<SemIR::GenericInterfaceType>(
  1129. *this, interface_id, enclosing_specific_id);
  1130. }
  1131. auto Context::GetPointerType(SemIR::TypeId pointee_type_id) -> SemIR::TypeId {
  1132. return GetTypeImpl<SemIR::PointerType>(*this, pointee_type_id);
  1133. }
  1134. auto Context::GetUnboundElementType(SemIR::TypeId class_type_id,
  1135. SemIR::TypeId element_type_id)
  1136. -> SemIR::TypeId {
  1137. return GetTypeImpl<SemIR::UnboundElementType>(*this, class_type_id,
  1138. element_type_id);
  1139. }
  1140. auto Context::GetUnqualifiedType(SemIR::TypeId type_id) -> SemIR::TypeId {
  1141. if (auto const_type = types().TryGetAs<SemIR::ConstType>(type_id)) {
  1142. return const_type->inner_id;
  1143. }
  1144. return type_id;
  1145. }
  1146. auto Context::PrintForStackDump(llvm::raw_ostream& output) const -> void {
  1147. output << "Check::Context\n";
  1148. // In a stack dump, this is probably indented by a tab. We treat that as 8
  1149. // spaces then add a couple to indent past the Context label.
  1150. constexpr int Indent = 10;
  1151. SemIR::Formatter formatter(*tokens_, *parse_tree_, *sem_ir_);
  1152. node_stack_.PrintForStackDump(formatter, Indent, output);
  1153. inst_block_stack_.PrintForStackDump(formatter, Indent, output);
  1154. pattern_block_stack_.PrintForStackDump(formatter, Indent, output);
  1155. param_and_arg_refs_stack_.PrintForStackDump(formatter, Indent, output);
  1156. args_type_info_stack_.PrintForStackDump(formatter, Indent, output);
  1157. }
  1158. auto Context::DumpFormattedFile() const -> void {
  1159. SemIR::Formatter formatter(*tokens_, *parse_tree_, *sem_ir_);
  1160. formatter.Print(llvm::errs());
  1161. }
  1162. } // namespace Carbon::Check