member_access.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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 "llvm/ADT/STLExtras.h"
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/context.h"
  8. #include "toolchain/check/convert.h"
  9. #include "toolchain/check/import_ref.h"
  10. #include "toolchain/diagnostics/diagnostic_emitter.h"
  11. #include "toolchain/sem_ir/generic.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/inst.h"
  14. #include "toolchain/sem_ir/typed_insts.h"
  15. namespace Carbon::Check {
  16. // Returns the lookup scope corresponding to base_id, or nullopt if not a scope.
  17. // On invalid scopes, prints a diagnostic and still returns the scope.
  18. static auto GetAsLookupScope(Context& context, Parse::NodeId node_id,
  19. SemIR::ConstantId base_const_id)
  20. -> std::optional<LookupScope> {
  21. auto base_id = context.constant_values().GetInstId(base_const_id);
  22. auto base = context.insts().Get(base_id);
  23. if (auto base_as_namespace = base.TryAs<SemIR::Namespace>()) {
  24. return LookupScope{.name_scope_id = base_as_namespace->name_scope_id,
  25. .specific_id = SemIR::SpecificId::Invalid};
  26. }
  27. // TODO: Consider refactoring the near-identical class and interface support
  28. // below.
  29. if (auto base_as_class = base.TryAs<SemIR::ClassType>()) {
  30. context.TryToDefineType(
  31. context.GetTypeIdForTypeConstant(base_const_id), [&] {
  32. CARBON_DIAGNOSTIC(QualifiedExprInIncompleteClassScope, Error,
  33. "Member access into incomplete class `{0}`.",
  34. std::string);
  35. return context.emitter().Build(
  36. node_id, QualifiedExprInIncompleteClassScope,
  37. context.sem_ir().StringifyType(base_const_id));
  38. });
  39. auto& class_info = context.classes().Get(base_as_class->class_id);
  40. return LookupScope{.name_scope_id = class_info.scope_id,
  41. .specific_id = base_as_class->specific_id};
  42. }
  43. if (auto base_as_interface = base.TryAs<SemIR::InterfaceType>()) {
  44. context.TryToDefineType(
  45. context.GetTypeIdForTypeConstant(base_const_id), [&] {
  46. CARBON_DIAGNOSTIC(QualifiedExprInUndefinedInterfaceScope, Error,
  47. "Member access into undefined interface `{0}`.",
  48. std::string);
  49. return context.emitter().Build(
  50. node_id, QualifiedExprInUndefinedInterfaceScope,
  51. context.sem_ir().StringifyType(base_const_id));
  52. });
  53. auto& interface_info =
  54. context.interfaces().Get(base_as_interface->interface_id);
  55. return LookupScope{.name_scope_id = interface_info.scope_id,
  56. .specific_id = base_as_interface->specific_id};
  57. }
  58. // TODO: Per the design, if `base_id` is any kind of type, then lookup should
  59. // treat it as a name scope, even if it doesn't have members. For example,
  60. // `(i32*).X` should fail because there's no name `X` in `i32*`, not because
  61. // there's no name `X` in `type`.
  62. return std::nullopt;
  63. }
  64. // Returns the index of the specified class element within the class's
  65. // representation.
  66. static auto GetClassElementIndex(Context& context, SemIR::InstId element_id)
  67. -> SemIR::ElementIndex {
  68. auto element_inst = context.insts().Get(element_id);
  69. if (auto field = element_inst.TryAs<SemIR::FieldDecl>()) {
  70. return field->index;
  71. }
  72. if (auto base = element_inst.TryAs<SemIR::BaseDecl>()) {
  73. return base->index;
  74. }
  75. CARBON_FATAL() << "Unexpected value " << element_inst
  76. << " in class element name";
  77. }
  78. // Returns whether `function_id` is an instance method, that is, whether it has
  79. // an implicit `self` parameter.
  80. static auto IsInstanceMethod(const SemIR::File& sem_ir,
  81. SemIR::FunctionId function_id) -> bool {
  82. const auto& function = sem_ir.functions().Get(function_id);
  83. for (auto param_id :
  84. sem_ir.inst_blocks().GetOrEmpty(function.implicit_param_refs_id)) {
  85. auto param =
  86. SemIR::Function::GetParamFromParamRefId(sem_ir, param_id).second;
  87. if (param.name_id == SemIR::NameId::SelfValue) {
  88. return true;
  89. }
  90. }
  91. return false;
  92. }
  93. // Returns whether `scope` is a scope for which impl lookup should be performed
  94. // if we find an associated entity.
  95. static auto ScopeNeedsImplLookup(Context& context, LookupScope scope) -> bool {
  96. auto [_, inst] = context.name_scopes().GetInstIfValid(scope.name_scope_id);
  97. if (!inst) {
  98. return false;
  99. }
  100. if (inst->Is<SemIR::InterfaceDecl>()) {
  101. // Don't perform impl lookup if an associated entity is named as a member of
  102. // a facet type.
  103. return false;
  104. }
  105. if (inst->Is<SemIR::Namespace>()) {
  106. // Don't perform impl lookup if an associated entity is named as a namespace
  107. // member.
  108. // TODO: This case is not yet listed in the design.
  109. return false;
  110. }
  111. // Any other kind of scope is assumed to be a type that implements the
  112. // interface containing the associated entity, and impl lookup is performed.
  113. return true;
  114. }
  115. // Given a type and an interface, searches for an impl that describes how that
  116. // type implements that interface, and returns the corresponding witness.
  117. // Returns an invalid InstId if no matching impl is found.
  118. static auto LookupInterfaceWitness(Context& context,
  119. SemIR::ConstantId type_const_id,
  120. SemIR::TypeId interface_type_id)
  121. -> SemIR::InstId {
  122. // TODO: Add a better impl lookup system. At the very least, we should only be
  123. // considering impls that are for the same interface we're querying. We can
  124. // also skip impls that mention any types that aren't part of our impl query.
  125. for (const auto& impl : context.impls().array_ref()) {
  126. if (!context.constant_values().AreEqualAcrossDeclarations(
  127. context.types().GetConstantId(impl.self_id), type_const_id)) {
  128. continue;
  129. }
  130. if (!context.types().AreEqualAcrossDeclarations(impl.constraint_id,
  131. interface_type_id)) {
  132. // TODO: An impl of a constraint type should be treated as implementing
  133. // the constraint's interfaces.
  134. continue;
  135. }
  136. if (!impl.witness_id.is_valid()) {
  137. // TODO: Diagnose if the impl isn't defined yet?
  138. return SemIR::InstId::Invalid;
  139. }
  140. LoadImportRef(context, impl.witness_id);
  141. return impl.witness_id;
  142. }
  143. return SemIR::InstId::Invalid;
  144. }
  145. // Performs impl lookup for a member name expression. This finds the relevant
  146. // impl witness and extracts the corresponding impl member.
  147. static auto PerformImplLookup(Context& context, Parse::NodeId node_id,
  148. SemIR::ConstantId type_const_id,
  149. SemIR::AssociatedEntityType assoc_type,
  150. SemIR::InstId member_id) -> SemIR::InstId {
  151. auto interface_type =
  152. context.types().GetAs<SemIR::InterfaceType>(assoc_type.interface_type_id);
  153. auto& interface = context.interfaces().Get(interface_type.interface_id);
  154. auto witness_id = LookupInterfaceWitness(context, type_const_id,
  155. assoc_type.interface_type_id);
  156. if (!witness_id.is_valid()) {
  157. CARBON_DIAGNOSTIC(MissingImplInMemberAccess, Error,
  158. "Cannot access member of interface {0} in type {1} "
  159. "that does not implement that interface.",
  160. SemIR::NameId, std::string);
  161. context.emitter().Emit(node_id, MissingImplInMemberAccess,
  162. interface.name_id,
  163. context.sem_ir().StringifyType(type_const_id));
  164. return SemIR::InstId::BuiltinError;
  165. }
  166. auto member_value_id = context.constant_values().GetConstantInstId(member_id);
  167. if (!member_value_id.is_valid()) {
  168. if (member_value_id != SemIR::InstId::BuiltinError) {
  169. context.TODO(member_id, "non-constant associated entity");
  170. }
  171. return SemIR::InstId::BuiltinError;
  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::InstId::BuiltinError;
  178. }
  179. // TODO: This produces the type of the associated entity with no value for
  180. // `Self`. The type `Self` might appear in the type of an associated constant,
  181. // and if so, we'll need to substitute it here somehow.
  182. auto subst_type_id = SemIR::GetTypeInSpecific(
  183. context.sem_ir(), interface_type.specific_id, assoc_type.entity_type_id);
  184. return context.AddInst(
  185. SemIR::LocIdAndInst::NoLoc<SemIR::InterfaceWitnessAccess>(
  186. {.type_id = subst_type_id,
  187. .witness_id = witness_id,
  188. .index = assoc_entity->index}));
  189. }
  190. // Performs a member name lookup into the specified scope, including performing
  191. // impl lookup if necessary. If the scope is invalid, assume an error has
  192. // already been diagnosed, and return BuiltinError.
  193. static auto LookupMemberNameInScope(Context& context, Parse::NodeId node_id,
  194. SemIR::InstId /*base_id*/,
  195. SemIR::NameId name_id,
  196. SemIR::ConstantId name_scope_const_id,
  197. LookupScope lookup_scope) -> SemIR::InstId {
  198. LookupResult result = {.specific_id = SemIR::SpecificId::Invalid,
  199. .inst_id = SemIR::InstId::BuiltinError};
  200. if (lookup_scope.name_scope_id.is_valid()) {
  201. result = context.LookupQualifiedName(node_id, name_id, lookup_scope);
  202. }
  203. // TODO: This duplicates the work that HandleNameAsExpr does. Factor this out.
  204. auto inst = context.insts().Get(result.inst_id);
  205. auto type_id = SemIR::GetTypeInSpecific(context.sem_ir(), result.specific_id,
  206. inst.type_id());
  207. CARBON_CHECK(type_id.is_valid()) << "Missing type for member " << inst;
  208. // If the named entity has a constant value that depends on its specific,
  209. // store the specific too.
  210. if (result.specific_id.is_valid() &&
  211. context.constant_values().Get(result.inst_id).is_symbolic()) {
  212. result.inst_id = context.AddInst<SemIR::SpecificConstant>(
  213. node_id, {.type_id = type_id,
  214. .inst_id = result.inst_id,
  215. .specific_id = result.specific_id});
  216. }
  217. // TODO: Use a different kind of instruction that also references the
  218. // `base_id` so that `SemIR` consumers can find it.
  219. auto member_id = context.AddInst<SemIR::NameRef>(
  220. node_id,
  221. {.type_id = type_id, .name_id = name_id, .value_id = result.inst_id});
  222. // If member name lookup finds an associated entity name, and the scope is not
  223. // a facet type, perform impl lookup.
  224. //
  225. // TODO: We need to do this as part of searching extended scopes, because a
  226. // lookup that finds an associated entity and also finds the corresponding
  227. // impl member is not supposed to be treated as ambiguous.
  228. if (auto assoc_type =
  229. context.types().TryGetAs<SemIR::AssociatedEntityType>(type_id)) {
  230. if (ScopeNeedsImplLookup(context, lookup_scope)) {
  231. member_id = PerformImplLookup(context, node_id, name_scope_const_id,
  232. *assoc_type, member_id);
  233. }
  234. }
  235. return member_id;
  236. }
  237. // Performs the instance binding step in member access. If the found member is a
  238. // field, forms a class member access. If the found member is an instance
  239. // method, forms a bound method. Otherwise, the member is returned unchanged.
  240. static auto PerformInstanceBinding(Context& context, Parse::NodeId node_id,
  241. SemIR::InstId base_id,
  242. SemIR::InstId member_id) -> SemIR::InstId {
  243. auto member_type_id = context.insts().Get(member_id).type_id();
  244. CARBON_KIND_SWITCH(context.types().GetAsInst(member_type_id)) {
  245. case CARBON_KIND(SemIR::UnboundElementType unbound_element_type): {
  246. // Convert the base to the type of the element if necessary.
  247. base_id = ConvertToValueOrRefOfType(context, node_id, base_id,
  248. unbound_element_type.class_type_id);
  249. // Find the specified element, which could be either a field or a base
  250. // class, and build an element access expression.
  251. auto element_id = context.constant_values().GetConstantInstId(member_id);
  252. CARBON_CHECK(element_id.is_valid())
  253. << "Non-constant value " << context.insts().Get(member_id)
  254. << " of unbound element type";
  255. auto index = GetClassElementIndex(context, element_id);
  256. auto access_id = context.AddInst<SemIR::ClassElementAccess>(
  257. node_id, {.type_id = unbound_element_type.element_type_id,
  258. .base_id = base_id,
  259. .index = index});
  260. if (SemIR::GetExprCategory(context.sem_ir(), base_id) ==
  261. SemIR::ExprCategory::Value &&
  262. SemIR::GetExprCategory(context.sem_ir(), access_id) !=
  263. SemIR::ExprCategory::Value) {
  264. // Class element access on a value expression produces an ephemeral
  265. // reference if the class's value representation is a pointer to the
  266. // object representation. Add a value binding in that case so that the
  267. // expression category of the result matches the expression category of
  268. // the base.
  269. access_id = ConvertToValueExpr(context, access_id);
  270. }
  271. return access_id;
  272. }
  273. case CARBON_KIND(SemIR::FunctionType fn_type): {
  274. if (IsInstanceMethod(context.sem_ir(), fn_type.function_id)) {
  275. return context.AddInst<SemIR::BoundMethod>(
  276. node_id, {.type_id = context.GetBuiltinType(
  277. SemIR::BuiltinInstKind::BoundMethodType),
  278. .object_id = base_id,
  279. .function_id = member_id});
  280. }
  281. [[fallthrough]];
  282. }
  283. default:
  284. // Not an instance member: no instance binding.
  285. return member_id;
  286. }
  287. }
  288. auto PerformMemberAccess(Context& context, Parse::NodeId node_id,
  289. SemIR::InstId base_id, SemIR::NameId name_id)
  290. -> SemIR::InstId {
  291. // If the base is a name scope, such as a class or namespace, perform lookup
  292. // into that scope.
  293. if (auto base_const_id = context.constant_values().Get(base_id);
  294. base_const_id.is_constant()) {
  295. if (auto lookup_scope = GetAsLookupScope(context, node_id, base_const_id)) {
  296. return LookupMemberNameInScope(context, node_id, base_id, name_id,
  297. base_const_id, *lookup_scope);
  298. }
  299. }
  300. // If the base isn't a scope, it must have a complete type.
  301. auto base_type_id = context.insts().Get(base_id).type_id();
  302. if (!context.TryToCompleteType(base_type_id, [&] {
  303. CARBON_DIAGNOSTIC(IncompleteTypeInMemberAccess, Error,
  304. "Member access into object of incomplete type `{0}`.",
  305. SemIR::TypeId);
  306. return context.emitter().Build(base_id, IncompleteTypeInMemberAccess,
  307. base_type_id);
  308. })) {
  309. return SemIR::InstId::BuiltinError;
  310. }
  311. // Materialize a temporary for the base expression if necessary.
  312. base_id = ConvertToValueOrRefExpr(context, base_id);
  313. base_type_id = context.insts().Get(base_id).type_id();
  314. auto base_type_const_id = context.types().GetConstantId(base_type_id);
  315. // Find the scope corresponding to the base type.
  316. auto lookup_scope = GetAsLookupScope(context, node_id, base_type_const_id);
  317. if (!lookup_scope) {
  318. // The base type is not a name scope. Try some fallback options.
  319. if (auto struct_type = context.insts().TryGetAs<SemIR::StructType>(
  320. context.constant_values().GetInstId(base_type_const_id))) {
  321. // TODO: Do we need to optimize this with a lookup table for O(1)?
  322. for (auto [i, ref_id] :
  323. llvm::enumerate(context.inst_blocks().Get(struct_type->fields_id))) {
  324. auto field = context.insts().GetAs<SemIR::StructTypeField>(ref_id);
  325. if (name_id == field.name_id) {
  326. // TODO: Model this as producing a lookup result, and do instance
  327. // binding separately. Perhaps a struct type should be a name scope.
  328. return context.AddInst<SemIR::StructAccess>(
  329. node_id, {.type_id = field.field_type_id,
  330. .struct_id = base_id,
  331. .index = SemIR::ElementIndex(i)});
  332. }
  333. }
  334. CARBON_DIAGNOSTIC(QualifiedExprNameNotFound, Error,
  335. "Type `{0}` does not have a member `{1}`.",
  336. SemIR::TypeId, SemIR::NameId);
  337. context.emitter().Emit(node_id, QualifiedExprNameNotFound, base_type_id,
  338. name_id);
  339. return SemIR::InstId::BuiltinError;
  340. }
  341. if (base_type_id != SemIR::TypeId::Error) {
  342. CARBON_DIAGNOSTIC(QualifiedExprUnsupported, Error,
  343. "Type `{0}` does not support qualified expressions.",
  344. SemIR::TypeId);
  345. context.emitter().Emit(node_id, QualifiedExprUnsupported, base_type_id);
  346. }
  347. return SemIR::InstId::BuiltinError;
  348. }
  349. // Perform lookup into the base type.
  350. auto member_id = LookupMemberNameInScope(context, node_id, base_id, name_id,
  351. base_type_const_id, *lookup_scope);
  352. // Perform instance binding if we found an instance member.
  353. member_id = PerformInstanceBinding(context, node_id, base_id, member_id);
  354. return member_id;
  355. }
  356. auto PerformCompoundMemberAccess(Context& context, Parse::NodeId node_id,
  357. SemIR::InstId base_id,
  358. SemIR::InstId member_expr_id)
  359. -> SemIR::InstId {
  360. // Materialize a temporary for the base expression if necessary.
  361. base_id = ConvertToValueOrRefExpr(context, base_id);
  362. auto base_type_id = context.insts().Get(base_id).type_id();
  363. auto base_type_const_id = context.types().GetConstantId(base_type_id);
  364. auto member_id = member_expr_id;
  365. auto member = context.insts().Get(member_id);
  366. // If the member expression names an associated entity, impl lookup is always
  367. // performed using the type of the base expression.
  368. if (auto assoc_type = context.types().TryGetAs<SemIR::AssociatedEntityType>(
  369. member.type_id())) {
  370. member_id = PerformImplLookup(context, node_id, base_type_const_id,
  371. *assoc_type, member_id);
  372. }
  373. // Perform instance binding if we found an instance member.
  374. member_id = PerformInstanceBinding(context, node_id, base_id, member_id);
  375. // If we didn't perform impl lookup or instance binding, that's an error
  376. // because the base expression is not used for anything.
  377. if (member_id == member_expr_id) {
  378. CARBON_DIAGNOSTIC(CompoundMemberAccessDoesNotUseBase, Error,
  379. "Member name of type `{0}` in compound member access is "
  380. "not an instance member or an interface member.",
  381. SemIR::TypeId);
  382. context.emitter().Emit(node_id, CompoundMemberAccessDoesNotUseBase,
  383. member.type_id());
  384. }
  385. return member_id;
  386. }
  387. } // namespace Carbon::Check