member_access.cpp 27 KB

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