member_access.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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<SemIR::InterfaceWitnessAccess>(
  185. node_id, {.type_id = subst_type_id,
  186. .witness_id = witness_id,
  187. .index = assoc_entity->index});
  188. }
  189. // Performs a member name lookup into the specified scope, including performing
  190. // impl lookup if necessary. If the scope is invalid, assume an error has
  191. // already been diagnosed, and return BuiltinError.
  192. static auto LookupMemberNameInScope(Context& context, Parse::NodeId node_id,
  193. SemIR::InstId /*base_id*/,
  194. SemIR::NameId name_id,
  195. SemIR::ConstantId name_scope_const_id,
  196. LookupScope lookup_scope) -> SemIR::InstId {
  197. LookupResult result = {.specific_id = SemIR::SpecificId::Invalid,
  198. .inst_id = SemIR::InstId::BuiltinError};
  199. if (lookup_scope.name_scope_id.is_valid()) {
  200. result = context.LookupQualifiedName(node_id, name_id, lookup_scope);
  201. }
  202. // TODO: This duplicates the work that HandleNameAsExpr does. Factor this out.
  203. auto inst = context.insts().Get(result.inst_id);
  204. auto type_id = SemIR::GetTypeInSpecific(context.sem_ir(), result.specific_id,
  205. inst.type_id());
  206. CARBON_CHECK(type_id.is_valid()) << "Missing type for member " << inst;
  207. // If the named entity has a constant value that depends on its specific,
  208. // store the specific too.
  209. if (result.specific_id.is_valid() &&
  210. context.constant_values().Get(result.inst_id).is_symbolic()) {
  211. result.inst_id = context.AddInst<SemIR::SpecificConstant>(
  212. node_id, {.type_id = type_id,
  213. .inst_id = result.inst_id,
  214. .specific_id = result.specific_id});
  215. }
  216. // TODO: Use a different kind of instruction that also references the
  217. // `base_id` so that `SemIR` consumers can find it.
  218. auto member_id = context.AddInst<SemIR::NameRef>(
  219. node_id,
  220. {.type_id = type_id, .name_id = name_id, .value_id = result.inst_id});
  221. // If member name lookup finds an associated entity name, and the scope is not
  222. // a facet type, perform impl lookup.
  223. //
  224. // TODO: We need to do this as part of searching extended scopes, because a
  225. // lookup that finds an associated entity and also finds the corresponding
  226. // impl member is not supposed to be treated as ambiguous.
  227. if (auto assoc_type =
  228. context.types().TryGetAs<SemIR::AssociatedEntityType>(type_id)) {
  229. if (ScopeNeedsImplLookup(context, lookup_scope)) {
  230. member_id = PerformImplLookup(context, node_id, name_scope_const_id,
  231. *assoc_type, member_id);
  232. }
  233. }
  234. return member_id;
  235. }
  236. // Performs the instance binding step in member access. If the found member is a
  237. // field, forms a class member access. If the found member is an instance
  238. // method, forms a bound method. Otherwise, the member is returned unchanged.
  239. static auto PerformInstanceBinding(Context& context, Parse::NodeId node_id,
  240. SemIR::InstId base_id,
  241. SemIR::InstId member_id) -> SemIR::InstId {
  242. auto member_type_id = context.insts().Get(member_id).type_id();
  243. CARBON_KIND_SWITCH(context.types().GetAsInst(member_type_id)) {
  244. case CARBON_KIND(SemIR::UnboundElementType unbound_element_type): {
  245. // Convert the base to the type of the element if necessary.
  246. base_id = ConvertToValueOrRefOfType(context, node_id, base_id,
  247. unbound_element_type.class_type_id);
  248. // Find the specified element, which could be either a field or a base
  249. // class, and build an element access expression.
  250. auto element_id = context.constant_values().GetConstantInstId(member_id);
  251. CARBON_CHECK(element_id.is_valid())
  252. << "Non-constant value " << context.insts().Get(member_id)
  253. << " of unbound element type";
  254. auto index = GetClassElementIndex(context, element_id);
  255. auto access_id = context.AddInst<SemIR::ClassElementAccess>(
  256. node_id, {.type_id = unbound_element_type.element_type_id,
  257. .base_id = base_id,
  258. .index = index});
  259. if (SemIR::GetExprCategory(context.sem_ir(), base_id) ==
  260. SemIR::ExprCategory::Value &&
  261. SemIR::GetExprCategory(context.sem_ir(), access_id) !=
  262. SemIR::ExprCategory::Value) {
  263. // Class element access on a value expression produces an ephemeral
  264. // reference if the class's value representation is a pointer to the
  265. // object representation. Add a value binding in that case so that the
  266. // expression category of the result matches the expression category of
  267. // the base.
  268. access_id = ConvertToValueExpr(context, access_id);
  269. }
  270. return access_id;
  271. }
  272. case CARBON_KIND(SemIR::FunctionType fn_type): {
  273. if (IsInstanceMethod(context.sem_ir(), fn_type.function_id)) {
  274. return context.AddInst<SemIR::BoundMethod>(
  275. node_id, {.type_id = context.GetBuiltinType(
  276. SemIR::BuiltinInstKind::BoundMethodType),
  277. .object_id = base_id,
  278. .function_id = member_id});
  279. }
  280. [[fallthrough]];
  281. }
  282. default:
  283. // Not an instance member: no instance binding.
  284. return member_id;
  285. }
  286. }
  287. // Validates that the index (required to be an IntLiteral) is valid within the
  288. // tuple size. Returns the index on success, or nullptr on failure.
  289. static auto ValidateTupleIndex(Context& context, Parse::NodeId node_id,
  290. SemIR::Inst operand_inst,
  291. SemIR::IntLiteral index_inst, int size)
  292. -> const llvm::APInt* {
  293. const auto& index_val = context.ints().Get(index_inst.int_id);
  294. if (index_val.uge(size)) {
  295. CARBON_DIAGNOSTIC(
  296. TupleIndexOutOfBounds, Error,
  297. "Tuple element index `{0}` is past the end of type `{1}`.", TypedInt,
  298. SemIR::TypeId);
  299. context.emitter().Emit(node_id, TupleIndexOutOfBounds,
  300. {.type = index_inst.type_id, .value = index_val},
  301. operand_inst.type_id());
  302. return nullptr;
  303. }
  304. return &index_val;
  305. }
  306. auto PerformMemberAccess(Context& context, Parse::NodeId node_id,
  307. SemIR::InstId base_id, SemIR::NameId name_id)
  308. -> SemIR::InstId {
  309. // If the base is a name scope, such as a class or namespace, perform lookup
  310. // into that scope.
  311. if (auto base_const_id = context.constant_values().Get(base_id);
  312. base_const_id.is_constant()) {
  313. if (auto lookup_scope = GetAsLookupScope(context, node_id, base_const_id)) {
  314. return LookupMemberNameInScope(context, node_id, base_id, name_id,
  315. base_const_id, *lookup_scope);
  316. }
  317. }
  318. // If the base isn't a scope, it must have a complete type.
  319. auto base_type_id = context.insts().Get(base_id).type_id();
  320. if (!context.TryToCompleteType(base_type_id, [&] {
  321. CARBON_DIAGNOSTIC(IncompleteTypeInMemberAccess, Error,
  322. "Member access into object of incomplete type `{0}`.",
  323. SemIR::TypeId);
  324. return context.emitter().Build(base_id, IncompleteTypeInMemberAccess,
  325. base_type_id);
  326. })) {
  327. return SemIR::InstId::BuiltinError;
  328. }
  329. // Materialize a temporary for the base expression if necessary.
  330. base_id = ConvertToValueOrRefExpr(context, base_id);
  331. base_type_id = context.insts().Get(base_id).type_id();
  332. auto base_type_const_id = context.types().GetConstantId(base_type_id);
  333. // Find the scope corresponding to the base type.
  334. auto lookup_scope = GetAsLookupScope(context, node_id, base_type_const_id);
  335. if (!lookup_scope) {
  336. // The base type is not a name scope. Try some fallback options.
  337. if (auto struct_type = context.insts().TryGetAs<SemIR::StructType>(
  338. context.constant_values().GetInstId(base_type_const_id))) {
  339. // TODO: Do we need to optimize this with a lookup table for O(1)?
  340. for (auto [i, ref_id] :
  341. llvm::enumerate(context.inst_blocks().Get(struct_type->fields_id))) {
  342. auto field = context.insts().GetAs<SemIR::StructTypeField>(ref_id);
  343. if (name_id == field.name_id) {
  344. // TODO: Model this as producing a lookup result, and do instance
  345. // binding separately. Perhaps a struct type should be a name scope.
  346. return context.AddInst<SemIR::StructAccess>(
  347. node_id, {.type_id = field.field_type_id,
  348. .struct_id = base_id,
  349. .index = SemIR::ElementIndex(i)});
  350. }
  351. }
  352. CARBON_DIAGNOSTIC(QualifiedExprNameNotFound, Error,
  353. "Type `{0}` does not have a member `{1}`.",
  354. SemIR::TypeId, SemIR::NameId);
  355. context.emitter().Emit(node_id, QualifiedExprNameNotFound, base_type_id,
  356. name_id);
  357. return SemIR::InstId::BuiltinError;
  358. }
  359. if (base_type_id != SemIR::TypeId::Error) {
  360. CARBON_DIAGNOSTIC(QualifiedExprUnsupported, Error,
  361. "Type `{0}` does not support qualified expressions.",
  362. SemIR::TypeId);
  363. context.emitter().Emit(node_id, QualifiedExprUnsupported, base_type_id);
  364. }
  365. return SemIR::InstId::BuiltinError;
  366. }
  367. // Perform lookup into the base type.
  368. auto member_id = LookupMemberNameInScope(context, node_id, base_id, name_id,
  369. base_type_const_id, *lookup_scope);
  370. // Perform instance binding if we found an instance member.
  371. member_id = PerformInstanceBinding(context, node_id, base_id, member_id);
  372. return member_id;
  373. }
  374. auto PerformCompoundMemberAccess(Context& context, Parse::NodeId node_id,
  375. SemIR::InstId base_id,
  376. SemIR::InstId member_expr_id)
  377. -> SemIR::InstId {
  378. // Materialize a temporary for the base expression if necessary.
  379. base_id = ConvertToValueOrRefExpr(context, base_id);
  380. auto base_type_id = context.insts().Get(base_id).type_id();
  381. auto base_type_const_id = context.types().GetConstantId(base_type_id);
  382. auto member_id = member_expr_id;
  383. auto member = context.insts().Get(member_id);
  384. // If the member expression names an associated entity, impl lookup is always
  385. // performed using the type of the base expression.
  386. if (auto assoc_type = context.types().TryGetAs<SemIR::AssociatedEntityType>(
  387. member.type_id())) {
  388. member_id = PerformImplLookup(context, node_id, base_type_const_id,
  389. *assoc_type, member_id);
  390. } else if (context.insts().Is<SemIR::TupleType>(
  391. context.constant_values().GetInstId(base_type_const_id))) {
  392. return PerformTupleIndex(context, node_id, base_id, member_expr_id);
  393. }
  394. // Perform instance binding if we found an instance member.
  395. member_id = PerformInstanceBinding(context, node_id, base_id, member_id);
  396. // If we didn't perform impl lookup or instance binding, that's an error
  397. // because the base expression is not used for anything.
  398. if (member_id == member_expr_id) {
  399. CARBON_DIAGNOSTIC(CompoundMemberAccessDoesNotUseBase, Error,
  400. "Member name of type `{0}` in compound member access is "
  401. "not an instance member or an interface member.",
  402. SemIR::TypeId);
  403. context.emitter().Emit(node_id, CompoundMemberAccessDoesNotUseBase,
  404. member.type_id());
  405. }
  406. return member_id;
  407. }
  408. auto PerformTupleIndex(Context& context, Parse::NodeId node_id,
  409. SemIR::InstId tuple_inst_id, SemIR::InstId index_inst_id)
  410. -> SemIR::InstId {
  411. tuple_inst_id = ConvertToValueOrRefExpr(context, tuple_inst_id);
  412. auto tuple_inst = context.insts().Get(tuple_inst_id);
  413. auto tuple_type_id = tuple_inst.type_id();
  414. auto tuple_type = context.types().TryGetAs<SemIR::TupleType>(tuple_type_id);
  415. if (!tuple_type) {
  416. CARBON_DIAGNOSTIC(TupleIndexOnANonTupleType, Error,
  417. "Type `{0}` does not support tuple indexing. Only "
  418. "tuples can be indexed that way.",
  419. SemIR::TypeId);
  420. context.emitter().Emit(node_id, TupleIndexOnANonTupleType, tuple_type_id);
  421. return SemIR::InstId::BuiltinError;
  422. }
  423. SemIR::TypeId element_type_id = SemIR::TypeId::Error;
  424. auto index_node_id = context.insts().GetLocId(index_inst_id);
  425. index_inst_id = ConvertToValueOfType(
  426. context, index_node_id, index_inst_id,
  427. context.GetBuiltinType(SemIR::BuiltinInstKind::IntType));
  428. auto index_const_id = context.constant_values().Get(index_inst_id);
  429. if (index_const_id == SemIR::ConstantId::Error) {
  430. index_inst_id = SemIR::InstId::BuiltinError;
  431. } else if (!index_const_id.is_template()) {
  432. // TODO: Decide what to do if the index is a symbolic constant.
  433. CARBON_DIAGNOSTIC(TupleIndexNotConstant, Error,
  434. "Tuple index must be a constant.");
  435. context.emitter().Emit(node_id, TupleIndexNotConstant);
  436. index_inst_id = SemIR::InstId::BuiltinError;
  437. } else {
  438. auto index_literal = context.insts().GetAs<SemIR::IntLiteral>(
  439. context.constant_values().GetInstId(index_const_id));
  440. auto type_block = context.type_blocks().Get(tuple_type->elements_id);
  441. if (const auto* index_val = ValidateTupleIndex(
  442. context, node_id, tuple_inst, index_literal, type_block.size())) {
  443. element_type_id = type_block[index_val->getZExtValue()];
  444. } else {
  445. index_inst_id = SemIR::InstId::BuiltinError;
  446. }
  447. }
  448. return context.AddInst<SemIR::TupleIndex>(node_id,
  449. {.type_id = element_type_id,
  450. .tuple_id = tuple_inst_id,
  451. .index_id = index_inst_id});
  452. }
  453. } // namespace Carbon::Check