member_access.cpp 38 KB

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