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 =
  111. context.constant_values().TryGetInstAs<SemIR::ClassType>(
  112. name_scope_const_id)) {
  113. auto class_info = context.classes().Get(class_type->class_id);
  114. if (self_class_info.self_type_id == class_info.self_type_id) {
  115. return SemIR::AccessKind::Private;
  116. }
  117. // If the `type_id` of `Self` does not match with the one we're currently
  118. // accessing, try checking if this class is of the parent type of `Self`.
  119. if (auto base_type_id = self_class_info.GetBaseType(
  120. context.sem_ir(), self_class_type->specific_id);
  121. base_type_id.has_value()) {
  122. if (context.types().GetConstantId(base_type_id) == name_scope_const_id) {
  123. return SemIR::AccessKind::Protected;
  124. }
  125. // TODO: Also check whether this base class has a base class of its own.
  126. } else if (auto adapt_type_id = self_class_info.GetAdaptedType(
  127. context.sem_ir(), self_class_type->specific_id);
  128. adapt_type_id.has_value()) {
  129. if (context.types().GetConstantId(adapt_type_id) == name_scope_const_id) {
  130. // TODO: Should we be allowed to access protected fields of a type we
  131. // are adapting? The design doesn't allow this.
  132. return SemIR::AccessKind::Protected;
  133. }
  134. }
  135. }
  136. return SemIR::AccessKind::Public;
  137. }
  138. // Returns whether `scope` is a scope for which impl lookup should be performed
  139. // if we find an associated entity.
  140. static auto ScopeNeedsImplLookup(Context& context,
  141. SemIR::ConstantId name_scope_const_id)
  142. -> bool {
  143. SemIR::InstId inst_id =
  144. context.constant_values().GetInstId(name_scope_const_id);
  145. CARBON_CHECK(inst_id.has_value());
  146. SemIR::Inst inst = context.insts().Get(inst_id);
  147. if (inst.Is<SemIR::FacetType>()) {
  148. // Don't perform impl lookup if an associated entity is named as a member of
  149. // a facet type.
  150. return false;
  151. }
  152. if (inst.Is<SemIR::Namespace>()) {
  153. // Don't perform impl lookup if an associated entity is named as a namespace
  154. // member.
  155. // TODO: This case is not yet listed in the design.
  156. return false;
  157. }
  158. // Any other kind of scope is assumed to be a type that implements the
  159. // interface containing the associated entity, and impl lookup is performed.
  160. return true;
  161. }
  162. static auto AccessMemberOfImplWitness(
  163. Context& context, SemIR::LocId loc_id, SemIR::InstId witness_id,
  164. SemIR::SpecificId interface_with_self_specific_id, SemIR::InstId member_id)
  165. -> SemIR::InstId {
  166. auto member_value_id = context.constant_values().GetConstantInstId(member_id);
  167. if (!member_value_id.has_value()) {
  168. if (member_value_id != SemIR::ErrorInst::InstId) {
  169. context.TODO(member_id, "non-constant associated entity");
  170. }
  171. return SemIR::ErrorInst::InstId;
  172. }
  173. auto assoc_entity =
  174. context.insts().TryGetAs<SemIR::AssociatedEntity>(member_value_id);
  175. if (!assoc_entity) {
  176. context.TODO(member_id, "unexpected value for associated entity");
  177. return SemIR::ErrorInst::InstId;
  178. }
  179. // Substitute the interface specific and `Self` type into the type of the
  180. // associated entity to find the type of the member access.
  181. LoadImportRef(context, assoc_entity->decl_id);
  182. auto assoc_type_id = GetTypeForSpecificAssociatedEntity(
  183. context, interface_with_self_specific_id, assoc_entity->decl_id);
  184. return GetOrAddInst<SemIR::ImplWitnessAccess>(context, loc_id,
  185. {.type_id = assoc_type_id,
  186. .witness_id = witness_id,
  187. .index = assoc_entity->index});
  188. }
  189. // For an impl lookup query with a single interface in it, we can convert the
  190. // result to a single witness InstId.
  191. //
  192. // This CHECKs that the result (and thus the query) was a single interface. This
  193. // generally only makes sense in member access, where the lookup query's
  194. // interface is found through name lookup, and we don't have an arbitrary
  195. // `FacetType`.
  196. static auto GetWitnessFromSingleImplLookupResult(
  197. Context& context, SemIR::InstBlockIdOrError lookup_result)
  198. -> SemIR::InstId {
  199. auto witness_id = SemIR::InstId::None;
  200. if (lookup_result.has_error_value()) {
  201. witness_id = SemIR::ErrorInst::InstId;
  202. } else {
  203. auto witnesses = context.inst_blocks().Get(lookup_result.inst_block_id());
  204. CARBON_CHECK(witnesses.size() == 1);
  205. witness_id = witnesses[0];
  206. }
  207. return witness_id;
  208. }
  209. // Performs impl lookup for a member name expression. This finds the relevant
  210. // impl witness and extracts the corresponding impl member.
  211. static auto PerformImplLookup(
  212. Context& context, SemIR::LocId loc_id, SemIR::ConstantId type_const_id,
  213. SemIR::AssociatedEntityType assoc_type, SemIR::InstId member_id,
  214. bool diagnose = true,
  215. DiagnosticContextFn missing_impl_diagnostic_context = nullptr)
  216. -> SemIR::InstId {
  217. auto self_type_id = context.types().GetTypeIdForTypeConstantId(type_const_id);
  218. // TODO: Avoid forming and then immediately decomposing a `FacetType` here.
  219. auto interface_type_id =
  220. GetInterfaceType(context, assoc_type.interface_id,
  221. assoc_type.interface_without_self_specific_id);
  222. auto lookup_result = LookupImplWitness(context, loc_id, type_const_id,
  223. interface_type_id.AsConstantId());
  224. if (!lookup_result.has_value()) {
  225. if (diagnose) {
  226. if (missing_impl_diagnostic_context) {
  227. Diagnostics::ContextScope scope(&context.emitter(),
  228. missing_impl_diagnostic_context);
  229. // TODO: Pass in the expression whose type we are printing.
  230. CARBON_DIAGNOSTIC(MissingImplInMemberAccessInContext, Error,
  231. "type {1} does not implement interface {0}",
  232. SemIR::TypeId, SemIR::TypeId);
  233. context.emitter().Emit(loc_id, MissingImplInMemberAccessInContext,
  234. interface_type_id, self_type_id);
  235. } else {
  236. // TODO: Pass in the expression whose type we are printing.
  237. CARBON_DIAGNOSTIC(MissingImplInMemberAccess, Error,
  238. "cannot access member of interface {0} in type {1} "
  239. "that does not implement that interface",
  240. SemIR::TypeId, SemIR::TypeId);
  241. context.emitter().Emit(loc_id, MissingImplInMemberAccess,
  242. interface_type_id, self_type_id);
  243. }
  244. }
  245. return SemIR::ErrorInst::InstId;
  246. }
  247. auto witness_id =
  248. GetWitnessFromSingleImplLookupResult(context, lookup_result);
  249. auto self_facet = GetConstantFacetValueForTypeAndInterface(
  250. context, context.types().GetTypeInstId(self_type_id),
  251. assoc_type.GetSpecificInterface(), witness_id);
  252. const auto& interface = context.interfaces().Get(assoc_type.interface_id);
  253. auto interface_with_self_specific_id = MakeSpecificWithInnerSelf(
  254. context, loc_id, interface.generic_id, interface.generic_with_self_id,
  255. assoc_type.interface_without_self_specific_id, self_facet);
  256. return AccessMemberOfImplWitness(context, loc_id, witness_id,
  257. interface_with_self_specific_id, member_id);
  258. }
  259. // Performs a member name lookup into the specified scope, including performing
  260. // impl lookup if necessary. If the scope result is `None`, assume an error has
  261. // already been diagnosed, and return `ErrorInst`.
  262. static auto LookupMemberNameInScope(Context& context, SemIR::LocId loc_id,
  263. SemIR::InstId base_id,
  264. SemIR::NameId name_id,
  265. SemIR::ConstantId name_scope_const_id,
  266. llvm::ArrayRef<LookupScope> lookup_scopes,
  267. bool lookup_in_type_of_base, bool required)
  268. -> SemIR::InstId {
  269. AccessInfo access_info = {
  270. .constant_id = name_scope_const_id,
  271. .highest_allowed_access =
  272. GetHighestAllowedAccess(context, loc_id, name_scope_const_id),
  273. };
  274. LookupResult result = LookupQualifiedName(
  275. context, loc_id, name_id, lookup_scopes, required, access_info);
  276. if (!result.scope_result.is_found()) {
  277. return SemIR::ErrorInst::InstId;
  278. }
  279. // TODO: This duplicates the work that HandleNameAsExpr does. Factor this out.
  280. auto type_id =
  281. SemIR::GetTypeOfInstInSpecific(context.sem_ir(), result.specific_id,
  282. result.scope_result.target_inst_id());
  283. CARBON_CHECK(type_id.has_value(), "Missing type for member {0}",
  284. context.insts().Get(result.scope_result.target_inst_id()));
  285. // If the named entity has a constant value that depends on its specific,
  286. // store the specific too.
  287. if (result.specific_id.has_value() &&
  288. context.constant_values()
  289. .Get(result.scope_result.target_inst_id())
  290. .is_symbolic()) {
  291. result.scope_result = SemIR::ScopeLookupResult::MakeFound(
  292. GetOrAddInst<SemIR::SpecificConstant>(
  293. context, loc_id,
  294. {.type_id = type_id,
  295. .inst_id = result.scope_result.target_inst_id(),
  296. .specific_id = result.specific_id}),
  297. SemIR::AccessKind::Public);
  298. }
  299. // TODO: Use a different kind of instruction that also references the
  300. // `base_id` so that `SemIR` consumers can find it.
  301. auto member_id = GetOrAddInst<SemIR::NameRef>(
  302. context, loc_id,
  303. {.type_id = type_id,
  304. .name_id = name_id,
  305. .value_id = result.scope_result.target_inst_id()});
  306. // If member name lookup finds an associated entity name, and the scope is not
  307. // a facet type, perform impl lookup.
  308. //
  309. // TODO: We need to do this as part of searching extended scopes, because a
  310. // lookup that finds an associated entity and also finds the corresponding
  311. // impl member is not supposed to be treated as ambiguous.
  312. if (auto assoc_type =
  313. context.types().TryGetAs<SemIR::AssociatedEntityType>(type_id)) {
  314. if (lookup_in_type_of_base) {
  315. auto base_type_id = context.insts().Get(base_id).type_id();
  316. member_id = PerformImplLookup(context, loc_id,
  317. context.types().GetConstantId(base_type_id),
  318. *assoc_type, member_id);
  319. } else if (ScopeNeedsImplLookup(context, name_scope_const_id)) {
  320. // Handles `T.F` where `T` is a type extending an interface containing
  321. // `F`.
  322. member_id = PerformImplLookup(context, loc_id, name_scope_const_id,
  323. *assoc_type, member_id);
  324. }
  325. }
  326. if (!context.rewrites_stack().empty()) {
  327. if (auto access =
  328. context.insts().TryGetAs<SemIR::ImplWitnessAccess>(member_id)) {
  329. if (auto result = context.rewrites_stack().back().Lookup(
  330. context.constant_values().Get(member_id))) {
  331. return GetOrAddInst<SemIR::ImplWitnessAccessSubstituted>(
  332. context, loc_id,
  333. {.type_id = access->type_id,
  334. .impl_witness_access_id = member_id,
  335. .value_id = result.value()});
  336. }
  337. }
  338. }
  339. return member_id;
  340. }
  341. // Performs the instance binding step in member access. If the found member is a
  342. // field, forms a class member access. If the found member is an instance
  343. // method, forms a bound method. Otherwise, the member is returned unchanged.
  344. static auto PerformInstanceBinding(Context& context, SemIR::LocId loc_id,
  345. SemIR::InstId base_id,
  346. SemIR::InstId member_id) -> SemIR::InstId {
  347. // If the member is a function, check whether it's an instance method.
  348. if (auto self_id = GetSelfIfInstanceMethod(
  349. context.sem_ir(), SemIR::GetCallee(context.sem_ir(), member_id))) {
  350. if (self_id->has_value()) {
  351. // Found an already-bound method.
  352. return member_id;
  353. }
  354. return GetOrAddInst<SemIR::BoundMethod>(
  355. context, loc_id,
  356. {.type_id =
  357. GetSingletonType(context, SemIR::BoundMethodType::TypeInstId),
  358. .object_id = base_id,
  359. .function_decl_id = member_id});
  360. }
  361. // Otherwise, if it's a field, form a class element access.
  362. if (auto unbound_element_type =
  363. context.types().TryGetAs<SemIR::UnboundElementType>(
  364. context.insts().Get(member_id).type_id())) {
  365. // Convert the base to the type of the element if necessary.
  366. base_id = ConvertToValueOrRefOfType(
  367. context, loc_id, base_id,
  368. context.types().GetTypeIdForTypeInstId(
  369. unbound_element_type->class_type_inst_id));
  370. // Find the specified element, which could be either a field or a base
  371. // class, and build an element access expression.
  372. auto element_id = context.constant_values().GetConstantInstId(member_id);
  373. CARBON_CHECK(element_id.has_value(),
  374. "Non-constant value {0} of unbound element type",
  375. context.insts().Get(member_id));
  376. auto index = GetClassElementIndex(context, element_id);
  377. auto access_id = GetOrAddInst<SemIR::ClassElementAccess>(
  378. context, loc_id,
  379. {.type_id = context.types().GetTypeIdForTypeInstId(
  380. unbound_element_type->element_type_inst_id),
  381. .base_id = base_id,
  382. .index = index});
  383. if (SemIR::GetExprCategory(context.sem_ir(), base_id) ==
  384. SemIR::ExprCategory::Value &&
  385. SemIR::GetExprCategory(context.sem_ir(), access_id) !=
  386. SemIR::ExprCategory::Value) {
  387. // Class element access on a value expression produces an ephemeral
  388. // reference if the class's value representation is a pointer to the
  389. // object representation. Add a value acquisition in that case so that the
  390. // expression category of the result matches the expression category
  391. // of the base.
  392. access_id = ConvertToValueExpr(context, access_id);
  393. }
  394. return access_id;
  395. }
  396. // Not an instance member: no instance binding.
  397. return member_id;
  398. }
  399. // Validates that the index (required to be an IntValue) is valid within the
  400. // tuple size. Returns the index on success, or nullptr on failure.
  401. static auto ValidateTupleIndex(Context& context, SemIR::LocId loc_id,
  402. SemIR::InstId operand_inst_id,
  403. SemIR::IntValue index_inst, int size)
  404. -> std::optional<llvm::APInt> {
  405. llvm::APInt index_val = context.ints().Get(index_inst.int_id);
  406. if (index_val.uge(size)) {
  407. CARBON_DIAGNOSTIC(TupleIndexOutOfBounds, Error,
  408. "tuple element index `{0}` is past the end of type {1}",
  409. TypedInt, TypeOfInstId);
  410. context.emitter().Emit(loc_id, TupleIndexOutOfBounds,
  411. {.type = index_inst.type_id, .value = index_val},
  412. operand_inst_id);
  413. return std::nullopt;
  414. }
  415. return index_val;
  416. }
  417. auto PerformMemberAccess(Context& context, SemIR::LocId loc_id,
  418. SemIR::InstId base_id, SemIR::NameId name_id,
  419. bool required) -> SemIR::InstId {
  420. // TODO: Member access for dependent member names is supposed to perform a
  421. // lookup in both the template definition context and the template
  422. // instantiation context, and reject if both succeed but find different
  423. // things.
  424. if (required) {
  425. return HandleAction<SemIR::AccessMemberAction>(
  426. context, loc_id,
  427. {.type_id = GetSingletonType(context, SemIR::InstType::TypeInstId),
  428. .base_id = base_id,
  429. .name_id = name_id});
  430. } else {
  431. return HandleAction<SemIR::AccessOptionalMemberAction>(
  432. context, loc_id,
  433. {.type_id = GetSingletonType(context, SemIR::InstType::TypeInstId),
  434. .base_id = base_id,
  435. .name_id = name_id});
  436. }
  437. }
  438. // Common logic for `AccessMemberAction` and `AccessOptionalMemberAction`.
  439. static auto PerformActionHelper(Context& context, SemIR::LocId loc_id,
  440. SemIR::InstId base_id, SemIR::NameId name_id,
  441. bool required) -> SemIR::InstId {
  442. // Unwrap the facet value in `base_id` if possible.
  443. if (auto facet_value = TryGetCanonicalFacetValue(context, base_id);
  444. facet_value.has_value()) {
  445. base_id = facet_value;
  446. }
  447. // If the base is a name scope, such as a class or namespace, perform lookup
  448. // into that scope.
  449. if (auto base_const_id = context.constant_values().Get(base_id);
  450. base_const_id.is_constant()) {
  451. llvm::SmallVector<LookupScope> lookup_scopes;
  452. if (AppendLookupScopesForConstant(context, loc_id, base_const_id,
  453. base_const_id, &lookup_scopes)) {
  454. return LookupMemberNameInScope(
  455. context, loc_id, base_id, name_id, base_const_id, lookup_scopes,
  456. /*lookup_in_type_of_base=*/false, required);
  457. }
  458. // If the base is a facet (a symbolic name scope), perform lookup into its
  459. // facet type.
  460. //
  461. // TODO: According to the design, this should just lookup directly in the
  462. // `base_id` (as part the class case above), as the `base_id` facet should
  463. // have member names that directly name members of the `impl`.
  464. auto base_type_id = context.insts().Get(base_id).type_id();
  465. if (context.types().Is<SemIR::FacetType>(base_type_id)) {
  466. // Name lookup into a facet requires the facet type to be complete, so
  467. // that any names available through the facet type are known for the
  468. // facet.
  469. //
  470. // TODO: This should be part of AppendLookupScopesForConstant when we do
  471. // lookup on the facet directly instead of the facet type. For now it's
  472. // here to provide a better diagnostic than what we get when looking for
  473. // scopes directly on the facet type.
  474. if (!RequireCompleteType(
  475. context, base_type_id, SemIR::LocId(base_id), [&](auto& builder) {
  476. CARBON_DIAGNOSTIC(
  477. IncompleteTypeInMemberAccessOfFacet, Context,
  478. "member access into facet of incomplete type {0}",
  479. SemIR::TypeId);
  480. builder.Context(base_id, IncompleteTypeInMemberAccessOfFacet,
  481. base_type_id);
  482. })) {
  483. // If the scope is invalid in AppendLookupScopesForConstant we still
  484. // return true and proceed with lookup, just ignoring that scope.
  485. // Match behaviour here for when this moves into
  486. // AppendLookupScopesForConstant.
  487. base_type_id = SemIR::ErrorInst::TypeId;
  488. }
  489. auto base_type_const_id = context.types().GetConstantId(base_type_id);
  490. llvm::SmallVector<LookupScope> lookup_scopes;
  491. if (AppendLookupScopesForConstant(context, loc_id, base_type_const_id,
  492. base_const_id, &lookup_scopes)) {
  493. // The name scope constant needs to be a type, but is currently a
  494. // FacetType, so perform `as type` to get a FacetAccessType.
  495. auto base_as_type = ExprAsType(context, loc_id, base_id);
  496. base_type_const_id =
  497. context.types().GetConstantId(base_as_type.type_id);
  498. return LookupMemberNameInScope(context, loc_id, base_id, name_id,
  499. base_type_const_id, lookup_scopes,
  500. /*lookup_in_type_of_base=*/false,
  501. required);
  502. }
  503. }
  504. }
  505. // Otherwise, handle `x.F` by performing lookup into the type of `x` (where
  506. // `x` is `base_id`).
  507. auto base_type_id = context.insts().Get(base_id).type_id();
  508. // Require a complete type explicitly. Materializing a temporary will too, but
  509. // we can produce a better diagnostic here with context about what operation
  510. // is being done (member access) that requires the complete type.
  511. //
  512. // TODO: ConvertToValueOrRefExpr could take context about the operation being
  513. // done to give a better error than "invalid use of" an incomplete type?
  514. if (!RequireCompleteType(
  515. context, base_type_id, SemIR::LocId(base_id), [&](auto& builder) {
  516. CARBON_DIAGNOSTIC(
  517. IncompleteTypeInMemberAccess, Context,
  518. "member access into object of incomplete type {0}",
  519. TypeOfInstId);
  520. builder.Context(base_id, IncompleteTypeInMemberAccess, base_id);
  521. })) {
  522. return SemIR::ErrorInst::InstId;
  523. }
  524. // Materialize a temporary for the base expression if necessary.
  525. base_id = ConvertToValueOrRefExpr(context, base_id);
  526. base_type_id = context.insts().Get(base_id).type_id();
  527. auto lookup_const_id = context.types().GetConstantId(base_type_id);
  528. // TODO: If the type is a facet, we look through it into the facet's type (a
  529. // FacetType) for names. According to the design, we shouldn't need to do
  530. // this, as the facet should have member names that directly name members of
  531. // the `impl`.
  532. auto base_type_as_facet = GetCanonicalFacetOrTypeValue(
  533. context, context.types().GetTypeInstId(base_type_id));
  534. auto base_type_facet_type_id =
  535. context.insts().Get(base_type_as_facet).type_id();
  536. if (context.types().Is<SemIR::FacetType>(base_type_facet_type_id)) {
  537. lookup_const_id = context.types().GetConstantId(base_type_facet_type_id);
  538. }
  539. // Perform lookup into the base type.
  540. llvm::SmallVector<LookupScope> lookup_scopes;
  541. if (AppendLookupScopesForConstant(
  542. context, loc_id, lookup_const_id,
  543. // The `self_type_const_id` should be the type of `base_id` even if
  544. // it's a facet.
  545. //
  546. // TODO: This can be replaced with `lookup_const_id` once we stop
  547. // having to look through the facet at its type for the scope.
  548. context.types().GetConstantId(base_type_id), &lookup_scopes)) {
  549. auto member_id = LookupMemberNameInScope(
  550. context, loc_id, base_id, name_id, lookup_const_id, lookup_scopes,
  551. /*lookup_in_type_of_base=*/true, required);
  552. // Perform instance binding if we found an instance member.
  553. member_id = PerformInstanceBinding(context, loc_id, base_id, member_id);
  554. return member_id;
  555. }
  556. // The base type is not a name scope. Try some fallback options.
  557. if (auto struct_type = context.insts().TryGetAs<SemIR::StructType>(
  558. context.types().GetTypeInstId(base_type_id))) {
  559. // TODO: Do we need to optimize this with a lookup table for O(1)?
  560. for (auto [i, field] : llvm::enumerate(
  561. context.struct_type_fields().Get(struct_type->fields_id))) {
  562. if (name_id == field.name_id) {
  563. // TODO: Model this as producing a lookup result, and do instance
  564. // binding separately. Perhaps a struct type should be a name scope.
  565. return GetOrAddInst<SemIR::StructAccess>(
  566. context, loc_id,
  567. {.type_id =
  568. context.types().GetTypeIdForTypeInstId(field.type_inst_id),
  569. .struct_id = base_id,
  570. .index = SemIR::ElementIndex(i)});
  571. }
  572. }
  573. if (required) {
  574. CARBON_DIAGNOSTIC(QualifiedExprNameNotFound, Error,
  575. "type {0} does not have a member `{1}`", TypeOfInstId,
  576. SemIR::NameId);
  577. context.emitter().Emit(loc_id, QualifiedExprNameNotFound, base_id,
  578. name_id);
  579. return SemIR::ErrorInst::InstId;
  580. } else {
  581. return SemIR::InstId::None;
  582. }
  583. }
  584. if (base_type_id != SemIR::ErrorInst::TypeId) {
  585. CARBON_DIAGNOSTIC(QualifiedExprUnsupported, Error,
  586. "type {0} does not support qualified expressions",
  587. TypeOfInstId);
  588. context.emitter().Emit(loc_id, QualifiedExprUnsupported, base_id);
  589. }
  590. return SemIR::ErrorInst::InstId;
  591. }
  592. auto PerformAction(Context& context, SemIR::LocId loc_id,
  593. SemIR::AccessMemberAction action) -> SemIR::InstId {
  594. return PerformActionHelper(context, loc_id, action.base_id, action.name_id,
  595. /*required=*/true);
  596. }
  597. auto PerformAction(Context& context, SemIR::LocId loc_id,
  598. SemIR::AccessOptionalMemberAction action) -> SemIR::InstId {
  599. return PerformActionHelper(context, loc_id, action.base_id, action.name_id,
  600. /*required=*/false);
  601. }
  602. // Logic shared by GetAssociatedValue() and PerformCompoundMemberAccess().
  603. static auto GetAssociatedValueImpl(Context& context, SemIR::LocId loc_id,
  604. SemIR::InstId base_id,
  605. const SemIR::AssociatedEntity& assoc_entity,
  606. SemIR::SpecificInterface specific_interface)
  607. -> SemIR::InstId {
  608. // Convert to the interface type of the associated member, to get a facet
  609. // value.
  610. auto interface_type_id = GetInterfaceType(
  611. context, specific_interface.interface_id, specific_interface.specific_id);
  612. auto self_facet_inst_id =
  613. ConvertToValueOfType(context, loc_id, base_id, interface_type_id);
  614. if (self_facet_inst_id == SemIR::ErrorInst::InstId) {
  615. return SemIR::ErrorInst::InstId;
  616. }
  617. auto self_facet_const_id = context.constant_values().Get(self_facet_inst_id);
  618. // TODO: We should be able to lookup constant associated values from runtime
  619. // facet values by using their FacetType only, but we assume constant values
  620. // for impl lookup at the moment.
  621. if (!self_facet_const_id.is_constant()) {
  622. context.TODO(loc_id, "associated value lookup on runtime facet value");
  623. return SemIR::ErrorInst::InstId;
  624. }
  625. // TODO: If `ConvertToValueOfType` returned a `FacetValue`, we already got a
  626. // witness for this interface there. We don't need to do both a
  627. // ConvertToValueOfType and LookupImplWitness, that is redundant. Since we
  628. // want to do LookupImplWitness unconditionally (eg. if `base_id` has exactly
  629. // the right FacetType already), can we drop the ConvertToValueOfType step?
  630. auto lookup_result = LookupImplWitness(
  631. context, loc_id, self_facet_const_id,
  632. EvalOrAddInst(
  633. context, loc_id,
  634. FacetTypeFromInterface(context, specific_interface.interface_id,
  635. specific_interface.specific_id)));
  636. CARBON_CHECK(lookup_result.has_value());
  637. auto witness_id =
  638. GetWitnessFromSingleImplLookupResult(context, lookup_result);
  639. const auto& interface =
  640. context.interfaces().Get(specific_interface.interface_id);
  641. auto interface_with_self_specific_id = MakeSpecificWithInnerSelf(
  642. context, loc_id, interface.generic_id, interface.generic_with_self_id,
  643. specific_interface.specific_id, self_facet_const_id);
  644. // Before we can access the element of the witness, we need to figure out
  645. // the type of that element. It depends on the self type and the specific
  646. // interface.
  647. auto assoc_type_id = GetTypeForSpecificAssociatedEntity(
  648. context, interface_with_self_specific_id, assoc_entity.decl_id);
  649. // Now that we have the witness, an index into it, and the type of the
  650. // result, return the element of the witness.
  651. return GetOrAddInst<SemIR::ImplWitnessAccess>(context, loc_id,
  652. {.type_id = assoc_type_id,
  653. .witness_id = witness_id,
  654. .index = assoc_entity.index});
  655. }
  656. auto GetAssociatedValue(Context& context, SemIR::LocId loc_id,
  657. SemIR::InstId base_id,
  658. SemIR::ConstantId assoc_entity_const_id,
  659. SemIR::SpecificInterface specific_interface)
  660. -> SemIR::InstId {
  661. // TODO: This function shares a code with PerformCompoundMemberAccess(),
  662. // it would be nice to reduce the duplication.
  663. auto assoc_entity =
  664. context.constant_values().GetInstAs<SemIR::AssociatedEntity>(
  665. assoc_entity_const_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.constant_values().InstIs<SemIR::TupleType>(
  724. 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 =
  773. context.constant_values().GetInstAs<SemIR::IntValue>(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