member_access.cpp 28 KB

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