context.cpp 49 KB

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