member_access.cpp 36 KB

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