member_access.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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/import_ref.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 lookup scope corresponding to base_id, or nullopt if not a scope.
  19. // On invalid scopes, prints a diagnostic and still returns the scope.
  20. static auto GetAsLookupScope(Context& context, SemIR::LocId loc_id,
  21. SemIR::ConstantId base_const_id)
  22. -> std::optional<LookupScope> {
  23. auto base_id = context.constant_values().GetInstId(base_const_id);
  24. auto base = context.insts().Get(base_id);
  25. if (auto base_as_namespace = base.TryAs<SemIR::Namespace>()) {
  26. return LookupScope{.name_scope_id = base_as_namespace->name_scope_id,
  27. .specific_id = SemIR::SpecificId::Invalid};
  28. }
  29. // TODO: Consider refactoring the near-identical class and interface support
  30. // below.
  31. if (auto base_as_class = base.TryAs<SemIR::ClassType>()) {
  32. context.TryToDefineType(
  33. context.GetTypeIdForTypeConstant(base_const_id), [&] {
  34. CARBON_DIAGNOSTIC(QualifiedExprInIncompleteClassScope, Error,
  35. "Member access into incomplete class `{0}`.",
  36. std::string);
  37. return context.emitter().Build(
  38. loc_id, QualifiedExprInIncompleteClassScope,
  39. context.sem_ir().StringifyType(base_const_id));
  40. });
  41. auto& class_info = context.classes().Get(base_as_class->class_id);
  42. return LookupScope{.name_scope_id = class_info.scope_id,
  43. .specific_id = base_as_class->specific_id};
  44. }
  45. if (auto base_as_interface = base.TryAs<SemIR::InterfaceType>()) {
  46. context.TryToDefineType(
  47. context.GetTypeIdForTypeConstant(base_const_id), [&] {
  48. CARBON_DIAGNOSTIC(QualifiedExprInUndefinedInterfaceScope, Error,
  49. "Member access into undefined interface `{0}`.",
  50. std::string);
  51. return context.emitter().Build(
  52. loc_id, QualifiedExprInUndefinedInterfaceScope,
  53. context.sem_ir().StringifyType(base_const_id));
  54. });
  55. auto& interface_info =
  56. context.interfaces().Get(base_as_interface->interface_id);
  57. return LookupScope{.name_scope_id = interface_info.scope_id,
  58. .specific_id = base_as_interface->specific_id};
  59. }
  60. // TODO: Per the design, if `base_id` is any kind of type, then lookup should
  61. // treat it as a name scope, even if it doesn't have members. For example,
  62. // `(i32*).X` should fail because there's no name `X` in `i32*`, not because
  63. // there's no name `X` in `type`.
  64. return std::nullopt;
  65. }
  66. // Returns the index of the specified class element within the class's
  67. // representation.
  68. static auto GetClassElementIndex(Context& context, SemIR::InstId element_id)
  69. -> SemIR::ElementIndex {
  70. auto element_inst = context.insts().Get(element_id);
  71. if (auto field = element_inst.TryAs<SemIR::FieldDecl>()) {
  72. return field->index;
  73. }
  74. if (auto base = element_inst.TryAs<SemIR::BaseDecl>()) {
  75. return base->index;
  76. }
  77. CARBON_FATAL("Unexpected value {0} in class element name", element_inst);
  78. }
  79. // Returns whether `function_id` is an instance method, that is, whether it has
  80. // an implicit `self` parameter.
  81. static auto IsInstanceMethod(const SemIR::File& sem_ir,
  82. SemIR::FunctionId function_id) -> bool {
  83. const auto& function = sem_ir.functions().Get(function_id);
  84. for (auto param_id :
  85. sem_ir.inst_blocks().GetOrEmpty(function.implicit_param_refs_id)) {
  86. auto param =
  87. SemIR::Function::GetParamFromParamRefId(sem_ir, param_id).second;
  88. if (param.name_id == SemIR::NameId::SelfValue) {
  89. return true;
  90. }
  91. }
  92. return false;
  93. }
  94. // Returns the FunctionId of the current function if it exists.
  95. static auto GetCurrentFunction(Context& context)
  96. -> std::optional<SemIR::FunctionId> {
  97. if (context.return_scope_stack().empty()) {
  98. return std::nullopt;
  99. }
  100. return context.insts()
  101. .GetAs<SemIR::FunctionDecl>(context.return_scope_stack().back().decl_id)
  102. .function_id;
  103. }
  104. // Returns the highest allowed access. For example, if this returns `Protected`
  105. // then only `Public` and `Protected` accesses are allowed--not `Private`.
  106. static auto GetHighestAllowedAccess(Context& context, SemIRLoc loc,
  107. SemIR::ConstantId name_scope_const_id)
  108. -> SemIR::AccessKind {
  109. // TODO: Maybe use LookupUnqualifiedName for `Self` to support things like
  110. // `var x: Self.ParentProtectedType`?
  111. auto current_function = GetCurrentFunction(context);
  112. // If `current_function` is a `nullopt` then we're accessing from a global
  113. // variable.
  114. if (!current_function) {
  115. return SemIR::AccessKind::Public;
  116. }
  117. auto scope_id = context.functions().Get(*current_function).parent_scope_id;
  118. if (!scope_id.is_valid()) {
  119. return SemIR::AccessKind::Public;
  120. }
  121. auto scope = context.name_scopes().Get(scope_id);
  122. // Lookup the inst for `Self` in the parent scope of the current function.
  123. auto [self_type_inst_id, _] = context.LookupNameInExactScope(
  124. loc, SemIR::NameId::SelfType, scope_id, scope);
  125. if (!self_type_inst_id.is_valid()) {
  126. return SemIR::AccessKind::Public;
  127. }
  128. // TODO: Support other types for `Self`.
  129. auto self_class_type =
  130. context.insts().TryGetAs<SemIR::ClassType>(self_type_inst_id);
  131. if (!self_class_type) {
  132. return SemIR::AccessKind::Public;
  133. }
  134. auto self_class_info = context.classes().Get(self_class_type->class_id);
  135. // TODO: Support other types.
  136. if (auto class_type = context.insts().TryGetAs<SemIR::ClassType>(
  137. context.constant_values().GetInstId(name_scope_const_id))) {
  138. auto class_info = context.classes().Get(class_type->class_id);
  139. if (self_class_info.self_type_id == class_info.self_type_id) {
  140. return SemIR::AccessKind::Private;
  141. }
  142. // If the `type_id` of `Self` does not match with the one we're currently
  143. // accessing, try checking if this class is of the parent type of `Self`.
  144. if (auto base_decl = context.insts().TryGetAsIfValid<SemIR::BaseDecl>(
  145. self_class_info.base_id)) {
  146. if (base_decl->base_type_id == class_info.self_type_id) {
  147. return SemIR::AccessKind::Protected;
  148. }
  149. } else if (auto adapt_decl =
  150. context.insts().TryGetAsIfValid<SemIR::AdaptDecl>(
  151. self_class_info.adapt_id)) {
  152. if (adapt_decl->adapted_type_id == class_info.self_type_id) {
  153. return SemIR::AccessKind::Protected;
  154. }
  155. }
  156. }
  157. return SemIR::AccessKind::Public;
  158. }
  159. // Returns whether `scope` is a scope for which impl lookup should be performed
  160. // if we find an associated entity.
  161. static auto ScopeNeedsImplLookup(Context& context, LookupScope scope) -> bool {
  162. auto [_, inst] = context.name_scopes().GetInstIfValid(scope.name_scope_id);
  163. if (!inst) {
  164. return false;
  165. }
  166. if (inst->Is<SemIR::InterfaceDecl>()) {
  167. // Don't perform impl lookup if an associated entity is named as a member of
  168. // a facet type.
  169. return false;
  170. }
  171. if (inst->Is<SemIR::Namespace>()) {
  172. // Don't perform impl lookup if an associated entity is named as a namespace
  173. // member.
  174. // TODO: This case is not yet listed in the design.
  175. return false;
  176. }
  177. // Any other kind of scope is assumed to be a type that implements the
  178. // interface containing the associated entity, and impl lookup is performed.
  179. return true;
  180. }
  181. // Given a type and an interface, searches for an impl that describes how that
  182. // type implements that interface, and returns the corresponding witness.
  183. // Returns an invalid InstId if no matching impl is found.
  184. static auto LookupInterfaceWitness(Context& context,
  185. SemIR::ConstantId type_const_id,
  186. SemIR::TypeId interface_type_id)
  187. -> SemIR::InstId {
  188. // TODO: Add a better impl lookup system. At the very least, we should only be
  189. // considering impls that are for the same interface we're querying. We can
  190. // also skip impls that mention any types that aren't part of our impl query.
  191. for (const auto& impl : context.impls().array_ref()) {
  192. if (!context.constant_values().AreEqualAcrossDeclarations(
  193. context.types().GetConstantId(impl.self_id), type_const_id)) {
  194. continue;
  195. }
  196. if (!context.types().AreEqualAcrossDeclarations(impl.constraint_id,
  197. interface_type_id)) {
  198. // TODO: An impl of a constraint type should be treated as implementing
  199. // the constraint's interfaces.
  200. continue;
  201. }
  202. if (!impl.witness_id.is_valid()) {
  203. // TODO: Diagnose if the impl isn't defined yet?
  204. return SemIR::InstId::Invalid;
  205. }
  206. LoadImportRef(context, impl.witness_id);
  207. return impl.witness_id;
  208. }
  209. return SemIR::InstId::Invalid;
  210. }
  211. // Performs impl lookup for a member name expression. This finds the relevant
  212. // impl witness and extracts the corresponding impl member.
  213. static auto PerformImplLookup(
  214. Context& context, SemIR::LocId loc_id, SemIR::ConstantId type_const_id,
  215. SemIR::AssociatedEntityType assoc_type, SemIR::InstId member_id,
  216. std::optional<Context::BuildDiagnosticFn> missing_impl_diagnoser)
  217. -> SemIR::InstId {
  218. auto interface_type =
  219. context.types().GetAs<SemIR::InterfaceType>(assoc_type.interface_type_id);
  220. auto& interface = context.interfaces().Get(interface_type.interface_id);
  221. auto witness_id = LookupInterfaceWitness(context, type_const_id,
  222. assoc_type.interface_type_id);
  223. if (!witness_id.is_valid()) {
  224. if (missing_impl_diagnoser) {
  225. CARBON_DIAGNOSTIC(MissingImplInMemberAccessNote, Note,
  226. "Type `{1}` does not implement interface `{0}`.",
  227. SemIR::NameId, SemIR::TypeId);
  228. (*missing_impl_diagnoser)()
  229. .Note(loc_id, MissingImplInMemberAccessNote, interface.name_id,
  230. context.GetTypeIdForTypeConstant(type_const_id))
  231. .Emit();
  232. } else {
  233. CARBON_DIAGNOSTIC(MissingImplInMemberAccess, Error,
  234. "Cannot access member of interface `{0}` in type `{1}` "
  235. "that does not implement that interface.",
  236. SemIR::NameId, SemIR::TypeId);
  237. context.emitter().Emit(loc_id, MissingImplInMemberAccess,
  238. interface.name_id,
  239. context.GetTypeIdForTypeConstant(type_const_id));
  240. }
  241. return SemIR::InstId::BuiltinError;
  242. }
  243. auto member_value_id = context.constant_values().GetConstantInstId(member_id);
  244. if (!member_value_id.is_valid()) {
  245. if (member_value_id != SemIR::InstId::BuiltinError) {
  246. context.TODO(member_id, "non-constant associated entity");
  247. }
  248. return SemIR::InstId::BuiltinError;
  249. }
  250. auto assoc_entity =
  251. context.insts().TryGetAs<SemIR::AssociatedEntity>(member_value_id);
  252. if (!assoc_entity) {
  253. context.TODO(member_id, "unexpected value for associated entity");
  254. return SemIR::InstId::BuiltinError;
  255. }
  256. // TODO: This produces the type of the associated entity with no value for
  257. // `Self`. The type `Self` might appear in the type of an associated constant,
  258. // and if so, we'll need to substitute it here somehow.
  259. auto subst_type_id = SemIR::GetTypeInSpecific(
  260. context.sem_ir(), interface_type.specific_id, assoc_type.entity_type_id);
  261. return context.AddInst<SemIR::InterfaceWitnessAccess>(
  262. loc_id, {.type_id = subst_type_id,
  263. .witness_id = witness_id,
  264. .index = assoc_entity->index});
  265. }
  266. // Performs a member name lookup into the specified scope, including performing
  267. // impl lookup if necessary. If the scope is invalid, assume an error has
  268. // already been diagnosed, and return BuiltinError.
  269. static auto LookupMemberNameInScope(Context& context, SemIR::LocId loc_id,
  270. SemIR::InstId /*base_id*/,
  271. SemIR::NameId name_id,
  272. SemIR::ConstantId name_scope_const_id,
  273. LookupScope lookup_scope) -> SemIR::InstId {
  274. LookupResult result = {.specific_id = SemIR::SpecificId::Invalid,
  275. .inst_id = SemIR::InstId::BuiltinError};
  276. if (lookup_scope.name_scope_id.is_valid()) {
  277. AccessInfo access_info = {
  278. .constant_id = name_scope_const_id,
  279. .highest_allowed_access =
  280. GetHighestAllowedAccess(context, loc_id, name_scope_const_id),
  281. };
  282. result = context.LookupQualifiedName(loc_id, name_id, lookup_scope,
  283. /*required=*/true, access_info);
  284. if (!result.inst_id.is_valid()) {
  285. return SemIR::InstId::BuiltinError;
  286. }
  287. }
  288. // TODO: This duplicates the work that HandleNameAsExpr does. Factor this out.
  289. auto inst = context.insts().Get(result.inst_id);
  290. auto type_id = SemIR::GetTypeInSpecific(context.sem_ir(), result.specific_id,
  291. inst.type_id());
  292. CARBON_CHECK(type_id.is_valid(), "Missing type for member {0}", inst);
  293. // If the named entity has a constant value that depends on its specific,
  294. // store the specific too.
  295. if (result.specific_id.is_valid() &&
  296. context.constant_values().Get(result.inst_id).is_symbolic()) {
  297. result.inst_id = context.AddInst<SemIR::SpecificConstant>(
  298. loc_id, {.type_id = type_id,
  299. .inst_id = result.inst_id,
  300. .specific_id = result.specific_id});
  301. }
  302. // TODO: Use a different kind of instruction that also references the
  303. // `base_id` so that `SemIR` consumers can find it.
  304. auto member_id = context.AddInst<SemIR::NameRef>(
  305. loc_id,
  306. {.type_id = type_id, .name_id = name_id, .value_id = result.inst_id});
  307. // If member name lookup finds an associated entity name, and the scope is not
  308. // a facet type, perform impl lookup.
  309. //
  310. // TODO: We need to do this as part of searching extended scopes, because a
  311. // lookup that finds an associated entity and also finds the corresponding
  312. // impl member is not supposed to be treated as ambiguous.
  313. if (auto assoc_type =
  314. context.types().TryGetAs<SemIR::AssociatedEntityType>(type_id)) {
  315. if (ScopeNeedsImplLookup(context, lookup_scope)) {
  316. member_id = PerformImplLookup(context, loc_id, name_scope_const_id,
  317. *assoc_type, member_id, std::nullopt);
  318. }
  319. }
  320. return member_id;
  321. }
  322. // Performs the instance binding step in member access. If the found member is a
  323. // field, forms a class member access. If the found member is an instance
  324. // method, forms a bound method. Otherwise, the member is returned unchanged.
  325. static auto PerformInstanceBinding(Context& context, SemIR::LocId loc_id,
  326. SemIR::InstId base_id,
  327. SemIR::InstId member_id) -> SemIR::InstId {
  328. auto member_type_id = context.insts().Get(member_id).type_id();
  329. CARBON_KIND_SWITCH(context.types().GetAsInst(member_type_id)) {
  330. case CARBON_KIND(SemIR::UnboundElementType unbound_element_type): {
  331. // Convert the base to the type of the element if necessary.
  332. base_id = ConvertToValueOrRefOfType(context, loc_id, base_id,
  333. unbound_element_type.class_type_id);
  334. // Find the specified element, which could be either a field or a base
  335. // class, and build an element access expression.
  336. auto element_id = context.constant_values().GetConstantInstId(member_id);
  337. CARBON_CHECK(element_id.is_valid(),
  338. "Non-constant value {0} of unbound element type",
  339. context.insts().Get(member_id));
  340. auto index = GetClassElementIndex(context, element_id);
  341. auto access_id = context.AddInst<SemIR::ClassElementAccess>(
  342. loc_id, {.type_id = unbound_element_type.element_type_id,
  343. .base_id = base_id,
  344. .index = index});
  345. if (SemIR::GetExprCategory(context.sem_ir(), base_id) ==
  346. SemIR::ExprCategory::Value &&
  347. SemIR::GetExprCategory(context.sem_ir(), access_id) !=
  348. SemIR::ExprCategory::Value) {
  349. // Class element access on a value expression produces an ephemeral
  350. // reference if the class's value representation is a pointer to the
  351. // object representation. Add a value binding in that case so that the
  352. // expression category of the result matches the expression category of
  353. // the base.
  354. access_id = ConvertToValueExpr(context, access_id);
  355. }
  356. return access_id;
  357. }
  358. case CARBON_KIND(SemIR::FunctionType fn_type): {
  359. if (IsInstanceMethod(context.sem_ir(), fn_type.function_id)) {
  360. return context.AddInst<SemIR::BoundMethod>(
  361. loc_id, {.type_id = context.GetBuiltinType(
  362. SemIR::BuiltinInstKind::BoundMethodType),
  363. .object_id = base_id,
  364. .function_id = member_id});
  365. }
  366. [[fallthrough]];
  367. }
  368. default:
  369. // Not an instance member: no instance binding.
  370. return member_id;
  371. }
  372. }
  373. // Validates that the index (required to be an IntLiteral) is valid within the
  374. // tuple size. Returns the index on success, or nullptr on failure.
  375. static auto ValidateTupleIndex(Context& context, SemIR::LocId loc_id,
  376. SemIR::Inst operand_inst,
  377. SemIR::IntLiteral index_inst, int size)
  378. -> const llvm::APInt* {
  379. const auto& index_val = context.ints().Get(index_inst.int_id);
  380. if (index_val.uge(size)) {
  381. CARBON_DIAGNOSTIC(
  382. TupleIndexOutOfBounds, Error,
  383. "Tuple element index `{0}` is past the end of type `{1}`.", TypedInt,
  384. SemIR::TypeId);
  385. context.emitter().Emit(loc_id, TupleIndexOutOfBounds,
  386. {.type = index_inst.type_id, .value = index_val},
  387. operand_inst.type_id());
  388. return nullptr;
  389. }
  390. return &index_val;
  391. }
  392. auto PerformMemberAccess(Context& context, SemIR::LocId loc_id,
  393. SemIR::InstId base_id, SemIR::NameId name_id)
  394. -> SemIR::InstId {
  395. // If the base is a name scope, such as a class or namespace, perform lookup
  396. // into that scope.
  397. if (auto base_const_id = context.constant_values().Get(base_id);
  398. base_const_id.is_constant()) {
  399. if (auto lookup_scope = GetAsLookupScope(context, loc_id, base_const_id)) {
  400. return LookupMemberNameInScope(context, loc_id, base_id, name_id,
  401. base_const_id, *lookup_scope);
  402. }
  403. }
  404. // If the base isn't a scope, it must have a complete type.
  405. auto base_type_id = context.insts().Get(base_id).type_id();
  406. if (!context.TryToCompleteType(base_type_id, [&] {
  407. CARBON_DIAGNOSTIC(IncompleteTypeInMemberAccess, Error,
  408. "Member access into object of incomplete type `{0}`.",
  409. SemIR::TypeId);
  410. return context.emitter().Build(base_id, IncompleteTypeInMemberAccess,
  411. base_type_id);
  412. })) {
  413. return SemIR::InstId::BuiltinError;
  414. }
  415. // Materialize a temporary for the base expression if necessary.
  416. base_id = ConvertToValueOrRefExpr(context, base_id);
  417. base_type_id = context.insts().Get(base_id).type_id();
  418. auto base_type_const_id = context.types().GetConstantId(base_type_id);
  419. // Find the scope corresponding to the base type.
  420. auto lookup_scope = GetAsLookupScope(context, loc_id, base_type_const_id);
  421. if (!lookup_scope) {
  422. // The base type is not a name scope. Try some fallback options.
  423. if (auto struct_type = context.insts().TryGetAs<SemIR::StructType>(
  424. context.constant_values().GetInstId(base_type_const_id))) {
  425. // TODO: Do we need to optimize this with a lookup table for O(1)?
  426. for (auto [i, ref_id] :
  427. llvm::enumerate(context.inst_blocks().Get(struct_type->fields_id))) {
  428. auto field = context.insts().GetAs<SemIR::StructTypeField>(ref_id);
  429. if (name_id == field.name_id) {
  430. // TODO: Model this as producing a lookup result, and do instance
  431. // binding separately. Perhaps a struct type should be a name scope.
  432. return context.AddInst<SemIR::StructAccess>(
  433. loc_id, {.type_id = field.field_type_id,
  434. .struct_id = base_id,
  435. .index = SemIR::ElementIndex(i)});
  436. }
  437. }
  438. CARBON_DIAGNOSTIC(QualifiedExprNameNotFound, Error,
  439. "Type `{0}` does not have a member `{1}`.",
  440. SemIR::TypeId, SemIR::NameId);
  441. context.emitter().Emit(loc_id, QualifiedExprNameNotFound, base_type_id,
  442. name_id);
  443. return SemIR::InstId::BuiltinError;
  444. }
  445. if (base_type_id != SemIR::TypeId::Error) {
  446. CARBON_DIAGNOSTIC(QualifiedExprUnsupported, Error,
  447. "Type `{0}` does not support qualified expressions.",
  448. SemIR::TypeId);
  449. context.emitter().Emit(loc_id, QualifiedExprUnsupported, base_type_id);
  450. }
  451. return SemIR::InstId::BuiltinError;
  452. }
  453. // Perform lookup into the base type.
  454. auto member_id = LookupMemberNameInScope(context, loc_id, base_id, name_id,
  455. base_type_const_id, *lookup_scope);
  456. // Perform instance binding if we found an instance member.
  457. member_id = PerformInstanceBinding(context, loc_id, base_id, member_id);
  458. return member_id;
  459. }
  460. auto PerformCompoundMemberAccess(
  461. Context& context, SemIR::LocId loc_id, SemIR::InstId base_id,
  462. SemIR::InstId member_expr_id,
  463. std::optional<Context::BuildDiagnosticFn> missing_impl_diagnoser)
  464. -> SemIR::InstId {
  465. // Materialize a temporary for the base expression if necessary.
  466. base_id = ConvertToValueOrRefExpr(context, base_id);
  467. auto base_type_id = context.insts().Get(base_id).type_id();
  468. auto base_type_const_id = context.types().GetConstantId(base_type_id);
  469. auto member_id = member_expr_id;
  470. auto member = context.insts().Get(member_id);
  471. // If the member expression names an associated entity, impl lookup is always
  472. // performed using the type of the base expression.
  473. if (auto assoc_type = context.types().TryGetAs<SemIR::AssociatedEntityType>(
  474. member.type_id())) {
  475. member_id =
  476. PerformImplLookup(context, loc_id, base_type_const_id, *assoc_type,
  477. member_id, missing_impl_diagnoser);
  478. } else if (context.insts().Is<SemIR::TupleType>(
  479. context.constant_values().GetInstId(base_type_const_id))) {
  480. return PerformTupleIndex(context, loc_id, base_id, member_expr_id);
  481. }
  482. // Perform instance binding if we found an instance member.
  483. member_id = PerformInstanceBinding(context, loc_id, base_id, member_id);
  484. // If we didn't perform impl lookup or instance binding, that's an error
  485. // because the base expression is not used for anything.
  486. if (member_id == member_expr_id && member.type_id() != SemIR::TypeId::Error) {
  487. CARBON_DIAGNOSTIC(CompoundMemberAccessDoesNotUseBase, Error,
  488. "Member name of type `{0}` in compound member access is "
  489. "not an instance member or an interface member.",
  490. SemIR::TypeId);
  491. context.emitter().Emit(loc_id, CompoundMemberAccessDoesNotUseBase,
  492. member.type_id());
  493. }
  494. return member_id;
  495. }
  496. auto PerformTupleIndex(Context& context, SemIR::LocId loc_id,
  497. SemIR::InstId tuple_inst_id, SemIR::InstId index_inst_id)
  498. -> SemIR::InstId {
  499. tuple_inst_id = ConvertToValueOrRefExpr(context, tuple_inst_id);
  500. auto tuple_inst = context.insts().Get(tuple_inst_id);
  501. auto tuple_type_id = tuple_inst.type_id();
  502. auto tuple_type = context.types().TryGetAs<SemIR::TupleType>(tuple_type_id);
  503. if (!tuple_type) {
  504. CARBON_DIAGNOSTIC(TupleIndexOnANonTupleType, Error,
  505. "Type `{0}` does not support tuple indexing. Only "
  506. "tuples can be indexed that way.",
  507. SemIR::TypeId);
  508. context.emitter().Emit(loc_id, TupleIndexOnANonTupleType, tuple_type_id);
  509. return SemIR::InstId::BuiltinError;
  510. }
  511. SemIR::TypeId element_type_id = SemIR::TypeId::Error;
  512. auto index_node_id = context.insts().GetLocId(index_inst_id);
  513. index_inst_id = ConvertToValueOfType(
  514. context, index_node_id, index_inst_id,
  515. context.GetBuiltinType(SemIR::BuiltinInstKind::IntType));
  516. auto index_const_id = context.constant_values().Get(index_inst_id);
  517. if (index_const_id == SemIR::ConstantId::Error) {
  518. index_inst_id = SemIR::InstId::BuiltinError;
  519. } else if (!index_const_id.is_template()) {
  520. // TODO: Decide what to do if the index is a symbolic constant.
  521. CARBON_DIAGNOSTIC(TupleIndexNotConstant, Error,
  522. "Tuple index must be a constant.");
  523. context.emitter().Emit(loc_id, TupleIndexNotConstant);
  524. index_inst_id = SemIR::InstId::BuiltinError;
  525. } else {
  526. auto index_literal = context.insts().GetAs<SemIR::IntLiteral>(
  527. context.constant_values().GetInstId(index_const_id));
  528. auto type_block = context.type_blocks().Get(tuple_type->elements_id);
  529. if (const auto* index_val = ValidateTupleIndex(
  530. context, loc_id, tuple_inst, index_literal, type_block.size())) {
  531. element_type_id = type_block[index_val->getZExtValue()];
  532. } else {
  533. index_inst_id = SemIR::InstId::BuiltinError;
  534. }
  535. }
  536. return context.AddInst<SemIR::TupleIndex>(loc_id,
  537. {.type_id = element_type_id,
  538. .tuple_id = tuple_inst_id,
  539. .index_id = index_inst_id});
  540. }
  541. } // namespace Carbon::Check