member_access.cpp 34 KB

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