member_access.cpp 19 KB

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