member_access.cpp 32 KB

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