member_access.cpp 18 KB

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