member_access.cpp 18 KB

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