member_access.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  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/action.h"
  9. #include "toolchain/check/context.h"
  10. #include "toolchain/check/convert.h"
  11. #include "toolchain/check/eval.h"
  12. #include "toolchain/check/impl_lookup.h"
  13. #include "toolchain/check/import_ref.h"
  14. #include "toolchain/check/interface.h"
  15. #include "toolchain/check/name_lookup.h"
  16. #include "toolchain/check/type.h"
  17. #include "toolchain/check/type_completion.h"
  18. #include "toolchain/diagnostics/diagnostic_emitter.h"
  19. #include "toolchain/sem_ir/expr_info.h"
  20. #include "toolchain/sem_ir/function.h"
  21. #include "toolchain/sem_ir/generic.h"
  22. #include "toolchain/sem_ir/ids.h"
  23. #include "toolchain/sem_ir/inst.h"
  24. #include "toolchain/sem_ir/name_scope.h"
  25. #include "toolchain/sem_ir/typed_insts.h"
  26. namespace Carbon::Check {
  27. // Returns the index of the specified class element within the class's
  28. // representation.
  29. static auto GetClassElementIndex(Context& context, SemIR::InstId element_id)
  30. -> SemIR::ElementIndex {
  31. auto element_inst = context.insts().Get(element_id);
  32. if (auto field = element_inst.TryAs<SemIR::FieldDecl>()) {
  33. return field->index;
  34. }
  35. if (auto base = element_inst.TryAs<SemIR::BaseDecl>()) {
  36. return base->index;
  37. }
  38. CARBON_FATAL("Unexpected value {0} in class element name", element_inst);
  39. }
  40. // Returns whether `function_id` is an instance method, that is, whether it has
  41. // an implicit `self` parameter.
  42. static auto IsInstanceMethod(const SemIR::File& sem_ir,
  43. SemIR::FunctionId function_id) -> bool {
  44. const auto& function = sem_ir.functions().Get(function_id);
  45. return function.self_param_id.has_value();
  46. }
  47. // Return whether `type_id`, the type of an associated entity, is for an
  48. // instance member (currently true only for instance methods).
  49. static auto IsInstanceType(Context& context, SemIR::TypeId type_id) -> bool {
  50. if (auto function_type =
  51. context.types().TryGetAs<SemIR::FunctionType>(type_id)) {
  52. return IsInstanceMethod(context.sem_ir(), function_type->function_id);
  53. }
  54. return false;
  55. }
  56. // Returns the highest allowed access. For example, if this returns `Protected`
  57. // then only `Public` and `Protected` accesses are allowed--not `Private`.
  58. static auto GetHighestAllowedAccess(Context& context, SemIR::LocId loc_id,
  59. SemIR::ConstantId name_scope_const_id)
  60. -> SemIR::AccessKind {
  61. SemIR::ScopeLookupResult lookup_result =
  62. LookupUnqualifiedName(context, loc_id.node_id(), SemIR::NameId::SelfType,
  63. /*required=*/false)
  64. .scope_result;
  65. CARBON_CHECK(!lookup_result.is_poisoned());
  66. if (!lookup_result.is_found()) {
  67. return SemIR::AccessKind::Public;
  68. }
  69. // TODO: Support other types for `Self`.
  70. auto self_class_type = context.insts().TryGetAs<SemIR::ClassType>(
  71. lookup_result.target_inst_id());
  72. if (!self_class_type) {
  73. return SemIR::AccessKind::Public;
  74. }
  75. auto self_class_info = context.classes().Get(self_class_type->class_id);
  76. // TODO: Support other types.
  77. if (auto class_type = context.insts().TryGetAs<SemIR::ClassType>(
  78. context.constant_values().GetInstId(name_scope_const_id))) {
  79. auto class_info = context.classes().Get(class_type->class_id);
  80. if (self_class_info.self_type_id == class_info.self_type_id) {
  81. return SemIR::AccessKind::Private;
  82. }
  83. // If the `type_id` of `Self` does not match with the one we're currently
  84. // accessing, try checking if this class is of the parent type of `Self`.
  85. if (auto base_type_id = self_class_info.GetBaseType(
  86. context.sem_ir(), self_class_type->specific_id);
  87. base_type_id.has_value()) {
  88. if (context.types().GetConstantId(base_type_id) == name_scope_const_id) {
  89. return SemIR::AccessKind::Protected;
  90. }
  91. // TODO: Also check whether this base class has a base class of its own.
  92. } else if (auto adapt_type_id = self_class_info.GetAdaptedType(
  93. context.sem_ir(), self_class_type->specific_id);
  94. adapt_type_id.has_value()) {
  95. if (context.types().GetConstantId(adapt_type_id) == name_scope_const_id) {
  96. // TODO: Should we be allowed to access protected fields of a type we
  97. // are adapting? The design doesn't allow this.
  98. return SemIR::AccessKind::Protected;
  99. }
  100. }
  101. }
  102. return SemIR::AccessKind::Public;
  103. }
  104. // Returns whether `scope` is a scope for which impl lookup should be performed
  105. // if we find an associated entity.
  106. static auto ScopeNeedsImplLookup(Context& context,
  107. SemIR::ConstantId name_scope_const_id)
  108. -> bool {
  109. SemIR::InstId inst_id =
  110. context.constant_values().GetInstId(name_scope_const_id);
  111. CARBON_CHECK(inst_id.has_value());
  112. SemIR::Inst inst = context.insts().Get(inst_id);
  113. if (inst.Is<SemIR::FacetType>()) {
  114. // Don't perform impl lookup if an associated entity is named as a member of
  115. // a facet type.
  116. return false;
  117. }
  118. if (inst.Is<SemIR::Namespace>()) {
  119. // Don't perform impl lookup if an associated entity is named as a namespace
  120. // member.
  121. // TODO: This case is not yet listed in the design.
  122. return false;
  123. }
  124. // Any other kind of scope is assumed to be a type that implements the
  125. // interface containing the associated entity, and impl lookup is performed.
  126. return true;
  127. }
  128. static auto GetInterfaceFromFacetType(Context& context, SemIR::TypeId type_id)
  129. -> std::optional<SemIR::FacetTypeInfo::ImplsConstraint> {
  130. auto facet_type = context.types().GetAs<SemIR::FacetType>(type_id);
  131. const auto& facet_type_info =
  132. context.facet_types().Get(facet_type.facet_type_id);
  133. return facet_type_info.TryAsSingleInterface();
  134. }
  135. static auto AccessMemberOfImplWitness(Context& context, SemIR::LocId loc_id,
  136. SemIR::TypeId self_type_id,
  137. SemIR::InstId witness_id,
  138. SemIR::SpecificId interface_specific_id,
  139. SemIR::InstId member_id)
  140. -> SemIR::InstId {
  141. auto member_value_id = context.constant_values().GetConstantInstId(member_id);
  142. if (!member_value_id.has_value()) {
  143. if (member_value_id != SemIR::ErrorInst::SingletonInstId) {
  144. context.TODO(member_id, "non-constant associated entity");
  145. }
  146. return SemIR::ErrorInst::SingletonInstId;
  147. }
  148. auto assoc_entity =
  149. context.insts().TryGetAs<SemIR::AssociatedEntity>(member_value_id);
  150. if (!assoc_entity) {
  151. context.TODO(member_id, "unexpected value for associated entity");
  152. return SemIR::ErrorInst::SingletonInstId;
  153. }
  154. // Substitute the interface specific and `Self` type into the type of the
  155. // associated entity to find the type of the member access.
  156. LoadImportRef(context, assoc_entity->decl_id);
  157. auto assoc_type_id = GetTypeForSpecificAssociatedEntity(
  158. context, loc_id, interface_specific_id, assoc_entity->decl_id,
  159. self_type_id, witness_id);
  160. return GetOrAddInst<SemIR::ImplWitnessAccess>(context, loc_id,
  161. {.type_id = assoc_type_id,
  162. .witness_id = witness_id,
  163. .index = assoc_entity->index});
  164. }
  165. // Performs impl lookup for a member name expression. This finds the relevant
  166. // impl witness and extracts the corresponding impl member.
  167. static auto PerformImplLookup(
  168. Context& context, SemIR::LocId loc_id, SemIR::ConstantId type_const_id,
  169. SemIR::AssociatedEntityType assoc_type, SemIR::InstId member_id,
  170. MakeDiagnosticBuilderFn missing_impl_diagnoser = nullptr) -> SemIR::InstId {
  171. auto interface_type =
  172. GetInterfaceFromFacetType(context, assoc_type.interface_type_id);
  173. // An associated entity is always associated with a single interface.
  174. CARBON_CHECK(interface_type);
  175. auto self_type_id = context.types().GetTypeIdForTypeConstantId(type_const_id);
  176. auto lookup_result =
  177. LookupImplWitness(context, loc_id, type_const_id,
  178. assoc_type.interface_type_id.AsConstantId());
  179. if (!lookup_result.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. // The query facet type given to `LookupImplWitness()` had only a single
  203. // interface in it, so the returned witness set will have the same. Convert
  204. // from the InstBlockId to the single ImplWitness instruction.
  205. auto witness_id = SemIR::InstId::None;
  206. if (lookup_result.has_error_value()) {
  207. witness_id = SemIR::ErrorInst::SingletonInstId;
  208. } else {
  209. auto witnesses = context.inst_blocks().Get(lookup_result.inst_block_id());
  210. CARBON_CHECK(witnesses.size() == 1);
  211. witness_id = witnesses[0];
  212. }
  213. return AccessMemberOfImplWitness(context, loc_id, self_type_id, witness_id,
  214. interface_type->specific_id, member_id);
  215. }
  216. // Performs a member name lookup into the specified scope, including performing
  217. // impl lookup if necessary. If the scope result is `None`, assume an error has
  218. // already been diagnosed, and return `ErrorInst`.
  219. static auto LookupMemberNameInScope(Context& context, SemIR::LocId loc_id,
  220. SemIR::InstId base_id,
  221. SemIR::NameId name_id,
  222. SemIR::ConstantId name_scope_const_id,
  223. llvm::ArrayRef<LookupScope> lookup_scopes,
  224. bool lookup_in_type_of_base, bool required)
  225. -> SemIR::InstId {
  226. AccessInfo access_info = {
  227. .constant_id = name_scope_const_id,
  228. .highest_allowed_access =
  229. GetHighestAllowedAccess(context, loc_id, name_scope_const_id),
  230. };
  231. LookupResult result = LookupQualifiedName(
  232. context, loc_id, name_id, lookup_scopes, required, access_info);
  233. if (!result.scope_result.is_found()) {
  234. return SemIR::ErrorInst::SingletonInstId;
  235. }
  236. // TODO: This duplicates the work that HandleNameAsExpr does. Factor this out.
  237. auto type_id =
  238. SemIR::GetTypeOfInstInSpecific(context.sem_ir(), result.specific_id,
  239. result.scope_result.target_inst_id());
  240. CARBON_CHECK(type_id.has_value(), "Missing type for member {0}",
  241. context.insts().Get(result.scope_result.target_inst_id()));
  242. // If the named entity has a constant value that depends on its specific,
  243. // store the specific too.
  244. if (result.specific_id.has_value() &&
  245. context.constant_values()
  246. .Get(result.scope_result.target_inst_id())
  247. .is_symbolic()) {
  248. result.scope_result = SemIR::ScopeLookupResult::MakeFound(
  249. GetOrAddInst<SemIR::SpecificConstant>(
  250. context, loc_id,
  251. {.type_id = type_id,
  252. .inst_id = result.scope_result.target_inst_id(),
  253. .specific_id = result.specific_id}),
  254. SemIR::AccessKind::Public);
  255. }
  256. // TODO: Use a different kind of instruction that also references the
  257. // `base_id` so that `SemIR` consumers can find it.
  258. auto member_id = GetOrAddInst<SemIR::NameRef>(
  259. context, loc_id,
  260. {.type_id = type_id,
  261. .name_id = name_id,
  262. .value_id = result.scope_result.target_inst_id()});
  263. // If member name lookup finds an associated entity name, and the scope is not
  264. // a facet type, perform impl lookup.
  265. //
  266. // TODO: We need to do this as part of searching extended scopes, because a
  267. // lookup that finds an associated entity and also finds the corresponding
  268. // impl member is not supposed to be treated as ambiguous.
  269. if (auto assoc_type =
  270. context.types().TryGetAs<SemIR::AssociatedEntityType>(type_id)) {
  271. if (lookup_in_type_of_base) {
  272. SemIR::TypeId base_type_id = context.insts().Get(base_id).type_id();
  273. if (auto facet_access_type =
  274. context.types().TryGetAs<SemIR::FacetAccessType>(base_type_id)) {
  275. // Move from the type of a symbolic facet value up in typish-ness to its
  276. // FacetType to find the type to work with.
  277. base_id = facet_access_type->facet_value_inst_id;
  278. base_type_id = context.insts().Get(base_id).type_id();
  279. }
  280. if (auto facet_type =
  281. context.types().TryGetAs<SemIR::FacetType>(base_type_id)) {
  282. // Handles `T.F` when `T` is a non-type facet.
  283. auto base_as_type = ExprAsType(context, loc_id, base_id);
  284. auto assoc_interface =
  285. GetInterfaceFromFacetType(context, assoc_type->interface_type_id);
  286. // An associated entity should always be associated with a single
  287. // interface.
  288. CARBON_CHECK(assoc_interface);
  289. // First look for `*assoc_interface` in the type of the base. If it is
  290. // found, get the witness that the interface is implemented from
  291. // `base_id`.
  292. const auto& facet_type_info =
  293. context.facet_types().Get(facet_type->facet_type_id);
  294. // Witness that `T` implements the `*assoc_interface`.
  295. SemIR::InstId witness_inst_id = SemIR::InstId::None;
  296. // TODO: This assumes `impls_constraints` are in the same order as
  297. // `CompleteFacetType::required_interfaces`, and come first in the list.
  298. // Once we add support for named constraints there may be more
  299. // interfaces in the `CompleteFacetType`, and we will require those
  300. // additional interfaces in the `CompleteFacetType` to come after the
  301. // ones we see in `impls_constraints` in order to not invalidate the
  302. // index computed here.
  303. for (auto [index, base_interface] :
  304. llvm::enumerate(facet_type_info.impls_constraints)) {
  305. // Get the witness that `T` implements `base_type_id`.
  306. if (base_interface == *assoc_interface) {
  307. witness_inst_id = GetOrAddInst(
  308. context, loc_id,
  309. SemIR::FacetAccessWitness{
  310. .type_id = GetSingletonType(
  311. context, SemIR::WitnessType::SingletonInstId),
  312. .facet_value_inst_id = base_id,
  313. .index = SemIR::ElementIndex(index)});
  314. break;
  315. }
  316. }
  317. // TODO: If that fails, would need to do impl lookup to see if the facet
  318. // value implements the interface of `*assoc_type`.
  319. if (!witness_inst_id.has_value()) {
  320. context.TODO(member_id,
  321. "associated entity not found in facet type, need to do "
  322. "impl lookup");
  323. return SemIR::ErrorInst::SingletonInstId;
  324. }
  325. member_id = AccessMemberOfImplWitness(
  326. context, loc_id, base_as_type.type_id, witness_inst_id,
  327. assoc_interface->specific_id, member_id);
  328. } else {
  329. // Handles `x.F` if `x` is of type `class C` that extends an interface
  330. // containing `F`.
  331. SemIR::ConstantId constant_id =
  332. context.types().GetConstantId(base_type_id);
  333. member_id = PerformImplLookup(context, loc_id, constant_id, *assoc_type,
  334. member_id);
  335. }
  336. } else if (ScopeNeedsImplLookup(context, name_scope_const_id)) {
  337. // Handles `T.F` where `T` is a type extending an interface containing
  338. // `F`.
  339. member_id = PerformImplLookup(context, loc_id, name_scope_const_id,
  340. *assoc_type, member_id);
  341. }
  342. }
  343. return member_id;
  344. }
  345. // Performs the instance binding step in member access. If the found member is a
  346. // field, forms a class member access. If the found member is an instance
  347. // method, forms a bound method. Otherwise, the member is returned unchanged.
  348. static auto PerformInstanceBinding(Context& context, SemIR::LocId loc_id,
  349. SemIR::InstId base_id,
  350. SemIR::InstId member_id) -> SemIR::InstId {
  351. // If the member is a function, check whether it's an instance method.
  352. if (auto callee = SemIR::GetCalleeFunction(context.sem_ir(), member_id);
  353. callee.function_id.has_value()) {
  354. if (!IsInstanceMethod(context.sem_ir(), callee.function_id) ||
  355. callee.self_id.has_value()) {
  356. // Found a static member function or an already-bound method.
  357. return member_id;
  358. }
  359. return GetOrAddInst<SemIR::BoundMethod>(
  360. context, loc_id,
  361. {.type_id =
  362. GetSingletonType(context, SemIR::BoundMethodType::SingletonInstId),
  363. .object_id = base_id,
  364. .function_decl_id = member_id});
  365. }
  366. // Otherwise, if it's a field, form a class element access.
  367. if (auto unbound_element_type =
  368. context.types().TryGetAs<SemIR::UnboundElementType>(
  369. context.insts().Get(member_id).type_id())) {
  370. // Convert the base to the type of the element if necessary.
  371. base_id = ConvertToValueOrRefOfType(context, loc_id, base_id,
  372. unbound_element_type->class_type_id);
  373. // Find the specified element, which could be either a field or a base
  374. // class, and build an element access expression.
  375. auto element_id = context.constant_values().GetConstantInstId(member_id);
  376. CARBON_CHECK(element_id.has_value(),
  377. "Non-constant value {0} of unbound element type",
  378. context.insts().Get(member_id));
  379. auto index = GetClassElementIndex(context, element_id);
  380. auto access_id = GetOrAddInst<SemIR::ClassElementAccess>(
  381. context, loc_id,
  382. {.type_id = unbound_element_type->element_type_id,
  383. .base_id = base_id,
  384. .index = index});
  385. if (SemIR::GetExprCategory(context.sem_ir(), base_id) ==
  386. SemIR::ExprCategory::Value &&
  387. SemIR::GetExprCategory(context.sem_ir(), access_id) !=
  388. SemIR::ExprCategory::Value) {
  389. // Class element access on a value expression produces an ephemeral
  390. // reference if the class's value representation is a pointer to the
  391. // object representation. Add a value binding in that case so that the
  392. // expression category of the result matches the expression category
  393. // of the base.
  394. access_id = ConvertToValueExpr(context, access_id);
  395. }
  396. return access_id;
  397. }
  398. // Not an instance member: no instance binding.
  399. return member_id;
  400. }
  401. // Validates that the index (required to be an IntValue) is valid within the
  402. // tuple size. Returns the index on success, or nullptr on failure.
  403. static auto ValidateTupleIndex(Context& context, SemIR::LocId loc_id,
  404. SemIR::InstId operand_inst_id,
  405. SemIR::IntValue index_inst, int size)
  406. -> std::optional<llvm::APInt> {
  407. llvm::APInt index_val = context.ints().Get(index_inst.int_id);
  408. if (index_val.uge(size)) {
  409. CARBON_DIAGNOSTIC(TupleIndexOutOfBounds, Error,
  410. "tuple element index `{0}` is past the end of type {1}",
  411. TypedInt, TypeOfInstId);
  412. context.emitter().Emit(loc_id, TupleIndexOutOfBounds,
  413. {.type = index_inst.type_id, .value = index_val},
  414. operand_inst_id);
  415. return std::nullopt;
  416. }
  417. return index_val;
  418. }
  419. auto PerformMemberAccess(Context& context, SemIR::LocId loc_id,
  420. SemIR::InstId base_id, SemIR::NameId name_id,
  421. bool required) -> SemIR::InstId {
  422. // TODO: Member access for dependent member names is supposed to perform a
  423. // lookup in both the template definition context and the template
  424. // instantiation context, and reject if both succeed but find different
  425. // things.
  426. if (required) {
  427. return HandleAction<SemIR::AccessMemberAction>(
  428. context, loc_id,
  429. {.type_id = SemIR::InstType::SingletonTypeId,
  430. .base_id = base_id,
  431. .name_id = name_id});
  432. } else {
  433. return HandleAction<SemIR::AccessOptionalMemberAction>(
  434. context, loc_id,
  435. {.type_id = SemIR::InstType::SingletonTypeId,
  436. .base_id = base_id,
  437. .name_id = name_id});
  438. }
  439. }
  440. // Common logic for `AccessMemberAction` and `AccessOptionalMemberAction`.
  441. static auto PerformActionHelper(Context& context, SemIR::LocId loc_id,
  442. SemIR::InstId base_id, SemIR::NameId name_id,
  443. bool required) -> SemIR::InstId {
  444. // If the base is a name scope, such as a class or namespace, perform lookup
  445. // into that scope.
  446. if (auto base_const_id = context.constant_values().Get(base_id);
  447. base_const_id.is_constant()) {
  448. llvm::SmallVector<LookupScope> lookup_scopes;
  449. if (AppendLookupScopesForConstant(context, loc_id, base_const_id,
  450. &lookup_scopes)) {
  451. return LookupMemberNameInScope(
  452. context, loc_id, base_id, name_id, base_const_id, lookup_scopes,
  453. /*lookup_in_type_of_base=*/false, /*required=*/required);
  454. }
  455. }
  456. // If the base isn't a scope, it must have a complete type.
  457. auto base_type_id = context.insts().Get(base_id).type_id();
  458. auto base_loc_id = context.insts().GetLocId(base_id);
  459. if (!RequireCompleteType(context, base_type_id, base_loc_id, [&] {
  460. CARBON_DIAGNOSTIC(IncompleteTypeInMemberAccess, Error,
  461. "member access into object of incomplete type {0}",
  462. TypeOfInstId);
  463. return context.emitter().Build(base_id, IncompleteTypeInMemberAccess,
  464. base_id);
  465. })) {
  466. return SemIR::ErrorInst::SingletonInstId;
  467. }
  468. // Materialize a temporary for the base expression if necessary.
  469. base_id = ConvertToValueOrRefExpr(context, base_id);
  470. base_type_id = context.insts().Get(base_id).type_id();
  471. auto base_type_const_id = context.types().GetConstantId(base_type_id);
  472. // Find the scope corresponding to the base type.
  473. llvm::SmallVector<LookupScope> lookup_scopes;
  474. if (!AppendLookupScopesForConstant(context, loc_id, base_type_const_id,
  475. &lookup_scopes)) {
  476. // The base type is not a name scope. Try some fallback options.
  477. if (auto struct_type = context.insts().TryGetAs<SemIR::StructType>(
  478. context.constant_values().GetInstId(base_type_const_id))) {
  479. // TODO: Do we need to optimize this with a lookup table for O(1)?
  480. for (auto [i, field] : llvm::enumerate(
  481. context.struct_type_fields().Get(struct_type->fields_id))) {
  482. if (name_id == field.name_id) {
  483. // TODO: Model this as producing a lookup result, and do instance
  484. // binding separately. Perhaps a struct type should be a name scope.
  485. return GetOrAddInst<SemIR::StructAccess>(
  486. context, loc_id,
  487. {.type_id = field.type_id,
  488. .struct_id = base_id,
  489. .index = SemIR::ElementIndex(i)});
  490. }
  491. }
  492. if (required) {
  493. CARBON_DIAGNOSTIC(QualifiedExprNameNotFound, Error,
  494. "type {0} does not have a member `{1}`", TypeOfInstId,
  495. SemIR::NameId);
  496. context.emitter().Emit(loc_id, QualifiedExprNameNotFound, base_id,
  497. name_id);
  498. return SemIR::ErrorInst::SingletonInstId;
  499. } else {
  500. return SemIR::InstId::None;
  501. }
  502. }
  503. if (base_type_id != SemIR::ErrorInst::SingletonTypeId) {
  504. CARBON_DIAGNOSTIC(QualifiedExprUnsupported, Error,
  505. "type {0} does not support qualified expressions",
  506. TypeOfInstId);
  507. context.emitter().Emit(loc_id, QualifiedExprUnsupported, base_id);
  508. }
  509. return SemIR::ErrorInst::SingletonInstId;
  510. }
  511. // Perform lookup into the base type.
  512. auto member_id = LookupMemberNameInScope(
  513. context, loc_id, base_id, name_id, base_type_const_id, lookup_scopes,
  514. /*lookup_in_type_of_base=*/true, /*required=*/required);
  515. // For name lookup into a facet, never perform instance binding.
  516. // TODO: According to the design, this should be a "lookup in base" lookup,
  517. // not a "lookup in type of base" lookup, and the facet itself should have
  518. // member names that directly name members of the `impl`.
  519. if (context.types().IsFacetType(base_type_id)) {
  520. return member_id;
  521. }
  522. // Perform instance binding if we found an instance member.
  523. member_id = PerformInstanceBinding(context, loc_id, base_id, member_id);
  524. return member_id;
  525. }
  526. auto PerformAction(Context& context, SemIR::LocId loc_id,
  527. SemIR::AccessMemberAction action) -> SemIR::InstId {
  528. return PerformActionHelper(context, loc_id, action.base_id, action.name_id,
  529. /*required=*/true);
  530. }
  531. auto PerformAction(Context& context, SemIR::LocId loc_id,
  532. SemIR::AccessOptionalMemberAction action) -> SemIR::InstId {
  533. return PerformActionHelper(context, loc_id, action.base_id, action.name_id,
  534. /*required=*/false);
  535. }
  536. // Logic shared by GetAssociatedValue() and PerformCompoundMemberAccess().
  537. static auto GetAssociatedValueImpl(Context& context, SemIR::LocId loc_id,
  538. SemIR::InstId base_id,
  539. const SemIR::AssociatedEntity& assoc_entity,
  540. SemIR::TypeId interface_type_id,
  541. SemIR::SpecificId interface_specific_id)
  542. -> SemIR::InstId {
  543. // Convert to the interface type of the associated member, to get a facet
  544. // value.
  545. auto facet_inst_id =
  546. ConvertToValueOfType(context, loc_id, base_id, interface_type_id);
  547. if (facet_inst_id == SemIR::ErrorInst::SingletonInstId) {
  548. return SemIR::ErrorInst::SingletonInstId;
  549. }
  550. // That facet value has both the self type we need below and the witness
  551. // we are going to use to look up the value of the associated member.
  552. auto self_type_const_id = TryEvalInst(
  553. context, SemIR::InstId::None,
  554. SemIR::FacetAccessType{.type_id = SemIR::TypeType::SingletonTypeId,
  555. .facet_value_inst_id = facet_inst_id});
  556. auto self_type_id =
  557. context.types().GetTypeIdForTypeConstantId(self_type_const_id);
  558. auto witness_id =
  559. GetOrAddInst(context, loc_id,
  560. SemIR::FacetAccessWitness{
  561. .type_id = GetSingletonType(
  562. context, SemIR::WitnessType::SingletonInstId),
  563. .facet_value_inst_id = facet_inst_id,
  564. // There's only one interface in this facet type.
  565. .index = SemIR::ElementIndex(0)});
  566. // Before we can access the element of the witness, we need to figure out
  567. // the type of that element. It depends on the self type and the specific
  568. // interface.
  569. auto assoc_type_id = GetTypeForSpecificAssociatedEntity(
  570. context, loc_id, interface_specific_id, assoc_entity.decl_id,
  571. self_type_id, witness_id);
  572. // Now that we have the witness, an index into it, and the type of the
  573. // result, return the element of the witness.
  574. return GetOrAddInst<SemIR::ImplWitnessAccess>(context, loc_id,
  575. {.type_id = assoc_type_id,
  576. .witness_id = witness_id,
  577. .index = assoc_entity.index});
  578. }
  579. auto GetAssociatedValue(Context& context, SemIR::LocId loc_id,
  580. SemIR::InstId base_id,
  581. SemIR::InstId assoc_entity_inst_id,
  582. SemIR::TypeId interface_type_id) -> SemIR::InstId {
  583. // TODO: This function shares a code with PerformCompoundMemberAccess(),
  584. // it would be nice to reduce the duplication.
  585. auto interface_type = GetInterfaceFromFacetType(context, interface_type_id);
  586. // An associated entity is always associated with a single interface.
  587. CARBON_CHECK(interface_type);
  588. auto value_inst_id =
  589. context.constant_values().GetConstantInstId(assoc_entity_inst_id);
  590. CARBON_CHECK(value_inst_id.has_value());
  591. auto assoc_entity =
  592. context.insts().GetAs<SemIR::AssociatedEntity>(value_inst_id);
  593. auto decl_id = assoc_entity.decl_id;
  594. LoadImportRef(context, decl_id);
  595. return GetAssociatedValueImpl(context, loc_id, base_id, assoc_entity,
  596. interface_type_id, interface_type->specific_id);
  597. }
  598. auto PerformCompoundMemberAccess(Context& context, SemIR::LocId loc_id,
  599. SemIR::InstId base_id,
  600. SemIR::InstId member_expr_id,
  601. MakeDiagnosticBuilderFn missing_impl_diagnoser)
  602. -> SemIR::InstId {
  603. auto base_type_id = context.insts().Get(base_id).type_id();
  604. auto base_type_const_id = context.types().GetConstantId(base_type_id);
  605. auto member_id = member_expr_id;
  606. auto member = context.insts().Get(member_id);
  607. // If the member expression names an associated entity, impl lookup is always
  608. // performed using the type of the base expression.
  609. if (auto assoc_type = context.types().TryGetAs<SemIR::AssociatedEntityType>(
  610. member.type_id())) {
  611. // Step 1: figure out the type of the associated entity from the interface.
  612. SemIR::TypeId interface_type_id = assoc_type->interface_type_id;
  613. auto interface_type = GetInterfaceFromFacetType(context, interface_type_id);
  614. // An associated entity is always associated with a single interface.
  615. CARBON_CHECK(interface_type);
  616. auto value_inst_id = context.constant_values().GetConstantInstId(member_id);
  617. // TODO: According to
  618. // https://docs.carbon-lang.dev/docs/design/expressions/member_access.html#member-resolution
  619. // > For a compound member access, the second operand is evaluated as a
  620. // > compile-time constant to determine the member being accessed. The
  621. // > evaluation is required to succeed [...]
  622. if (!value_inst_id.has_value()) {
  623. context.TODO(loc_id, "Non-constant associated entity value");
  624. return SemIR::ErrorInst::SingletonInstId;
  625. }
  626. auto assoc_entity =
  627. context.insts().GetAs<SemIR::AssociatedEntity>(value_inst_id);
  628. auto decl_id = assoc_entity.decl_id;
  629. LoadImportRef(context, decl_id);
  630. auto decl_value_id = context.constant_values().GetConstantInstId(decl_id);
  631. auto decl_type_id = context.insts().Get(decl_value_id).type_id();
  632. if (IsInstanceType(context, decl_type_id)) {
  633. // Step 2a: For instance methods, lookup the impl of the interface for
  634. // this type and get the method.
  635. member_id =
  636. PerformImplLookup(context, loc_id, base_type_const_id, *assoc_type,
  637. member_id, missing_impl_diagnoser);
  638. // Next we will perform instance binding.
  639. } else {
  640. // Step 2b: For non-instance methods and associated constants, we access
  641. // the value of the associated constant, and don't do any instance
  642. // binding.
  643. return GetAssociatedValueImpl(context, loc_id, base_id, assoc_entity,
  644. interface_type_id,
  645. interface_type->specific_id);
  646. }
  647. } else if (context.insts().Is<SemIR::TupleType>(
  648. context.constant_values().GetInstId(base_type_const_id))) {
  649. return PerformTupleAccess(context, loc_id, base_id, member_expr_id);
  650. }
  651. // Perform instance binding if we found an instance member.
  652. member_id = PerformInstanceBinding(context, loc_id, base_id, member_id);
  653. // If we didn't perform impl lookup or instance binding, that's an error
  654. // because the base expression is not used for anything.
  655. if (member_id == member_expr_id &&
  656. member.type_id() != SemIR::ErrorInst::SingletonTypeId) {
  657. CARBON_DIAGNOSTIC(CompoundMemberAccessDoesNotUseBase, Error,
  658. "member name of type {0} in compound member access is "
  659. "not an instance member or an interface member",
  660. TypeOfInstId);
  661. context.emitter().Emit(loc_id, CompoundMemberAccessDoesNotUseBase,
  662. member_id);
  663. }
  664. return member_id;
  665. }
  666. auto PerformTupleAccess(Context& context, SemIR::LocId loc_id,
  667. SemIR::InstId tuple_inst_id,
  668. SemIR::InstId index_inst_id) -> SemIR::InstId {
  669. tuple_inst_id = ConvertToValueOrRefExpr(context, tuple_inst_id);
  670. auto tuple_type_id = context.insts().Get(tuple_inst_id).type_id();
  671. auto tuple_type = context.types().TryGetAs<SemIR::TupleType>(tuple_type_id);
  672. if (!tuple_type) {
  673. CARBON_DIAGNOSTIC(TupleIndexOnANonTupleType, Error,
  674. "type {0} does not support tuple indexing; only "
  675. "tuples can be indexed that way",
  676. TypeOfInstId);
  677. context.emitter().Emit(loc_id, TupleIndexOnANonTupleType, tuple_inst_id);
  678. return SemIR::ErrorInst::SingletonInstId;
  679. }
  680. auto diag_non_constant_index = [&] {
  681. // TODO: Decide what to do if the index is a symbolic constant.
  682. CARBON_DIAGNOSTIC(TupleIndexNotConstant, Error,
  683. "tuple index must be a constant");
  684. context.emitter().Emit(loc_id, TupleIndexNotConstant);
  685. return SemIR::ErrorInst::SingletonInstId;
  686. };
  687. // Diagnose a non-constant index prior to conversion to IntLiteral, because
  688. // the conversion will fail if the index is not constant.
  689. if (!context.constant_values().Get(index_inst_id).is_concrete()) {
  690. return diag_non_constant_index();
  691. }
  692. SemIR::TypeId element_type_id = SemIR::ErrorInst::SingletonTypeId;
  693. auto index_node_id = context.insts().GetLocId(index_inst_id);
  694. index_inst_id = ConvertToValueOfType(
  695. context, index_node_id, index_inst_id,
  696. GetSingletonType(context, SemIR::IntLiteralType::SingletonInstId));
  697. auto index_const_id = context.constant_values().Get(index_inst_id);
  698. if (index_const_id == SemIR::ErrorInst::SingletonConstantId) {
  699. return SemIR::ErrorInst::SingletonInstId;
  700. } else if (!index_const_id.is_concrete()) {
  701. return diag_non_constant_index();
  702. }
  703. auto index_literal = context.insts().GetAs<SemIR::IntValue>(
  704. context.constant_values().GetInstId(index_const_id));
  705. auto type_block = context.type_blocks().Get(tuple_type->elements_id);
  706. std::optional<llvm::APInt> index_val = ValidateTupleIndex(
  707. context, loc_id, tuple_inst_id, index_literal, type_block.size());
  708. if (!index_val) {
  709. return SemIR::ErrorInst::SingletonInstId;
  710. }
  711. // TODO: Handle the case when `index_val->getZExtValue()` has too many bits.
  712. element_type_id = type_block[index_val->getZExtValue()];
  713. auto tuple_index = SemIR::ElementIndex(index_val->getZExtValue());
  714. return GetOrAddInst<SemIR::TupleAccess>(context, loc_id,
  715. {.type_id = element_type_id,
  716. .tuple_id = tuple_inst_id,
  717. .index = tuple_index});
  718. }
  719. } // namespace Carbon::Check