member_access.cpp 34 KB

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