member_access.cpp 18 KB

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