member_access.cpp 26 KB

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