member_access.cpp 25 KB

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