member_access.cpp 26 KB

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