impl.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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/impl.h"
  5. #include "toolchain/base/kind_switch.h"
  6. #include "toolchain/check/context.h"
  7. #include "toolchain/check/eval.h"
  8. #include "toolchain/check/function.h"
  9. #include "toolchain/check/generic.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/impl.h"
  15. #include "toolchain/sem_ir/inst.h"
  16. #include "toolchain/sem_ir/typed_insts.h"
  17. namespace Carbon::Check {
  18. // Adds the location of the associated function to a diagnostic.
  19. static auto NoteAssociatedFunction(Context& context,
  20. Context::DiagnosticBuilder& builder,
  21. SemIR::FunctionId function_id) -> void {
  22. CARBON_DIAGNOSTIC(ImplAssociatedFunctionHere, Note,
  23. "associated function {0} declared here", SemIR::NameId);
  24. const auto& function = context.functions().Get(function_id);
  25. builder.Note(function.latest_decl_id(), ImplAssociatedFunctionHere,
  26. function.name_id);
  27. }
  28. // Gets the self specific of a generic declaration that is an interface member,
  29. // given a specific for an enclosing generic, plus a type to use as `Self`.
  30. static auto GetSelfSpecificForInterfaceMemberWithSelfType(
  31. Context& context, SemIR::SpecificId enclosing_specific_id,
  32. SemIR::GenericId generic_id, SemIR::TypeId self_type_id)
  33. -> SemIR::SpecificId {
  34. const auto& generic = context.generics().Get(generic_id);
  35. auto bindings = context.inst_blocks().Get(generic.bindings_id);
  36. llvm::SmallVector<SemIR::InstId> arg_ids;
  37. arg_ids.reserve(bindings.size());
  38. // Start with the enclosing arguments.
  39. if (enclosing_specific_id.is_valid()) {
  40. auto enclosing_specific_args_id =
  41. context.specifics().Get(enclosing_specific_id).args_id;
  42. auto enclosing_specific_args =
  43. context.inst_blocks().Get(enclosing_specific_args_id);
  44. arg_ids.assign(enclosing_specific_args.begin(),
  45. enclosing_specific_args.end());
  46. }
  47. // Add the `Self` argument. First find the `Self` binding.
  48. auto self_binding =
  49. context.insts().GetAs<SemIR::BindSymbolicName>(bindings[arg_ids.size()]);
  50. CARBON_CHECK(
  51. context.entity_names().Get(self_binding.entity_name_id).name_id ==
  52. SemIR::NameId::SelfType,
  53. "Expected a Self binding, found {0}", self_binding);
  54. // Create a facet value to be the value of `Self` in the interface.
  55. // This facet value consists of the type `self_type_id` and a witness that the
  56. // type implements `self_binding.type_id`. The witness needs to be symbolic
  57. // since we haven't finished defining the implementation here.
  58. auto type_inst_id = context.types().GetInstId(self_type_id);
  59. // TODO: Make a symbolic interface witness here. For the moment, the witness
  60. // is never used.
  61. auto witness_inst_id = type_inst_id;
  62. auto facet_value_const_id =
  63. TryEvalInst(context, SemIR::InstId::Invalid,
  64. SemIR::FacetValue{.type_id = self_binding.type_id,
  65. .type_inst_id = type_inst_id,
  66. .witness_inst_id = witness_inst_id});
  67. arg_ids.push_back(context.constant_values().GetInstId(facet_value_const_id));
  68. // Take any trailing argument values from the self specific.
  69. // TODO: If these refer to outer arguments, for example in their types, we may
  70. // need to perform extra substitutions here.
  71. auto self_specific_args = context.inst_blocks().Get(
  72. context.specifics().Get(generic.self_specific_id).args_id);
  73. for (auto arg_id : self_specific_args.drop_front(arg_ids.size())) {
  74. arg_ids.push_back(context.constant_values().GetConstantInstId(arg_id));
  75. }
  76. auto args_id = context.inst_blocks().AddCanonical(arg_ids);
  77. return MakeSpecific(context, generic_id, args_id);
  78. }
  79. // Checks that `impl_function_id` is a valid implementation of the function
  80. // described in the interface as `interface_function_id`. Returns the value to
  81. // put into the corresponding slot in the witness table, which can be
  82. // `BuiltinErrorInst` if the function is not usable.
  83. static auto CheckAssociatedFunctionImplementation(
  84. Context& context, SemIR::FunctionType interface_function_type,
  85. SemIR::InstId impl_decl_id, SemIR::TypeId self_type_id) -> SemIR::InstId {
  86. auto impl_function_decl =
  87. context.insts().TryGetAs<SemIR::FunctionDecl>(impl_decl_id);
  88. if (!impl_function_decl) {
  89. CARBON_DIAGNOSTIC(ImplFunctionWithNonFunction, Error,
  90. "associated function {0} implemented by non-function",
  91. SemIR::NameId);
  92. auto builder = context.emitter().Build(
  93. impl_decl_id, ImplFunctionWithNonFunction,
  94. context.functions().Get(interface_function_type.function_id).name_id);
  95. NoteAssociatedFunction(context, builder,
  96. interface_function_type.function_id);
  97. builder.Emit();
  98. return SemIR::ErrorInst::SingletonInstId;
  99. }
  100. // Map from the specific for the function type to the specific for the
  101. // function signature. The function signature may have additional generic
  102. // parameters.
  103. auto interface_function_specific_id =
  104. GetSelfSpecificForInterfaceMemberWithSelfType(
  105. context, interface_function_type.specific_id,
  106. context.functions()
  107. .Get(interface_function_type.function_id)
  108. .generic_id,
  109. self_type_id);
  110. // TODO: This should be a semantic check rather than a syntactic one. The
  111. // functions should be allowed to have different signatures as long as we can
  112. // synthesize a suitable thunk.
  113. if (!CheckFunctionTypeMatches(
  114. context, context.functions().Get(impl_function_decl->function_id),
  115. context.functions().Get(interface_function_type.function_id),
  116. interface_function_specific_id,
  117. /*check_syntax=*/false)) {
  118. return SemIR::ErrorInst::SingletonInstId;
  119. }
  120. return impl_decl_id;
  121. }
  122. // Builds a witness that the specified impl implements the given interface.
  123. static auto BuildInterfaceWitness(
  124. Context& context, const SemIR::Impl& impl, SemIR::TypeId facet_type_id,
  125. SemIR::FacetTypeInfo::ImplsConstraint interface_type,
  126. llvm::SmallVectorImpl<SemIR::InstId>& used_decl_ids) -> SemIR::InstId {
  127. const auto& interface = context.interfaces().Get(interface_type.interface_id);
  128. // TODO: This is going to try and define all the interfaces for this facet
  129. // type, and so once we support impl of a facet type with more than one
  130. // interface, it might give the wrong name in the diagnostic.
  131. if (!context.TryToDefineType(facet_type_id, [&] {
  132. CARBON_DIAGNOSTIC(ImplOfUndefinedInterface, Error,
  133. "implementation of undefined interface {0}",
  134. SemIR::NameId);
  135. return context.emitter().Build(
  136. impl.definition_id, ImplOfUndefinedInterface, interface.name_id);
  137. })) {
  138. return SemIR::ErrorInst::SingletonInstId;
  139. }
  140. auto& impl_scope = context.name_scopes().Get(impl.scope_id);
  141. auto self_type_id = context.GetTypeIdForTypeInst(impl.self_id);
  142. llvm::SmallVector<SemIR::InstId> table;
  143. auto assoc_entities =
  144. context.inst_blocks().Get(interface.associated_entities_id);
  145. table.reserve(assoc_entities.size());
  146. for (auto decl_id : assoc_entities) {
  147. LoadImportRef(context, decl_id);
  148. decl_id =
  149. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  150. context.sem_ir(), interface_type.specific_id, decl_id));
  151. CARBON_CHECK(decl_id.is_valid(), "Non-constant associated entity");
  152. auto decl = context.insts().Get(decl_id);
  153. CARBON_KIND_SWITCH(decl) {
  154. case CARBON_KIND(SemIR::StructValue struct_value): {
  155. if (struct_value.type_id == SemIR::ErrorInst::SingletonTypeId) {
  156. return SemIR::ErrorInst::SingletonInstId;
  157. }
  158. auto type_inst = context.types().GetAsInst(struct_value.type_id);
  159. auto fn_type = type_inst.TryAs<SemIR::FunctionType>();
  160. if (!fn_type) {
  161. CARBON_FATAL("Unexpected type: {0}", type_inst);
  162. }
  163. auto& fn = context.functions().Get(fn_type->function_id);
  164. auto [impl_decl_id, _] = context.LookupNameInExactScope(
  165. decl_id, fn.name_id, impl.scope_id, impl_scope);
  166. if (impl_decl_id.is_valid()) {
  167. used_decl_ids.push_back(impl_decl_id);
  168. table.push_back(CheckAssociatedFunctionImplementation(
  169. context, *fn_type, impl_decl_id, self_type_id));
  170. } else {
  171. CARBON_DIAGNOSTIC(
  172. ImplMissingFunction, Error,
  173. "missing implementation of {0} in impl of interface {1}",
  174. SemIR::NameId, SemIR::NameId);
  175. auto builder =
  176. context.emitter().Build(impl.definition_id, ImplMissingFunction,
  177. fn.name_id, interface.name_id);
  178. NoteAssociatedFunction(context, builder, fn_type->function_id);
  179. builder.Emit();
  180. table.push_back(SemIR::ErrorInst::SingletonInstId);
  181. }
  182. break;
  183. }
  184. case CARBON_KIND(SemIR::AssociatedConstantDecl associated): {
  185. // TODO: Check we have a value for this constant in the constraint.
  186. context.TODO(
  187. impl.definition_id,
  188. "impl of interface with associated constant " +
  189. context.names().GetFormatted(associated.name_id).str());
  190. return SemIR::ErrorInst::SingletonInstId;
  191. }
  192. default:
  193. CARBON_CHECK(decl_id == SemIR::ErrorInst::SingletonInstId,
  194. "Unexpected kind of associated entity {0}", decl);
  195. table.push_back(SemIR::ErrorInst::SingletonInstId);
  196. break;
  197. }
  198. }
  199. auto table_id = context.inst_blocks().Add(table);
  200. return context.AddInst<SemIR::InterfaceWitness>(
  201. context.insts().GetLocId(impl.definition_id),
  202. {.type_id = context.GetBuiltinType(SemIR::BuiltinInstKind::WitnessType),
  203. .elements_id = table_id});
  204. }
  205. auto BuildImplWitness(Context& context, SemIR::ImplId impl_id)
  206. -> SemIR::InstId {
  207. auto& impl = context.impls().Get(impl_id);
  208. CARBON_CHECK(impl.is_being_defined());
  209. auto facet_type_id = context.GetTypeIdForTypeInst(impl.constraint_id);
  210. if (facet_type_id == SemIR::ErrorInst::SingletonTypeId) {
  211. return SemIR::ErrorInst::SingletonInstId;
  212. }
  213. auto facet_type = context.types().TryGetAs<SemIR::FacetType>(facet_type_id);
  214. if (!facet_type) {
  215. CARBON_DIAGNOSTIC(ImplAsNonFacetType, Error, "impl as non-facet-type");
  216. context.emitter().Emit(impl.definition_id, ImplAsNonFacetType);
  217. return SemIR::ErrorInst::SingletonInstId;
  218. }
  219. const SemIR::FacetTypeInfo& facet_type_info =
  220. context.facet_types().Get(facet_type->facet_type_id);
  221. auto interface = facet_type_info.TryAsSingleInterface();
  222. if (!interface) {
  223. context.TODO(impl.definition_id, "impl as not 1 interface");
  224. return SemIR::ErrorInst::SingletonInstId;
  225. }
  226. llvm::SmallVector<SemIR::InstId> used_decl_ids;
  227. auto witness_id = BuildInterfaceWitness(context, impl, facet_type_id,
  228. *interface, used_decl_ids);
  229. // TODO: Diagnose if any declarations in the impl are not in used_decl_ids.
  230. return witness_id;
  231. }
  232. } // namespace Carbon::Check