interface.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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/interface.h"
  5. #include <algorithm>
  6. #include <cstddef>
  7. #include "common/concepts.h"
  8. #include "toolchain/check/context.h"
  9. #include "toolchain/check/core_identifier.h"
  10. #include "toolchain/check/eval.h"
  11. #include "toolchain/check/generic.h"
  12. #include "toolchain/check/inst.h"
  13. #include "toolchain/check/merge.h"
  14. #include "toolchain/check/name_lookup.h"
  15. #include "toolchain/check/type.h"
  16. #include "toolchain/sem_ir/entity_with_params_base.h"
  17. #include "toolchain/sem_ir/ids.h"
  18. #include "toolchain/sem_ir/inst.h"
  19. #include "toolchain/sem_ir/typed_insts.h"
  20. namespace Carbon::Check {
  21. auto BuildAssociatedEntity(Context& context, SemIR::InterfaceId interface_id,
  22. SemIR::InstId decl_id) -> SemIR::InstId {
  23. auto& interface_info = context.interfaces().Get(interface_id);
  24. if (!interface_info.is_being_defined()) {
  25. // This should only happen if the interface is erroneously defined more than
  26. // once.
  27. // TODO: Find a way to CHECK this.
  28. return SemIR::ErrorInst::InstId;
  29. }
  30. // This associated entity is being declared as a member of an interface. We
  31. // use the self-specific of the interface-without-self as the AssociatedEntity
  32. // names the externally facing SpecificInterface (without self).
  33. auto interface_without_self_specific_id =
  34. context.generics().GetSelfSpecific(interface_info.generic_id);
  35. // Register this declaration as declaring an associated entity.
  36. auto index = SemIR::ElementIndex(
  37. context.args_type_info_stack().PeekCurrentBlockContents().size());
  38. context.args_type_info_stack().AddInstId(decl_id);
  39. // Name lookup for the declaration's name should name the associated entity,
  40. // not the declaration itself.
  41. auto type_id = GetAssociatedEntityType(context, interface_id,
  42. interface_without_self_specific_id);
  43. return AddInst<SemIR::AssociatedEntity>(
  44. context, SemIR::LocId(decl_id),
  45. {.type_id = type_id, .index = index, .decl_id = decl_id});
  46. }
  47. auto GetSelfSpecificForInterfaceMemberWithSelfType(
  48. Context& context, SemIR::LocId loc_id,
  49. SemIR::SpecificId interface_with_self_specific_id,
  50. SemIR::GenericId generic_id, SemIR::SpecificId enclosing_specific_id)
  51. -> SemIR::SpecificId {
  52. const auto& generic = context.generics().Get(generic_id);
  53. auto self_specific_args = context.inst_blocks().Get(
  54. context.specifics().Get(generic.self_specific_id).args_id);
  55. auto arg_ids = llvm::SmallVector<SemIR::InstId>(context.inst_blocks().Get(
  56. context.specifics().GetArgsOrEmpty(interface_with_self_specific_id)));
  57. // Determine the number of specific arguments that enclose the point where
  58. // this self specific will be used from. In an impl, this will be the number
  59. // of parameters that the impl has.
  60. int num_enclosing_specific_args =
  61. context.inst_blocks()
  62. .Get(context.specifics().GetArgsOrEmpty(enclosing_specific_id))
  63. .size();
  64. // The index of each remaining generic parameter is adjusted to match the
  65. // numbering at the point where the self specific is used.
  66. int index_delta = num_enclosing_specific_args - arg_ids.size();
  67. // Take any trailing argument values from the self specific.
  68. // TODO: If these refer to outer arguments, for example in their types, we may
  69. // need to perform extra substitutions here.
  70. for (auto arg_id : self_specific_args.drop_front(arg_ids.size())) {
  71. auto new_arg_id = context.constant_values().GetConstantInstId(arg_id);
  72. if (index_delta) {
  73. // If this parameter would have a new index in the context described by
  74. // `enclosing_specific_id`, form a new binding with an adjusted index.
  75. auto bind_name = context.insts().GetAs<SemIR::SymbolicBinding>(
  76. context.constant_values().GetConstantInstId(arg_id));
  77. auto entity_name = context.entity_names().Get(bind_name.entity_name_id);
  78. entity_name.bind_index_value += index_delta;
  79. CARBON_CHECK(entity_name.bind_index_value >= 0);
  80. bind_name.entity_name_id =
  81. context.entity_names().AddCanonical(entity_name);
  82. new_arg_id =
  83. context.constant_values().GetInstId(TryEvalInst(context, bind_name));
  84. }
  85. arg_ids.push_back(new_arg_id);
  86. }
  87. return MakeSpecific(context, loc_id, generic_id, arg_ids);
  88. }
  89. auto GetTypeForSpecificAssociatedEntity(
  90. Context& context, SemIR::SpecificId interface_with_self_specific_id,
  91. SemIR::InstId decl_id) -> SemIR::TypeId {
  92. auto decl_constant_inst_id =
  93. context.constant_values().GetConstantInstId(decl_id);
  94. if (decl_constant_inst_id == SemIR::ErrorInst::InstId) {
  95. return SemIR::ErrorInst::TypeId;
  96. }
  97. auto decl = context.insts().Get(decl_constant_inst_id);
  98. if (auto assoc_const = decl.TryAs<SemIR::AssociatedConstantDecl>()) {
  99. return SemIR::GetTypeOfInstInSpecific(
  100. context.sem_ir(), interface_with_self_specific_id, decl_id);
  101. }
  102. if (auto fn = context.types().TryGetAs<SemIR::FunctionType>(decl.type_id())) {
  103. // Form the type of the function within the interface, and attach the `Self`
  104. // type.
  105. auto interface_fn_type_id = SemIR::GetTypeOfInstInSpecific(
  106. context.sem_ir(), interface_with_self_specific_id, decl_id);
  107. auto self_facet_id = context.inst_blocks()
  108. .Get(context.specifics().GetArgsOrEmpty(
  109. interface_with_self_specific_id))
  110. .back();
  111. return GetFunctionTypeWithSelfType(
  112. context, context.types().GetTypeInstId(interface_fn_type_id),
  113. self_facet_id);
  114. }
  115. CARBON_FATAL("Unexpected kind for associated constant {0}", decl);
  116. }
  117. auto AddSelfSymbolicBindingToScope(Context& context,
  118. SemIR::LocId definition_loc_id,
  119. SemIR::TypeId type_id,
  120. SemIR::NameScopeId scope_id,
  121. bool is_template) -> SemIR::InstId {
  122. auto entity_name_id = context.entity_names().AddSymbolicBindingName(
  123. SemIR::NameId::SelfType, scope_id,
  124. context.scope_stack().AddCompileTimeBinding(), is_template,
  125. /*is_unused=*/false);
  126. // Because there is no equivalent non-symbolic value, we use `None` as
  127. // the `value_id` on the `SymbolicBinding`.
  128. auto self_param_inst_id =
  129. AddInst<SemIR::SymbolicBinding>(context, definition_loc_id,
  130. {.type_id = type_id,
  131. .entity_name_id = entity_name_id,
  132. .value_id = SemIR::InstId::None});
  133. context.name_scopes().AddRequiredName(scope_id, SemIR::NameId::SelfType,
  134. self_param_inst_id);
  135. return self_param_inst_id;
  136. }
  137. template <typename EntityT>
  138. requires std::same_as<EntityT, SemIR::Interface>
  139. static auto TryGetEntity(Context& context, SemIR::Inst inst)
  140. -> const SemIR::EntityWithParamsBase* {
  141. if (auto decl = inst.TryAs<SemIR::InterfaceDecl>()) {
  142. return &context.interfaces().Get(decl->interface_id);
  143. } else {
  144. return nullptr;
  145. }
  146. }
  147. template <typename EntityT>
  148. requires std::same_as<EntityT, SemIR::NamedConstraint>
  149. static auto TryGetEntity(Context& context, SemIR::Inst inst)
  150. -> const SemIR::EntityWithParamsBase* {
  151. if (auto decl = inst.TryAs<SemIR::NamedConstraintDecl>()) {
  152. return &context.named_constraints().Get(decl->named_constraint_id);
  153. } else {
  154. return nullptr;
  155. }
  156. }
  157. template <typename EntityT>
  158. requires std::same_as<EntityT, SemIR::Interface>
  159. static constexpr auto DeclTokenKind() -> Lex::TokenKind {
  160. return Lex::TokenKind::Interface;
  161. }
  162. template <typename EntityT>
  163. requires std::same_as<EntityT, SemIR::NamedConstraint>
  164. static constexpr auto DeclTokenKind() -> Lex::TokenKind {
  165. return Lex::TokenKind::Constraint;
  166. }
  167. template <typename EntityT>
  168. requires SameAsOneOf<EntityT, SemIR::Interface, SemIR::NamedConstraint>
  169. auto TryGetExistingDecl(Context& context, const NameComponent& name,
  170. SemIR::ScopeLookupResult lookup_result,
  171. const EntityT& entity, bool is_definition)
  172. -> std::optional<SemIR::Inst> {
  173. if (lookup_result.is_poisoned()) {
  174. // This is a declaration of a poisoned name.
  175. DiagnosePoisonedName(context, name.name_id,
  176. lookup_result.poisoning_loc_id(), name.name_loc_id);
  177. return std::nullopt;
  178. }
  179. if (!lookup_result.is_found()) {
  180. return std::nullopt;
  181. }
  182. SemIR::InstId existing_id = lookup_result.target_inst_id();
  183. SemIR::Inst existing_decl_inst = context.insts().Get(existing_id);
  184. const auto* existing_decl_entity =
  185. TryGetEntity<EntityT>(context, existing_decl_inst);
  186. if (!existing_decl_entity) {
  187. // This is a redeclaration with a different entity kind.
  188. DiagnoseDuplicateName(context, name.name_id, name.name_loc_id,
  189. SemIR::LocId(existing_id));
  190. return std::nullopt;
  191. }
  192. if (!CheckRedeclParamsMatch(
  193. context,
  194. DeclParams(SemIR::LocId(entity.latest_decl_id()),
  195. name.first_param_node_id, name.last_param_node_id,
  196. name.implicit_param_patterns_id, name.param_patterns_id),
  197. DeclParams(*existing_decl_entity))) {
  198. // Mismatch is diagnosed already if found.
  199. return std::nullopt;
  200. }
  201. // TODO: This should be refactored a little, particularly for
  202. // prev_import_ir_id. See similar logic for classes and functions, which
  203. // might also be refactored to merge.
  204. DiagnoseIfInvalidRedecl(
  205. context, DeclTokenKind<EntityT>(), existing_decl_entity->name_id,
  206. RedeclInfo(entity, SemIR::LocId(entity.latest_decl_id()), is_definition),
  207. RedeclInfo(*existing_decl_entity,
  208. SemIR::LocId(existing_decl_entity->latest_decl_id()),
  209. existing_decl_entity->has_definition_started()),
  210. /*prev_import_ir_id=*/SemIR::ImportIRId::None);
  211. if (is_definition && existing_decl_entity->has_definition_started()) {
  212. // DiagnoseIfInvalidRedecl would diagnose an error in this case, since we'd
  213. // have two definitions. Given the declaration parts of the definitions
  214. // match, we would be able to use the prior declaration for error recovery,
  215. // except that having two definitions causes larger problems for generics.
  216. // All interfaces (and named constraints) are generic with an implicit Self
  217. // compile time binding.
  218. return std::nullopt;
  219. }
  220. // This is a matching redeclaration of an existing entity of the same type.
  221. return existing_decl_inst;
  222. }
  223. template auto TryGetExistingDecl(Context& context, const NameComponent& name,
  224. SemIR::ScopeLookupResult lookup_result,
  225. const SemIR::Interface& entity,
  226. bool is_definition)
  227. -> std::optional<SemIR::Inst>;
  228. template auto TryGetExistingDecl(Context& context, const NameComponent& name,
  229. SemIR::ScopeLookupResult lookup_result,
  230. const SemIR::NamedConstraint& entity,
  231. bool is_definition)
  232. -> std::optional<SemIR::Inst>;
  233. } // namespace Carbon::Check