member_access.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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/member_access.h"
  5. #include <optional>
  6. #include "llvm/ADT/STLExtras.h"
  7. #include "toolchain/base/kind_switch.h"
  8. #include "toolchain/check/context.h"
  9. #include "toolchain/check/convert.h"
  10. #include "toolchain/check/impl_lookup.h"
  11. #include "toolchain/diagnostics/diagnostic_emitter.h"
  12. #include "toolchain/sem_ir/generic.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/inst.h"
  15. #include "toolchain/sem_ir/name_scope.h"
  16. #include "toolchain/sem_ir/typed_insts.h"
  17. namespace Carbon::Check {
  18. // Returns the lookup scope corresponding to base_id, or nullopt if not a scope.
  19. // On invalid scopes, prints a diagnostic and still returns the scope.
  20. static auto GetAsLookupScope(Context& context, SemIR::LocId loc_id,
  21. SemIR::ConstantId base_const_id)
  22. -> std::optional<LookupScope> {
  23. auto base_id = context.constant_values().GetInstId(base_const_id);
  24. auto base = context.insts().Get(base_id);
  25. if (auto base_as_namespace = base.TryAs<SemIR::Namespace>()) {
  26. return LookupScope{.name_scope_id = base_as_namespace->name_scope_id,
  27. .specific_id = SemIR::SpecificId::Invalid};
  28. }
  29. // TODO: Consider refactoring the near-identical class and interface support
  30. // below.
  31. if (auto base_as_class = base.TryAs<SemIR::ClassType>()) {
  32. context.TryToDefineType(
  33. context.GetTypeIdForTypeConstant(base_const_id), [&] {
  34. CARBON_DIAGNOSTIC(QualifiedExprInIncompleteClassScope, Error,
  35. "member access into incomplete class {0}",
  36. InstIdAsType);
  37. return context.emitter().Build(
  38. loc_id, QualifiedExprInIncompleteClassScope, base_id);
  39. });
  40. auto& class_info = context.classes().Get(base_as_class->class_id);
  41. return LookupScope{.name_scope_id = class_info.scope_id,
  42. .specific_id = base_as_class->specific_id};
  43. }
  44. if (auto base_as_interface = base.TryAs<SemIR::InterfaceType>()) {
  45. context.TryToDefineType(
  46. context.GetTypeIdForTypeConstant(base_const_id), [&] {
  47. CARBON_DIAGNOSTIC(QualifiedExprInUndefinedInterfaceScope, Error,
  48. "member access into undefined interface {0}",
  49. InstIdAsType);
  50. return context.emitter().Build(
  51. loc_id, QualifiedExprInUndefinedInterfaceScope, base_id);
  52. });
  53. auto& interface_info =
  54. context.interfaces().Get(base_as_interface->interface_id);
  55. return LookupScope{.name_scope_id = interface_info.scope_id,
  56. .specific_id = base_as_interface->specific_id};
  57. }
  58. // TODO: Per the design, if `base_id` is any kind of type, then lookup should
  59. // treat it as a name scope, even if it doesn't have members. For example,
  60. // `(i32*).X` should fail because there's no name `X` in `i32*`, not because
  61. // there's no name `X` in `type`.
  62. return std::nullopt;
  63. }
  64. // Returns the index of the specified class element within the class's
  65. // representation.
  66. static auto GetClassElementIndex(Context& context, SemIR::InstId element_id)
  67. -> SemIR::ElementIndex {
  68. auto element_inst = context.insts().Get(element_id);
  69. if (auto field = element_inst.TryAs<SemIR::FieldDecl>()) {
  70. return field->index;
  71. }
  72. if (auto base = element_inst.TryAs<SemIR::BaseDecl>()) {
  73. return base->index;
  74. }
  75. CARBON_FATAL("Unexpected value {0} in class element name", element_inst);
  76. }
  77. // Returns whether `function_id` is an instance method, that is, whether it has
  78. // an implicit `self` parameter.
  79. static auto IsInstanceMethod(const SemIR::File& sem_ir,
  80. SemIR::FunctionId function_id) -> bool {
  81. const auto& function = sem_ir.functions().Get(function_id);
  82. for (auto param_id :
  83. sem_ir.inst_blocks().GetOrEmpty(function.implicit_param_patterns_id)) {
  84. if (SemIR::Function::GetNameFromPatternId(sem_ir, param_id) ==
  85. SemIR::NameId::SelfValue) {
  86. return true;
  87. }
  88. }
  89. return false;
  90. }
  91. // Returns the highest allowed access. For example, if this returns `Protected`
  92. // then only `Public` and `Protected` accesses are allowed--not `Private`.
  93. static auto GetHighestAllowedAccess(Context& context, SemIR::LocId loc_id,
  94. SemIR::ConstantId name_scope_const_id)
  95. -> SemIR::AccessKind {
  96. auto [_, self_type_inst_id] = context.LookupUnqualifiedName(
  97. loc_id.node_id(), SemIR::NameId::SelfType, /*required=*/false);
  98. if (!self_type_inst_id.is_valid()) {
  99. return SemIR::AccessKind::Public;
  100. }
  101. // TODO: Support other types for `Self`.
  102. auto self_class_type =
  103. context.insts().TryGetAs<SemIR::ClassType>(self_type_inst_id);
  104. if (!self_class_type) {
  105. return SemIR::AccessKind::Public;
  106. }
  107. auto self_class_info = context.classes().Get(self_class_type->class_id);
  108. // TODO: Support other types.
  109. if (auto class_type = context.insts().TryGetAs<SemIR::ClassType>(
  110. context.constant_values().GetInstId(name_scope_const_id))) {
  111. auto class_info = context.classes().Get(class_type->class_id);
  112. if (self_class_info.self_type_id == class_info.self_type_id) {
  113. return SemIR::AccessKind::Private;
  114. }
  115. // If the `type_id` of `Self` does not match with the one we're currently
  116. // accessing, try checking if this class is of the parent type of `Self`.
  117. if (auto base_decl = context.insts().TryGetAsIfValid<SemIR::BaseDecl>(
  118. self_class_info.base_id)) {
  119. if (base_decl->base_type_id == class_info.self_type_id) {
  120. return SemIR::AccessKind::Protected;
  121. }
  122. } else if (auto adapt_decl =
  123. context.insts().TryGetAsIfValid<SemIR::AdaptDecl>(
  124. self_class_info.adapt_id)) {
  125. if (adapt_decl->adapted_type_id == class_info.self_type_id) {
  126. return SemIR::AccessKind::Protected;
  127. }
  128. }
  129. }
  130. return SemIR::AccessKind::Public;
  131. }
  132. // Returns whether `scope` is a scope for which impl lookup should be performed
  133. // if we find an associated entity.
  134. static auto ScopeNeedsImplLookup(Context& context, LookupScope scope) -> bool {
  135. auto [_, inst] = context.name_scopes().GetInstIfValid(scope.name_scope_id);
  136. if (!inst) {
  137. return false;
  138. }
  139. if (inst->Is<SemIR::InterfaceDecl>()) {
  140. // Don't perform impl lookup if an associated entity is named as a member of
  141. // a facet type.
  142. return false;
  143. }
  144. if (inst->Is<SemIR::Namespace>()) {
  145. // Don't perform impl lookup if an associated entity is named as a namespace
  146. // member.
  147. // TODO: This case is not yet listed in the design.
  148. return false;
  149. }
  150. // Any other kind of scope is assumed to be a type that implements the
  151. // interface containing the associated entity, and impl lookup is performed.
  152. return true;
  153. }
  154. // Performs impl lookup for a member name expression. This finds the relevant
  155. // impl witness and extracts the corresponding impl member.
  156. static auto PerformImplLookup(
  157. Context& context, SemIR::LocId loc_id, SemIR::ConstantId type_const_id,
  158. SemIR::AssociatedEntityType assoc_type, SemIR::InstId member_id,
  159. Context::BuildDiagnosticFn missing_impl_diagnoser = nullptr)
  160. -> SemIR::InstId {
  161. auto interface_type =
  162. context.types().GetAs<SemIR::InterfaceType>(assoc_type.interface_type_id);
  163. auto& interface = context.interfaces().Get(interface_type.interface_id);
  164. auto witness_id =
  165. LookupInterfaceWitness(context, loc_id, type_const_id,
  166. assoc_type.interface_type_id.AsConstantId());
  167. if (!witness_id.is_valid()) {
  168. if (missing_impl_diagnoser) {
  169. // TODO: Pass in the expression whose type we are printing.
  170. CARBON_DIAGNOSTIC(MissingImplInMemberAccessNote, Note,
  171. "type {1} does not implement interface `{0}`",
  172. SemIR::NameId, SemIR::TypeId);
  173. missing_impl_diagnoser()
  174. .Note(loc_id, MissingImplInMemberAccessNote, interface.name_id,
  175. context.GetTypeIdForTypeConstant(type_const_id))
  176. .Emit();
  177. } else {
  178. // TODO: Pass in the expression whose type we are printing.
  179. CARBON_DIAGNOSTIC(MissingImplInMemberAccess, Error,
  180. "cannot access member of interface `{0}` in type {1} "
  181. "that does not implement that interface",
  182. SemIR::NameId, SemIR::TypeId);
  183. context.emitter().Emit(loc_id, MissingImplInMemberAccess,
  184. interface.name_id,
  185. context.GetTypeIdForTypeConstant(type_const_id));
  186. }
  187. return SemIR::InstId::BuiltinError;
  188. }
  189. auto member_value_id = context.constant_values().GetConstantInstId(member_id);
  190. if (!member_value_id.is_valid()) {
  191. if (member_value_id != SemIR::InstId::BuiltinError) {
  192. context.TODO(member_id, "non-constant associated entity");
  193. }
  194. return SemIR::InstId::BuiltinError;
  195. }
  196. auto assoc_entity =
  197. context.insts().TryGetAs<SemIR::AssociatedEntity>(member_value_id);
  198. if (!assoc_entity) {
  199. context.TODO(member_id, "unexpected value for associated entity");
  200. return SemIR::InstId::BuiltinError;
  201. }
  202. // TODO: This produces the type of the associated entity with no value for
  203. // `Self`. The type `Self` might appear in the type of an associated constant,
  204. // and if so, we'll need to substitute it here somehow.
  205. auto subst_type_id = SemIR::GetTypeInSpecific(
  206. context.sem_ir(), interface_type.specific_id, assoc_type.entity_type_id);
  207. return context.GetOrAddInst<SemIR::InterfaceWitnessAccess>(
  208. loc_id, {.type_id = subst_type_id,
  209. .witness_id = witness_id,
  210. .index = assoc_entity->index});
  211. }
  212. // Performs a member name lookup into the specified scope, including performing
  213. // impl lookup if necessary. If the scope is invalid, assume an error has
  214. // already been diagnosed, and return BuiltinError.
  215. static auto LookupMemberNameInScope(Context& context, SemIR::LocId loc_id,
  216. SemIR::InstId /*base_id*/,
  217. SemIR::NameId name_id,
  218. SemIR::ConstantId name_scope_const_id,
  219. LookupScope lookup_scope) -> SemIR::InstId {
  220. LookupResult result = {.specific_id = SemIR::SpecificId::Invalid,
  221. .inst_id = SemIR::InstId::BuiltinError};
  222. if (lookup_scope.name_scope_id.is_valid()) {
  223. AccessInfo access_info = {
  224. .constant_id = name_scope_const_id,
  225. .highest_allowed_access =
  226. GetHighestAllowedAccess(context, loc_id, name_scope_const_id),
  227. };
  228. result = context.LookupQualifiedName(loc_id, name_id, lookup_scope,
  229. /*required=*/true, access_info);
  230. if (!result.inst_id.is_valid()) {
  231. return SemIR::InstId::BuiltinError;
  232. }
  233. }
  234. // TODO: This duplicates the work that HandleNameAsExpr does. Factor this out.
  235. auto inst = context.insts().Get(result.inst_id);
  236. auto type_id = SemIR::GetTypeInSpecific(context.sem_ir(), result.specific_id,
  237. inst.type_id());
  238. CARBON_CHECK(type_id.is_valid(), "Missing type for member {0}", inst);
  239. // If the named entity has a constant value that depends on its specific,
  240. // store the specific too.
  241. if (result.specific_id.is_valid() &&
  242. context.constant_values().Get(result.inst_id).is_symbolic()) {
  243. result.inst_id = context.GetOrAddInst<SemIR::SpecificConstant>(
  244. loc_id, {.type_id = type_id,
  245. .inst_id = result.inst_id,
  246. .specific_id = result.specific_id});
  247. }
  248. // TODO: Use a different kind of instruction that also references the
  249. // `base_id` so that `SemIR` consumers can find it.
  250. auto member_id = context.GetOrAddInst<SemIR::NameRef>(
  251. loc_id,
  252. {.type_id = type_id, .name_id = name_id, .value_id = result.inst_id});
  253. // If member name lookup finds an associated entity name, and the scope is not
  254. // a facet type, perform impl lookup.
  255. //
  256. // TODO: We need to do this as part of searching extended scopes, because a
  257. // lookup that finds an associated entity and also finds the corresponding
  258. // impl member is not supposed to be treated as ambiguous.
  259. if (auto assoc_type =
  260. context.types().TryGetAs<SemIR::AssociatedEntityType>(type_id)) {
  261. if (ScopeNeedsImplLookup(context, lookup_scope)) {
  262. member_id = PerformImplLookup(context, loc_id, name_scope_const_id,
  263. *assoc_type, member_id);
  264. }
  265. }
  266. return member_id;
  267. }
  268. // Performs the instance binding step in member access. If the found member is a
  269. // field, forms a class member access. If the found member is an instance
  270. // method, forms a bound method. Otherwise, the member is returned unchanged.
  271. static auto PerformInstanceBinding(Context& context, SemIR::LocId loc_id,
  272. SemIR::InstId base_id,
  273. SemIR::InstId member_id) -> SemIR::InstId {
  274. auto member_type_id = context.insts().Get(member_id).type_id();
  275. CARBON_KIND_SWITCH(context.types().GetAsInst(member_type_id)) {
  276. case CARBON_KIND(SemIR::UnboundElementType unbound_element_type): {
  277. // Convert the base to the type of the element if necessary.
  278. base_id = ConvertToValueOrRefOfType(context, loc_id, base_id,
  279. unbound_element_type.class_type_id);
  280. // Find the specified element, which could be either a field or a base
  281. // class, and build an element access expression.
  282. auto element_id = context.constant_values().GetConstantInstId(member_id);
  283. CARBON_CHECK(element_id.is_valid(),
  284. "Non-constant value {0} of unbound element type",
  285. context.insts().Get(member_id));
  286. auto index = GetClassElementIndex(context, element_id);
  287. auto access_id = context.GetOrAddInst<SemIR::ClassElementAccess>(
  288. loc_id, {.type_id = unbound_element_type.element_type_id,
  289. .base_id = base_id,
  290. .index = index});
  291. if (SemIR::GetExprCategory(context.sem_ir(), base_id) ==
  292. SemIR::ExprCategory::Value &&
  293. SemIR::GetExprCategory(context.sem_ir(), access_id) !=
  294. SemIR::ExprCategory::Value) {
  295. // Class element access on a value expression produces an ephemeral
  296. // reference if the class's value representation is a pointer to the
  297. // object representation. Add a value binding in that case so that the
  298. // expression category of the result matches the expression category of
  299. // the base.
  300. access_id = ConvertToValueExpr(context, access_id);
  301. }
  302. return access_id;
  303. }
  304. case CARBON_KIND(SemIR::FunctionType fn_type): {
  305. if (IsInstanceMethod(context.sem_ir(), fn_type.function_id)) {
  306. return context.GetOrAddInst<SemIR::BoundMethod>(
  307. loc_id, {.type_id = context.GetBuiltinType(
  308. SemIR::BuiltinInstKind::BoundMethodType),
  309. .object_id = base_id,
  310. .function_id = member_id});
  311. }
  312. [[fallthrough]];
  313. }
  314. default:
  315. // Not an instance member: no instance binding.
  316. return member_id;
  317. }
  318. }
  319. // Validates that the index (required to be an IntValue) is valid within the
  320. // tuple size. Returns the index on success, or nullptr on failure.
  321. static auto ValidateTupleIndex(Context& context, SemIR::LocId loc_id,
  322. SemIR::InstId operand_inst_id,
  323. SemIR::IntValue index_inst, int size)
  324. -> const llvm::APInt* {
  325. const auto& index_val = context.ints().Get(index_inst.int_id);
  326. if (index_val.uge(size)) {
  327. CARBON_DIAGNOSTIC(TupleIndexOutOfBounds, Error,
  328. "tuple element index `{0}` is past the end of type {1}",
  329. TypedInt, TypeOfInstId);
  330. context.emitter().Emit(loc_id, TupleIndexOutOfBounds,
  331. {.type = index_inst.type_id, .value = index_val},
  332. operand_inst_id);
  333. return nullptr;
  334. }
  335. return &index_val;
  336. }
  337. auto PerformMemberAccess(Context& context, SemIR::LocId loc_id,
  338. SemIR::InstId base_id, SemIR::NameId name_id)
  339. -> SemIR::InstId {
  340. // If the base is a name scope, such as a class or namespace, perform lookup
  341. // into that scope.
  342. if (auto base_const_id = context.constant_values().Get(base_id);
  343. base_const_id.is_constant()) {
  344. if (auto lookup_scope = GetAsLookupScope(context, loc_id, base_const_id)) {
  345. return LookupMemberNameInScope(context, loc_id, base_id, name_id,
  346. base_const_id, *lookup_scope);
  347. }
  348. }
  349. // If the base isn't a scope, it must have a complete type.
  350. auto base_type_id = context.insts().Get(base_id).type_id();
  351. if (!context.TryToCompleteType(base_type_id, [&] {
  352. CARBON_DIAGNOSTIC(IncompleteTypeInMemberAccess, Error,
  353. "member access into object of incomplete type {0}",
  354. TypeOfInstId);
  355. return context.emitter().Build(base_id, IncompleteTypeInMemberAccess,
  356. base_id);
  357. })) {
  358. return SemIR::InstId::BuiltinError;
  359. }
  360. // Materialize a temporary for the base expression if necessary.
  361. base_id = ConvertToValueOrRefExpr(context, base_id);
  362. base_type_id = context.insts().Get(base_id).type_id();
  363. auto base_type_const_id = context.types().GetConstantId(base_type_id);
  364. // Find the scope corresponding to the base type.
  365. auto lookup_scope = GetAsLookupScope(context, loc_id, base_type_const_id);
  366. if (!lookup_scope) {
  367. // The base type is not a name scope. Try some fallback options.
  368. if (auto struct_type = context.insts().TryGetAs<SemIR::StructType>(
  369. context.constant_values().GetInstId(base_type_const_id))) {
  370. // TODO: Do we need to optimize this with a lookup table for O(1)?
  371. for (auto [i, field] : llvm::enumerate(
  372. context.struct_type_fields().Get(struct_type->fields_id))) {
  373. if (name_id == field.name_id) {
  374. // TODO: Model this as producing a lookup result, and do instance
  375. // binding separately. Perhaps a struct type should be a name scope.
  376. return context.GetOrAddInst<SemIR::StructAccess>(
  377. loc_id, {.type_id = field.type_id,
  378. .struct_id = base_id,
  379. .index = SemIR::ElementIndex(i)});
  380. }
  381. }
  382. CARBON_DIAGNOSTIC(QualifiedExprNameNotFound, Error,
  383. "type {0} does not have a member `{1}`", TypeOfInstId,
  384. SemIR::NameId);
  385. context.emitter().Emit(loc_id, QualifiedExprNameNotFound, base_id,
  386. name_id);
  387. return SemIR::InstId::BuiltinError;
  388. }
  389. if (base_type_id != SemIR::TypeId::Error) {
  390. CARBON_DIAGNOSTIC(QualifiedExprUnsupported, Error,
  391. "type {0} does not support qualified expressions",
  392. TypeOfInstId);
  393. context.emitter().Emit(loc_id, QualifiedExprUnsupported, base_id);
  394. }
  395. return SemIR::InstId::BuiltinError;
  396. }
  397. // Perform lookup into the base type.
  398. auto member_id = LookupMemberNameInScope(context, loc_id, base_id, name_id,
  399. base_type_const_id, *lookup_scope);
  400. // Perform instance binding if we found an instance member.
  401. member_id = PerformInstanceBinding(context, loc_id, base_id, member_id);
  402. return member_id;
  403. }
  404. auto PerformCompoundMemberAccess(
  405. Context& context, SemIR::LocId loc_id, SemIR::InstId base_id,
  406. SemIR::InstId member_expr_id,
  407. Context::BuildDiagnosticFn missing_impl_diagnoser) -> SemIR::InstId {
  408. // Materialize a temporary for the base expression if necessary.
  409. base_id = ConvertToValueOrRefExpr(context, base_id);
  410. auto base_type_id = context.insts().Get(base_id).type_id();
  411. auto base_type_const_id = context.types().GetConstantId(base_type_id);
  412. auto member_id = member_expr_id;
  413. auto member = context.insts().Get(member_id);
  414. // If the member expression names an associated entity, impl lookup is always
  415. // performed using the type of the base expression.
  416. if (auto assoc_type = context.types().TryGetAs<SemIR::AssociatedEntityType>(
  417. member.type_id())) {
  418. member_id =
  419. PerformImplLookup(context, loc_id, base_type_const_id, *assoc_type,
  420. member_id, missing_impl_diagnoser);
  421. } else if (context.insts().Is<SemIR::TupleType>(
  422. context.constant_values().GetInstId(base_type_const_id))) {
  423. return PerformTupleAccess(context, loc_id, base_id, member_expr_id);
  424. }
  425. // Perform instance binding if we found an instance member.
  426. member_id = PerformInstanceBinding(context, loc_id, base_id, member_id);
  427. // If we didn't perform impl lookup or instance binding, that's an error
  428. // because the base expression is not used for anything.
  429. if (member_id == member_expr_id && member.type_id() != SemIR::TypeId::Error) {
  430. CARBON_DIAGNOSTIC(CompoundMemberAccessDoesNotUseBase, Error,
  431. "member name of type {0} in compound member access is "
  432. "not an instance member or an interface member",
  433. TypeOfInstId);
  434. context.emitter().Emit(loc_id, CompoundMemberAccessDoesNotUseBase,
  435. member_id);
  436. }
  437. return member_id;
  438. }
  439. auto PerformTupleAccess(Context& context, SemIR::LocId loc_id,
  440. SemIR::InstId tuple_inst_id,
  441. SemIR::InstId index_inst_id) -> SemIR::InstId {
  442. tuple_inst_id = ConvertToValueOrRefExpr(context, tuple_inst_id);
  443. auto tuple_type_id = context.insts().Get(tuple_inst_id).type_id();
  444. auto tuple_type = context.types().TryGetAs<SemIR::TupleType>(tuple_type_id);
  445. if (!tuple_type) {
  446. CARBON_DIAGNOSTIC(TupleIndexOnANonTupleType, Error,
  447. "type {0} does not support tuple indexing; only "
  448. "tuples can be indexed that way",
  449. TypeOfInstId);
  450. context.emitter().Emit(loc_id, TupleIndexOnANonTupleType, tuple_inst_id);
  451. return SemIR::InstId::BuiltinError;
  452. }
  453. SemIR::TypeId element_type_id = SemIR::TypeId::Error;
  454. auto index_node_id = context.insts().GetLocId(index_inst_id);
  455. index_inst_id = ConvertToValueOfType(
  456. context, index_node_id, index_inst_id,
  457. context.GetBuiltinType(SemIR::BuiltinInstKind::IntType));
  458. auto index_const_id = context.constant_values().Get(index_inst_id);
  459. if (index_const_id == SemIR::ConstantId::Error) {
  460. return SemIR::InstId::BuiltinError;
  461. } else if (!index_const_id.is_template()) {
  462. // TODO: Decide what to do if the index is a symbolic constant.
  463. CARBON_DIAGNOSTIC(TupleIndexNotConstant, Error,
  464. "tuple index must be a constant");
  465. context.emitter().Emit(loc_id, TupleIndexNotConstant);
  466. return SemIR::InstId::BuiltinError;
  467. }
  468. auto index_literal = context.insts().GetAs<SemIR::IntValue>(
  469. context.constant_values().GetInstId(index_const_id));
  470. auto type_block = context.type_blocks().Get(tuple_type->elements_id);
  471. const auto* index_val = ValidateTupleIndex(context, loc_id, tuple_inst_id,
  472. index_literal, type_block.size());
  473. if (!index_val) {
  474. return SemIR::InstId::BuiltinError;
  475. }
  476. // TODO: Handle the case when `index_val->getZExtValue()` has too many bits.
  477. element_type_id = type_block[index_val->getZExtValue()];
  478. auto tuple_index = SemIR::ElementIndex(index_val->getZExtValue());
  479. return context.GetOrAddInst<SemIR::TupleAccess>(loc_id,
  480. {.type_id = element_type_id,
  481. .tuple_id = tuple_inst_id,
  482. .index = tuple_index});
  483. }
  484. } // namespace Carbon::Check