member_access.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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 context.GetOrAddInst<SemIR::ImplWitnessAccess>(
  156. loc_id, {.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. Context::BuildDiagnosticFn missing_impl_diagnoser = nullptr)
  166. -> SemIR::InstId {
  167. auto interface_type =
  168. GetInterfaceFromFacetType(context, assoc_type.interface_type_id);
  169. if (!interface_type) {
  170. context.TODO(loc_id,
  171. "Lookup of impl witness not yet supported except for a single "
  172. "interface");
  173. return SemIR::ErrorInst::SingletonInstId;
  174. }
  175. auto self_type_id = context.types().GetTypeIdForTypeConstantId(type_const_id);
  176. auto witness_id =
  177. LookupImplWitness(context, loc_id, type_const_id,
  178. assoc_type.interface_type_id.AsConstantId());
  179. if (!witness_id.has_value()) {
  180. auto interface_type_id = GetInterfaceType(
  181. context, interface_type->interface_id, interface_type->specific_id);
  182. if (missing_impl_diagnoser) {
  183. // TODO: Pass in the expression whose type we are printing.
  184. CARBON_DIAGNOSTIC(MissingImplInMemberAccessNote, Note,
  185. "type {1} does not implement interface {0}",
  186. SemIR::TypeId, SemIR::TypeId);
  187. missing_impl_diagnoser()
  188. .Note(loc_id, MissingImplInMemberAccessNote, interface_type_id,
  189. self_type_id)
  190. .Emit();
  191. } else {
  192. // TODO: Pass in the expression whose type we are printing.
  193. CARBON_DIAGNOSTIC(MissingImplInMemberAccess, Error,
  194. "cannot access member of interface {0} in type {1} "
  195. "that does not implement that interface",
  196. SemIR::TypeId, SemIR::TypeId);
  197. context.emitter().Emit(loc_id, MissingImplInMemberAccess,
  198. interface_type_id, self_type_id);
  199. }
  200. return SemIR::ErrorInst::SingletonInstId;
  201. }
  202. return AccessMemberOfImplWitness(context, loc_id, self_type_id, witness_id,
  203. interface_type->specific_id, member_id);
  204. }
  205. // Performs a member name lookup into the specified scope, including performing
  206. // impl lookup if necessary. If the scope result is `None`, assume an error has
  207. // already been diagnosed, and return `ErrorInst`.
  208. static auto LookupMemberNameInScope(Context& context, SemIR::LocId loc_id,
  209. SemIR::InstId base_id,
  210. SemIR::NameId name_id,
  211. SemIR::ConstantId name_scope_const_id,
  212. llvm::ArrayRef<LookupScope> lookup_scopes,
  213. bool lookup_in_type_of_base)
  214. -> SemIR::InstId {
  215. AccessInfo access_info = {
  216. .constant_id = name_scope_const_id,
  217. .highest_allowed_access =
  218. GetHighestAllowedAccess(context, loc_id, name_scope_const_id),
  219. };
  220. LookupResult result =
  221. LookupQualifiedName(context, loc_id, name_id, lookup_scopes,
  222. /*required=*/true, access_info);
  223. if (!result.scope_result.is_found()) {
  224. return SemIR::ErrorInst::SingletonInstId;
  225. }
  226. // TODO: This duplicates the work that HandleNameAsExpr does. Factor this out.
  227. auto inst = context.insts().Get(result.scope_result.target_inst_id());
  228. auto type_id = SemIR::GetTypeInSpecific(context.sem_ir(), result.specific_id,
  229. inst.type_id());
  230. CARBON_CHECK(type_id.has_value(), "Missing type for member {0}", inst);
  231. // If the named entity has a constant value that depends on its specific,
  232. // store the specific too.
  233. if (result.specific_id.has_value() &&
  234. context.constant_values()
  235. .Get(result.scope_result.target_inst_id())
  236. .is_symbolic()) {
  237. result.scope_result = SemIR::ScopeLookupResult::MakeFound(
  238. context.GetOrAddInst<SemIR::SpecificConstant>(
  239. loc_id, {.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 = context.GetOrAddInst<SemIR::NameRef>(
  247. loc_id, {.type_id = type_id,
  248. .name_id = name_id,
  249. .value_id = result.scope_result.target_inst_id()});
  250. // If member name lookup finds an associated entity name, and the scope is not
  251. // a facet type, perform impl lookup.
  252. //
  253. // TODO: We need to do this as part of searching extended scopes, because a
  254. // lookup that finds an associated entity and also finds the corresponding
  255. // impl member is not supposed to be treated as ambiguous.
  256. if (auto assoc_type =
  257. context.types().TryGetAs<SemIR::AssociatedEntityType>(type_id)) {
  258. if (lookup_in_type_of_base) {
  259. SemIR::TypeId base_type_id = context.insts().Get(base_id).type_id();
  260. if (base_type_id != SemIR::TypeType::SingletonTypeId &&
  261. context.types().IsFacetType(base_type_id)) {
  262. // Handles `T.F` when `T` is a non-type facet.
  263. auto base_as_type = ExprAsType(context, loc_id, base_id);
  264. auto assoc_interface =
  265. GetInterfaceFromFacetType(context, assoc_type->interface_type_id);
  266. // An associated entity should always be associated with a single
  267. // interface.
  268. CARBON_CHECK(assoc_interface);
  269. // First look for `*assoc_interface` in the type of the base. If it is
  270. // found, get the witness that the interface is implemented from
  271. // `base_id`.
  272. auto facet_type = context.types().GetAs<SemIR::FacetType>(base_type_id);
  273. const auto& facet_type_info =
  274. context.facet_types().Get(facet_type.facet_type_id);
  275. // Witness that `T` implements the `*assoc_interface`.
  276. SemIR::InstId witness_inst_id = SemIR::InstId::None;
  277. for (auto base_interface : facet_type_info.impls_constraints) {
  278. // Get the witness that `T` implements `base_type_id`.
  279. if (base_interface == *assoc_interface) {
  280. witness_inst_id = context.GetOrAddInst<SemIR::FacetAccessWitness>(
  281. loc_id, {.type_id = GetSingletonType(
  282. context, SemIR::WitnessType::SingletonInstId),
  283. .facet_value_inst_id = base_id});
  284. // TODO: Result will eventually be a facet type witness instead of
  285. // an interface witness. Will need to use the index
  286. // `*assoc_interface` was found in
  287. // `facet_type_info.impls_constraints` to get the correct interface
  288. // witness out.
  289. break;
  290. }
  291. }
  292. // TODO: If that fails, would need to do impl lookup to see if the facet
  293. // value implements the interface of `*assoc_type`.
  294. if (!witness_inst_id.has_value()) {
  295. context.TODO(member_id,
  296. "associated entity not found in facet type, need to do "
  297. "impl lookup");
  298. return SemIR::ErrorInst::SingletonInstId;
  299. }
  300. member_id = AccessMemberOfImplWitness(
  301. context, loc_id, base_as_type.type_id, witness_inst_id,
  302. assoc_interface->specific_id, member_id);
  303. } else {
  304. // Handles `x.F` if `x` is of type `class C` that extends an interface
  305. // containing `F`.
  306. SemIR::ConstantId constant_id =
  307. context.types().GetConstantId(base_type_id);
  308. member_id = PerformImplLookup(context, loc_id, constant_id, *assoc_type,
  309. member_id);
  310. }
  311. } else if (ScopeNeedsImplLookup(context, name_scope_const_id)) {
  312. // Handles `T.F` where `T` is a type extending an interface containing
  313. // `F`.
  314. member_id = PerformImplLookup(context, loc_id, name_scope_const_id,
  315. *assoc_type, member_id);
  316. }
  317. }
  318. return member_id;
  319. }
  320. // Performs the instance binding step in member access. If the found member is a
  321. // field, forms a class member access. If the found member is an instance
  322. // method, forms a bound method. Otherwise, the member is returned unchanged.
  323. static auto PerformInstanceBinding(Context& context, SemIR::LocId loc_id,
  324. SemIR::InstId base_id,
  325. SemIR::InstId member_id) -> SemIR::InstId {
  326. // If the member is a function, check whether it's an instance method.
  327. if (auto callee = SemIR::GetCalleeFunction(context.sem_ir(), member_id);
  328. callee.function_id.has_value()) {
  329. if (!IsInstanceMethod(context.sem_ir(), callee.function_id) ||
  330. callee.self_id.has_value()) {
  331. // Found a static member function or an already-bound method.
  332. return member_id;
  333. }
  334. return context.GetOrAddInst<SemIR::BoundMethod>(
  335. loc_id, {.type_id = GetSingletonType(
  336. context, SemIR::BoundMethodType::SingletonInstId),
  337. .object_id = base_id,
  338. .function_decl_id = member_id});
  339. }
  340. // Otherwise, if it's a field, form a class element access.
  341. if (auto unbound_element_type =
  342. context.types().TryGetAs<SemIR::UnboundElementType>(
  343. context.insts().Get(member_id).type_id())) {
  344. // Convert the base to the type of the element if necessary.
  345. base_id = ConvertToValueOrRefOfType(context, loc_id, base_id,
  346. unbound_element_type->class_type_id);
  347. // Find the specified element, which could be either a field or a base
  348. // class, and build an element access expression.
  349. auto element_id = context.constant_values().GetConstantInstId(member_id);
  350. CARBON_CHECK(element_id.has_value(),
  351. "Non-constant value {0} of unbound element type",
  352. context.insts().Get(member_id));
  353. auto index = GetClassElementIndex(context, element_id);
  354. auto access_id = context.GetOrAddInst<SemIR::ClassElementAccess>(
  355. loc_id, {.type_id = unbound_element_type->element_type_id,
  356. .base_id = base_id,
  357. .index = index});
  358. if (SemIR::GetExprCategory(context.sem_ir(), base_id) ==
  359. SemIR::ExprCategory::Value &&
  360. SemIR::GetExprCategory(context.sem_ir(), access_id) !=
  361. SemIR::ExprCategory::Value) {
  362. // Class element access on a value expression produces an ephemeral
  363. // reference if the class's value representation is a pointer to the
  364. // object representation. Add a value binding in that case so that the
  365. // expression category of the result matches the expression category
  366. // of the base.
  367. access_id = ConvertToValueExpr(context, access_id);
  368. }
  369. return access_id;
  370. }
  371. // Not an instance member: no instance binding.
  372. return member_id;
  373. }
  374. // Validates that the index (required to be an IntValue) is valid within the
  375. // tuple size. Returns the index on success, or nullptr on failure.
  376. static auto ValidateTupleIndex(Context& context, SemIR::LocId loc_id,
  377. SemIR::InstId operand_inst_id,
  378. SemIR::IntValue index_inst, int size)
  379. -> std::optional<llvm::APInt> {
  380. llvm::APInt index_val = context.ints().Get(index_inst.int_id);
  381. if (index_val.uge(size)) {
  382. CARBON_DIAGNOSTIC(TupleIndexOutOfBounds, Error,
  383. "tuple element index `{0}` is past the end of type {1}",
  384. TypedInt, TypeOfInstId);
  385. context.emitter().Emit(loc_id, TupleIndexOutOfBounds,
  386. {.type = index_inst.type_id, .value = index_val},
  387. operand_inst_id);
  388. return std::nullopt;
  389. }
  390. return index_val;
  391. }
  392. auto PerformMemberAccess(Context& context, SemIR::LocId loc_id,
  393. SemIR::InstId base_id, SemIR::NameId name_id)
  394. -> SemIR::InstId {
  395. // If the base is a name scope, such as a class or namespace, perform lookup
  396. // into that scope.
  397. if (auto base_const_id = context.constant_values().Get(base_id);
  398. base_const_id.is_constant()) {
  399. llvm::SmallVector<LookupScope> lookup_scopes;
  400. if (AppendLookupScopesForConstant(context, loc_id, base_const_id,
  401. &lookup_scopes)) {
  402. return LookupMemberNameInScope(context, loc_id, base_id, name_id,
  403. base_const_id, lookup_scopes,
  404. /*lookup_in_type_of_base=*/false);
  405. }
  406. }
  407. // If the base isn't a scope, it must have a complete type.
  408. auto base_type_id = context.insts().Get(base_id).type_id();
  409. if (!RequireCompleteType(
  410. context, base_type_id, context.insts().GetLocId(base_id), [&] {
  411. CARBON_DIAGNOSTIC(
  412. IncompleteTypeInMemberAccess, Error,
  413. "member access into object of incomplete type {0}",
  414. TypeOfInstId);
  415. return context.emitter().Build(
  416. base_id, IncompleteTypeInMemberAccess, base_id);
  417. })) {
  418. return SemIR::ErrorInst::SingletonInstId;
  419. }
  420. // Materialize a temporary for the base expression if necessary.
  421. base_id = ConvertToValueOrRefExpr(context, base_id);
  422. base_type_id = context.insts().Get(base_id).type_id();
  423. auto base_type_const_id = context.types().GetConstantId(base_type_id);
  424. // Find the scope corresponding to the base type.
  425. llvm::SmallVector<LookupScope> lookup_scopes;
  426. if (!AppendLookupScopesForConstant(context, loc_id, base_type_const_id,
  427. &lookup_scopes)) {
  428. // The base type is not a name scope. Try some fallback options.
  429. if (auto struct_type = context.insts().TryGetAs<SemIR::StructType>(
  430. context.constant_values().GetInstId(base_type_const_id))) {
  431. // TODO: Do we need to optimize this with a lookup table for O(1)?
  432. for (auto [i, field] : llvm::enumerate(
  433. context.struct_type_fields().Get(struct_type->fields_id))) {
  434. if (name_id == field.name_id) {
  435. // TODO: Model this as producing a lookup result, and do instance
  436. // binding separately. Perhaps a struct type should be a name scope.
  437. return context.GetOrAddInst<SemIR::StructAccess>(
  438. loc_id, {.type_id = field.type_id,
  439. .struct_id = base_id,
  440. .index = SemIR::ElementIndex(i)});
  441. }
  442. }
  443. CARBON_DIAGNOSTIC(QualifiedExprNameNotFound, Error,
  444. "type {0} does not have a member `{1}`", TypeOfInstId,
  445. SemIR::NameId);
  446. context.emitter().Emit(loc_id, QualifiedExprNameNotFound, base_id,
  447. name_id);
  448. return SemIR::ErrorInst::SingletonInstId;
  449. }
  450. if (base_type_id != SemIR::ErrorInst::SingletonTypeId) {
  451. CARBON_DIAGNOSTIC(QualifiedExprUnsupported, Error,
  452. "type {0} does not support qualified expressions",
  453. TypeOfInstId);
  454. context.emitter().Emit(loc_id, QualifiedExprUnsupported, base_id);
  455. }
  456. return SemIR::ErrorInst::SingletonInstId;
  457. }
  458. // Perform lookup into the base type.
  459. auto member_id = LookupMemberNameInScope(context, loc_id, base_id, name_id,
  460. base_type_const_id, lookup_scopes,
  461. /*lookup_in_type_of_base=*/true);
  462. // For name lookup into a facet, never perform instance binding.
  463. // TODO: According to the design, this should be a "lookup in base" lookup,
  464. // not a "lookup in type of base" lookup, and the facet itself should have
  465. // member names that directly name members of the `impl`.
  466. if (context.types().IsFacetType(base_type_id)) {
  467. return member_id;
  468. }
  469. // Perform instance binding if we found an instance member.
  470. member_id = PerformInstanceBinding(context, loc_id, base_id, member_id);
  471. return member_id;
  472. }
  473. auto PerformCompoundMemberAccess(
  474. Context& context, SemIR::LocId loc_id, SemIR::InstId base_id,
  475. SemIR::InstId member_expr_id,
  476. Context::BuildDiagnosticFn missing_impl_diagnoser) -> SemIR::InstId {
  477. auto base_type_id = context.insts().Get(base_id).type_id();
  478. auto base_type_const_id = context.types().GetConstantId(base_type_id);
  479. auto member_id = member_expr_id;
  480. auto member = context.insts().Get(member_id);
  481. // If the member expression names an associated entity, impl lookup is always
  482. // performed using the type of the base expression.
  483. if (auto assoc_type = context.types().TryGetAs<SemIR::AssociatedEntityType>(
  484. member.type_id())) {
  485. member_id =
  486. PerformImplLookup(context, loc_id, base_type_const_id, *assoc_type,
  487. member_id, missing_impl_diagnoser);
  488. } else if (context.insts().Is<SemIR::TupleType>(
  489. context.constant_values().GetInstId(base_type_const_id))) {
  490. return PerformTupleAccess(context, loc_id, base_id, member_expr_id);
  491. }
  492. // Perform instance binding if we found an instance member.
  493. member_id = PerformInstanceBinding(context, loc_id, base_id, member_id);
  494. // If we didn't perform impl lookup or instance binding, that's an error
  495. // because the base expression is not used for anything.
  496. if (member_id == member_expr_id &&
  497. member.type_id() != SemIR::ErrorInst::SingletonTypeId) {
  498. CARBON_DIAGNOSTIC(CompoundMemberAccessDoesNotUseBase, Error,
  499. "member name of type {0} in compound member access is "
  500. "not an instance member or an interface member",
  501. TypeOfInstId);
  502. context.emitter().Emit(loc_id, CompoundMemberAccessDoesNotUseBase,
  503. member_id);
  504. }
  505. return member_id;
  506. }
  507. auto PerformTupleAccess(Context& context, SemIR::LocId loc_id,
  508. SemIR::InstId tuple_inst_id,
  509. SemIR::InstId index_inst_id) -> SemIR::InstId {
  510. tuple_inst_id = ConvertToValueOrRefExpr(context, tuple_inst_id);
  511. auto tuple_type_id = context.insts().Get(tuple_inst_id).type_id();
  512. auto tuple_type = context.types().TryGetAs<SemIR::TupleType>(tuple_type_id);
  513. if (!tuple_type) {
  514. CARBON_DIAGNOSTIC(TupleIndexOnANonTupleType, Error,
  515. "type {0} does not support tuple indexing; only "
  516. "tuples can be indexed that way",
  517. TypeOfInstId);
  518. context.emitter().Emit(loc_id, TupleIndexOnANonTupleType, tuple_inst_id);
  519. return SemIR::ErrorInst::SingletonInstId;
  520. }
  521. auto diag_non_constant_index = [&] {
  522. // TODO: Decide what to do if the index is a symbolic constant.
  523. CARBON_DIAGNOSTIC(TupleIndexNotConstant, Error,
  524. "tuple index must be a constant");
  525. context.emitter().Emit(loc_id, TupleIndexNotConstant);
  526. return SemIR::ErrorInst::SingletonInstId;
  527. };
  528. // Diagnose a non-constant index prior to conversion to IntLiteral, because
  529. // the conversion will fail if the index is not constant.
  530. if (!context.constant_values().Get(index_inst_id).is_concrete()) {
  531. return diag_non_constant_index();
  532. }
  533. SemIR::TypeId element_type_id = SemIR::ErrorInst::SingletonTypeId;
  534. auto index_node_id = context.insts().GetLocId(index_inst_id);
  535. index_inst_id = ConvertToValueOfType(
  536. context, index_node_id, index_inst_id,
  537. GetSingletonType(context, SemIR::IntLiteralType::SingletonInstId));
  538. auto index_const_id = context.constant_values().Get(index_inst_id);
  539. if (index_const_id == SemIR::ErrorInst::SingletonConstantId) {
  540. return SemIR::ErrorInst::SingletonInstId;
  541. } else if (!index_const_id.is_concrete()) {
  542. return diag_non_constant_index();
  543. }
  544. auto index_literal = context.insts().GetAs<SemIR::IntValue>(
  545. context.constant_values().GetInstId(index_const_id));
  546. auto type_block = context.type_blocks().Get(tuple_type->elements_id);
  547. std::optional<llvm::APInt> index_val = ValidateTupleIndex(
  548. context, loc_id, tuple_inst_id, index_literal, type_block.size());
  549. if (!index_val) {
  550. return SemIR::ErrorInst::SingletonInstId;
  551. }
  552. // TODO: Handle the case when `index_val->getZExtValue()` has too many bits.
  553. element_type_id = type_block[index_val->getZExtValue()];
  554. auto tuple_index = SemIR::ElementIndex(index_val->getZExtValue());
  555. return context.GetOrAddInst<SemIR::TupleAccess>(loc_id,
  556. {.type_id = element_type_id,
  557. .tuple_id = tuple_inst_id,
  558. .index = tuple_index});
  559. }
  560. } // namespace Carbon::Check