member_access.cpp 26 KB

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