member_access.cpp 26 KB

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