member_access.cpp 26 KB

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