impl.cpp 10 KB

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