member_access.cpp 27 KB

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