member_access.cpp 26 KB

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