member_access.cpp 34 KB

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