member_access.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 <optional>
  6. #include "llvm/ADT/STLExtras.h"
  7. #include "toolchain/base/kind_switch.h"
  8. #include "toolchain/check/context.h"
  9. #include "toolchain/check/convert.h"
  10. #include "toolchain/check/impl_lookup.h"
  11. #include "toolchain/diagnostics/diagnostic_emitter.h"
  12. #include "toolchain/sem_ir/generic.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/inst.h"
  15. #include "toolchain/sem_ir/name_scope.h"
  16. #include "toolchain/sem_ir/typed_insts.h"
  17. namespace Carbon::Check {
  18. // Returns the index of the specified class element within the class's
  19. // representation.
  20. static auto GetClassElementIndex(Context& context, SemIR::InstId element_id)
  21. -> SemIR::ElementIndex {
  22. auto element_inst = context.insts().Get(element_id);
  23. if (auto field = element_inst.TryAs<SemIR::FieldDecl>()) {
  24. return field->index;
  25. }
  26. if (auto base = element_inst.TryAs<SemIR::BaseDecl>()) {
  27. return base->index;
  28. }
  29. CARBON_FATAL("Unexpected value {0} in class element name", element_inst);
  30. }
  31. // Returns whether `function_id` is an instance method, that is, whether it has
  32. // an implicit `self` parameter.
  33. static auto IsInstanceMethod(const SemIR::File& sem_ir,
  34. SemIR::FunctionId function_id) -> bool {
  35. const auto& function = sem_ir.functions().Get(function_id);
  36. for (auto param_id :
  37. sem_ir.inst_blocks().GetOrEmpty(function.implicit_param_patterns_id)) {
  38. if (SemIR::Function::GetNameFromPatternId(sem_ir, param_id) ==
  39. SemIR::NameId::SelfValue) {
  40. return true;
  41. }
  42. }
  43. return false;
  44. }
  45. // Returns the highest allowed access. For example, if this returns `Protected`
  46. // then only `Public` and `Protected` accesses are allowed--not `Private`.
  47. static auto GetHighestAllowedAccess(Context& context, SemIR::LocId loc_id,
  48. SemIR::ConstantId name_scope_const_id)
  49. -> SemIR::AccessKind {
  50. auto [_, self_type_inst_id] = context.LookupUnqualifiedName(
  51. loc_id.node_id(), SemIR::NameId::SelfType, /*required=*/false);
  52. if (!self_type_inst_id.is_valid()) {
  53. return SemIR::AccessKind::Public;
  54. }
  55. // TODO: Support other types for `Self`.
  56. auto self_class_type =
  57. context.insts().TryGetAs<SemIR::ClassType>(self_type_inst_id);
  58. if (!self_class_type) {
  59. return SemIR::AccessKind::Public;
  60. }
  61. auto self_class_info = context.classes().Get(self_class_type->class_id);
  62. // TODO: Support other types.
  63. if (auto class_type = context.insts().TryGetAs<SemIR::ClassType>(
  64. context.constant_values().GetInstId(name_scope_const_id))) {
  65. auto class_info = context.classes().Get(class_type->class_id);
  66. if (self_class_info.self_type_id == class_info.self_type_id) {
  67. return SemIR::AccessKind::Private;
  68. }
  69. // If the `type_id` of `Self` does not match with the one we're currently
  70. // accessing, try checking if this class is of the parent type of `Self`.
  71. if (auto base_decl = context.insts().TryGetAsIfValid<SemIR::BaseDecl>(
  72. self_class_info.base_id)) {
  73. if (base_decl->base_type_id == class_info.self_type_id) {
  74. return SemIR::AccessKind::Protected;
  75. }
  76. } else if (auto adapt_decl =
  77. context.insts().TryGetAsIfValid<SemIR::AdaptDecl>(
  78. self_class_info.adapt_id)) {
  79. if (adapt_decl->adapted_type_id == class_info.self_type_id) {
  80. return SemIR::AccessKind::Protected;
  81. }
  82. }
  83. }
  84. return SemIR::AccessKind::Public;
  85. }
  86. // Returns whether `scope` is a scope for which impl lookup should be performed
  87. // if we find an associated entity.
  88. static auto ScopeNeedsImplLookup(Context& context,
  89. SemIR::ConstantId name_scope_const_id)
  90. -> bool {
  91. SemIR::InstId inst_id =
  92. context.constant_values().GetInstId(name_scope_const_id);
  93. CARBON_CHECK(inst_id.is_valid());
  94. SemIR::Inst inst = context.insts().Get(inst_id);
  95. if (inst.Is<SemIR::FacetType>()) {
  96. // Don't perform impl lookup if an associated entity is named as a member of
  97. // a facet type.
  98. return false;
  99. }
  100. if (inst.Is<SemIR::Namespace>()) {
  101. // Don't perform impl lookup if an associated entity is named as a namespace
  102. // member.
  103. // TODO: This case is not yet listed in the design.
  104. return false;
  105. }
  106. // Any other kind of scope is assumed to be a type that implements the
  107. // interface containing the associated entity, and impl lookup is performed.
  108. return true;
  109. }
  110. // Performs impl lookup for a member name expression. This finds the relevant
  111. // impl witness and extracts the corresponding impl member.
  112. static auto PerformImplLookup(
  113. Context& context, SemIR::LocId loc_id, SemIR::ConstantId type_const_id,
  114. SemIR::AssociatedEntityType assoc_type, SemIR::InstId member_id,
  115. Context::BuildDiagnosticFn missing_impl_diagnoser = nullptr)
  116. -> SemIR::InstId {
  117. auto facet_type =
  118. context.types().GetAs<SemIR::FacetType>(assoc_type.interface_type_id);
  119. const auto& facet_type_info =
  120. context.facet_types().Get(facet_type.facet_type_id);
  121. auto interface_type = facet_type_info.TryAsSingleInterface();
  122. if (!interface_type) {
  123. context.TODO(loc_id,
  124. "Lookup of impl witness not yet supported except for a single "
  125. "interface");
  126. return SemIR::InstId::BuiltinError;
  127. }
  128. auto witness_id =
  129. LookupInterfaceWitness(context, loc_id, type_const_id,
  130. assoc_type.interface_type_id.AsConstantId());
  131. if (!witness_id.is_valid()) {
  132. auto interface_type_id = context.GetInterfaceType(
  133. interface_type->interface_id, interface_type->specific_id);
  134. if (missing_impl_diagnoser) {
  135. // TODO: Pass in the expression whose type we are printing.
  136. CARBON_DIAGNOSTIC(MissingImplInMemberAccessNote, Note,
  137. "type {1} does not implement interface {0}",
  138. SemIR::TypeId, SemIR::TypeId);
  139. missing_impl_diagnoser()
  140. .Note(loc_id, MissingImplInMemberAccessNote, interface_type_id,
  141. context.GetTypeIdForTypeConstant(type_const_id))
  142. .Emit();
  143. } else {
  144. // TODO: Pass in the expression whose type we are printing.
  145. CARBON_DIAGNOSTIC(MissingImplInMemberAccess, Error,
  146. "cannot access member of interface {0} in type {1} "
  147. "that does not implement that interface",
  148. SemIR::TypeId, SemIR::TypeId);
  149. context.emitter().Emit(loc_id, MissingImplInMemberAccess,
  150. interface_type_id,
  151. context.GetTypeIdForTypeConstant(type_const_id));
  152. }
  153. return SemIR::InstId::BuiltinError;
  154. }
  155. auto member_value_id = context.constant_values().GetConstantInstId(member_id);
  156. if (!member_value_id.is_valid()) {
  157. if (member_value_id != SemIR::InstId::BuiltinError) {
  158. context.TODO(member_id, "non-constant associated entity");
  159. }
  160. return SemIR::InstId::BuiltinError;
  161. }
  162. auto assoc_entity =
  163. context.insts().TryGetAs<SemIR::AssociatedEntity>(member_value_id);
  164. if (!assoc_entity) {
  165. context.TODO(member_id, "unexpected value for associated entity");
  166. return SemIR::InstId::BuiltinError;
  167. }
  168. // TODO: This produces the type of the associated entity with no value for
  169. // `Self`. The type `Self` might appear in the type of an associated constant,
  170. // and if so, we'll need to substitute it here somehow.
  171. auto subst_type_id = SemIR::GetTypeInSpecific(
  172. context.sem_ir(), interface_type->specific_id, assoc_type.entity_type_id);
  173. return context.GetOrAddInst<SemIR::InterfaceWitnessAccess>(
  174. loc_id, {.type_id = subst_type_id,
  175. .witness_id = witness_id,
  176. .index = assoc_entity->index});
  177. }
  178. // Performs a member name lookup into the specified scope, including performing
  179. // impl lookup if necessary. If the scope is invalid, assume an error has
  180. // already been diagnosed, and return BuiltinError.
  181. static auto LookupMemberNameInScope(Context& context, SemIR::LocId loc_id,
  182. SemIR::InstId /*base_id*/,
  183. SemIR::NameId name_id,
  184. SemIR::ConstantId name_scope_const_id,
  185. llvm::ArrayRef<LookupScope> lookup_scopes)
  186. -> SemIR::InstId {
  187. AccessInfo access_info = {
  188. .constant_id = name_scope_const_id,
  189. .highest_allowed_access =
  190. GetHighestAllowedAccess(context, loc_id, name_scope_const_id),
  191. };
  192. LookupResult result =
  193. context.LookupQualifiedName(loc_id, name_id, lookup_scopes,
  194. /*required=*/true, access_info);
  195. if (!result.inst_id.is_valid()) {
  196. return SemIR::InstId::BuiltinError;
  197. }
  198. // TODO: This duplicates the work that HandleNameAsExpr does. Factor this out.
  199. auto inst = context.insts().Get(result.inst_id);
  200. auto type_id = SemIR::GetTypeInSpecific(context.sem_ir(), result.specific_id,
  201. inst.type_id());
  202. CARBON_CHECK(type_id.is_valid(), "Missing type for member {0}", inst);
  203. // If the named entity has a constant value that depends on its specific,
  204. // store the specific too.
  205. if (result.specific_id.is_valid() &&
  206. context.constant_values().Get(result.inst_id).is_symbolic()) {
  207. result.inst_id = context.GetOrAddInst<SemIR::SpecificConstant>(
  208. loc_id, {.type_id = type_id,
  209. .inst_id = result.inst_id,
  210. .specific_id = result.specific_id});
  211. }
  212. // TODO: Use a different kind of instruction that also references the
  213. // `base_id` so that `SemIR` consumers can find it.
  214. auto member_id = context.GetOrAddInst<SemIR::NameRef>(
  215. loc_id,
  216. {.type_id = type_id, .name_id = name_id, .value_id = result.inst_id});
  217. // If member name lookup finds an associated entity name, and the scope is not
  218. // a facet type, perform impl lookup.
  219. //
  220. // TODO: We need to do this as part of searching extended scopes, because a
  221. // lookup that finds an associated entity and also finds the corresponding
  222. // impl member is not supposed to be treated as ambiguous.
  223. if (auto assoc_type =
  224. context.types().TryGetAs<SemIR::AssociatedEntityType>(type_id)) {
  225. if (ScopeNeedsImplLookup(context, name_scope_const_id)) {
  226. member_id = PerformImplLookup(context, loc_id, name_scope_const_id,
  227. *assoc_type, member_id);
  228. }
  229. }
  230. return member_id;
  231. }
  232. // Performs the instance binding step in member access. If the found member is a
  233. // field, forms a class member access. If the found member is an instance
  234. // method, forms a bound method. Otherwise, the member is returned unchanged.
  235. static auto PerformInstanceBinding(Context& context, SemIR::LocId loc_id,
  236. SemIR::InstId base_id,
  237. SemIR::InstId member_id) -> SemIR::InstId {
  238. auto member_type_id = context.insts().Get(member_id).type_id();
  239. CARBON_KIND_SWITCH(context.types().GetAsInst(member_type_id)) {
  240. case CARBON_KIND(SemIR::UnboundElementType unbound_element_type): {
  241. // Convert the base to the type of the element if necessary.
  242. base_id = ConvertToValueOrRefOfType(context, loc_id, base_id,
  243. unbound_element_type.class_type_id);
  244. // Find the specified element, which could be either a field or a base
  245. // class, and build an element access expression.
  246. auto element_id = context.constant_values().GetConstantInstId(member_id);
  247. CARBON_CHECK(element_id.is_valid(),
  248. "Non-constant value {0} of unbound element type",
  249. context.insts().Get(member_id));
  250. auto index = GetClassElementIndex(context, element_id);
  251. auto access_id = context.GetOrAddInst<SemIR::ClassElementAccess>(
  252. loc_id, {.type_id = unbound_element_type.element_type_id,
  253. .base_id = base_id,
  254. .index = index});
  255. if (SemIR::GetExprCategory(context.sem_ir(), base_id) ==
  256. SemIR::ExprCategory::Value &&
  257. SemIR::GetExprCategory(context.sem_ir(), access_id) !=
  258. SemIR::ExprCategory::Value) {
  259. // Class element access on a value expression produces an ephemeral
  260. // reference if the class's value representation is a pointer to the
  261. // object representation. Add a value binding in that case so that the
  262. // expression category of the result matches the expression category of
  263. // the base.
  264. access_id = ConvertToValueExpr(context, access_id);
  265. }
  266. return access_id;
  267. }
  268. case CARBON_KIND(SemIR::FunctionType fn_type): {
  269. if (IsInstanceMethod(context.sem_ir(), fn_type.function_id)) {
  270. return context.GetOrAddInst<SemIR::BoundMethod>(
  271. loc_id, {.type_id = context.GetBuiltinType(
  272. SemIR::BuiltinInstKind::BoundMethodType),
  273. .object_id = base_id,
  274. .function_id = member_id});
  275. }
  276. [[fallthrough]];
  277. }
  278. default:
  279. // Not an instance member: no instance binding.
  280. return member_id;
  281. }
  282. }
  283. // Validates that the index (required to be an IntValue) is valid within the
  284. // tuple size. Returns the index on success, or nullptr on failure.
  285. static auto ValidateTupleIndex(Context& context, SemIR::LocId loc_id,
  286. SemIR::InstId operand_inst_id,
  287. SemIR::IntValue index_inst, int size)
  288. -> std::optional<llvm::APInt> {
  289. llvm::APInt index_val = context.ints().Get(index_inst.int_id);
  290. if (index_val.uge(size)) {
  291. CARBON_DIAGNOSTIC(TupleIndexOutOfBounds, Error,
  292. "tuple element index `{0}` is past the end of type {1}",
  293. TypedInt, TypeOfInstId);
  294. context.emitter().Emit(loc_id, TupleIndexOutOfBounds,
  295. {.type = index_inst.type_id, .value = index_val},
  296. operand_inst_id);
  297. return std::nullopt;
  298. }
  299. return index_val;
  300. }
  301. auto PerformMemberAccess(Context& context, SemIR::LocId loc_id,
  302. SemIR::InstId base_id, SemIR::NameId name_id)
  303. -> SemIR::InstId {
  304. // If the base is a name scope, such as a class or namespace, perform lookup
  305. // into that scope.
  306. if (auto base_const_id = context.constant_values().Get(base_id);
  307. base_const_id.is_constant()) {
  308. llvm::SmallVector<LookupScope> lookup_scopes;
  309. if (context.AppendLookupScopesForConstant(loc_id, base_const_id,
  310. &lookup_scopes)) {
  311. return LookupMemberNameInScope(context, loc_id, base_id, name_id,
  312. base_const_id, lookup_scopes);
  313. }
  314. }
  315. // If the base isn't a scope, it must have a complete type.
  316. auto base_type_id = context.insts().Get(base_id).type_id();
  317. if (!context.TryToCompleteType(base_type_id, [&] {
  318. CARBON_DIAGNOSTIC(IncompleteTypeInMemberAccess, Error,
  319. "member access into object of incomplete type {0}",
  320. TypeOfInstId);
  321. return context.emitter().Build(base_id, IncompleteTypeInMemberAccess,
  322. base_id);
  323. })) {
  324. return SemIR::InstId::BuiltinError;
  325. }
  326. // Materialize a temporary for the base expression if necessary.
  327. base_id = ConvertToValueOrRefExpr(context, base_id);
  328. base_type_id = context.insts().Get(base_id).type_id();
  329. auto base_type_const_id = context.types().GetConstantId(base_type_id);
  330. // Find the scope corresponding to the base type.
  331. llvm::SmallVector<LookupScope> lookup_scopes;
  332. if (!context.AppendLookupScopesForConstant(loc_id, base_type_const_id,
  333. &lookup_scopes)) {
  334. // The base type is not a name scope. Try some fallback options.
  335. if (auto struct_type = context.insts().TryGetAs<SemIR::StructType>(
  336. context.constant_values().GetInstId(base_type_const_id))) {
  337. // TODO: Do we need to optimize this with a lookup table for O(1)?
  338. for (auto [i, field] : llvm::enumerate(
  339. context.struct_type_fields().Get(struct_type->fields_id))) {
  340. if (name_id == field.name_id) {
  341. // TODO: Model this as producing a lookup result, and do instance
  342. // binding separately. Perhaps a struct type should be a name scope.
  343. return context.GetOrAddInst<SemIR::StructAccess>(
  344. loc_id, {.type_id = field.type_id,
  345. .struct_id = base_id,
  346. .index = SemIR::ElementIndex(i)});
  347. }
  348. }
  349. CARBON_DIAGNOSTIC(QualifiedExprNameNotFound, Error,
  350. "type {0} does not have a member `{1}`", TypeOfInstId,
  351. SemIR::NameId);
  352. context.emitter().Emit(loc_id, QualifiedExprNameNotFound, base_id,
  353. name_id);
  354. return SemIR::InstId::BuiltinError;
  355. }
  356. if (base_type_id != SemIR::TypeId::Error) {
  357. CARBON_DIAGNOSTIC(QualifiedExprUnsupported, Error,
  358. "type {0} does not support qualified expressions",
  359. TypeOfInstId);
  360. context.emitter().Emit(loc_id, QualifiedExprUnsupported, base_id);
  361. }
  362. return SemIR::InstId::BuiltinError;
  363. }
  364. // Perform lookup into the base type.
  365. auto member_id = LookupMemberNameInScope(context, loc_id, base_id, name_id,
  366. base_type_const_id, lookup_scopes);
  367. // Perform instance binding if we found an instance member.
  368. member_id = PerformInstanceBinding(context, loc_id, base_id, member_id);
  369. return member_id;
  370. }
  371. auto PerformCompoundMemberAccess(
  372. Context& context, SemIR::LocId loc_id, SemIR::InstId base_id,
  373. SemIR::InstId member_expr_id,
  374. Context::BuildDiagnosticFn missing_impl_diagnoser) -> SemIR::InstId {
  375. auto base_type_id = context.insts().Get(base_id).type_id();
  376. auto base_type_const_id = context.types().GetConstantId(base_type_id);
  377. auto member_id = member_expr_id;
  378. auto member = context.insts().Get(member_id);
  379. // If the member expression names an associated entity, impl lookup is always
  380. // performed using the type of the base expression.
  381. if (auto assoc_type = context.types().TryGetAs<SemIR::AssociatedEntityType>(
  382. member.type_id())) {
  383. member_id =
  384. PerformImplLookup(context, loc_id, base_type_const_id, *assoc_type,
  385. member_id, missing_impl_diagnoser);
  386. } else if (context.insts().Is<SemIR::TupleType>(
  387. context.constant_values().GetInstId(base_type_const_id))) {
  388. return PerformTupleAccess(context, loc_id, base_id, member_expr_id);
  389. }
  390. // Perform instance binding if we found an instance member.
  391. member_id = PerformInstanceBinding(context, loc_id, base_id, member_id);
  392. // If we didn't perform impl lookup or instance binding, that's an error
  393. // because the base expression is not used for anything.
  394. if (member_id == member_expr_id && member.type_id() != SemIR::TypeId::Error) {
  395. CARBON_DIAGNOSTIC(CompoundMemberAccessDoesNotUseBase, Error,
  396. "member name of type {0} in compound member access is "
  397. "not an instance member or an interface member",
  398. TypeOfInstId);
  399. context.emitter().Emit(loc_id, CompoundMemberAccessDoesNotUseBase,
  400. member_id);
  401. }
  402. return member_id;
  403. }
  404. auto PerformTupleAccess(Context& context, SemIR::LocId loc_id,
  405. SemIR::InstId tuple_inst_id,
  406. SemIR::InstId index_inst_id) -> SemIR::InstId {
  407. tuple_inst_id = ConvertToValueOrRefExpr(context, tuple_inst_id);
  408. auto tuple_type_id = context.insts().Get(tuple_inst_id).type_id();
  409. auto tuple_type = context.types().TryGetAs<SemIR::TupleType>(tuple_type_id);
  410. if (!tuple_type) {
  411. CARBON_DIAGNOSTIC(TupleIndexOnANonTupleType, Error,
  412. "type {0} does not support tuple indexing; only "
  413. "tuples can be indexed that way",
  414. TypeOfInstId);
  415. context.emitter().Emit(loc_id, TupleIndexOnANonTupleType, tuple_inst_id);
  416. return SemIR::InstId::BuiltinError;
  417. }
  418. auto diag_non_constant_index = [&] {
  419. // TODO: Decide what to do if the index is a symbolic constant.
  420. CARBON_DIAGNOSTIC(TupleIndexNotConstant, Error,
  421. "tuple index must be a constant");
  422. context.emitter().Emit(loc_id, TupleIndexNotConstant);
  423. return SemIR::InstId::BuiltinError;
  424. };
  425. // Diagnose a non-constant index prior to conversion to IntLiteral, because
  426. // the conversion will fail if the index is not constant.
  427. if (!context.constant_values().Get(index_inst_id).is_template()) {
  428. return diag_non_constant_index();
  429. }
  430. SemIR::TypeId element_type_id = SemIR::TypeId::Error;
  431. auto index_node_id = context.insts().GetLocId(index_inst_id);
  432. index_inst_id = ConvertToValueOfType(
  433. context, index_node_id, index_inst_id,
  434. context.GetBuiltinType(SemIR::BuiltinInstKind::IntLiteralType));
  435. auto index_const_id = context.constant_values().Get(index_inst_id);
  436. if (index_const_id == SemIR::ConstantId::Error) {
  437. return SemIR::InstId::BuiltinError;
  438. } else if (!index_const_id.is_template()) {
  439. return diag_non_constant_index();
  440. }
  441. auto index_literal = context.insts().GetAs<SemIR::IntValue>(
  442. context.constant_values().GetInstId(index_const_id));
  443. auto type_block = context.type_blocks().Get(tuple_type->elements_id);
  444. std::optional<llvm::APInt> index_val = ValidateTupleIndex(
  445. context, loc_id, tuple_inst_id, index_literal, type_block.size());
  446. if (!index_val) {
  447. return SemIR::InstId::BuiltinError;
  448. }
  449. // TODO: Handle the case when `index_val->getZExtValue()` has too many bits.
  450. element_type_id = type_block[index_val->getZExtValue()];
  451. auto tuple_index = SemIR::ElementIndex(index_val->getZExtValue());
  452. return context.GetOrAddInst<SemIR::TupleAccess>(loc_id,
  453. {.type_id = element_type_id,
  454. .tuple_id = tuple_inst_id,
  455. .index = tuple_index});
  456. }
  457. } // namespace Carbon::Check