context.cpp 54 KB

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