impl.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 "
  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. // `BuiltinError` 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::BuiltinError;
  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::BuiltinError;
  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 interface_type_id,
  113. SemIR::InterfaceType interface_type,
  114. llvm::SmallVectorImpl<SemIR::InstId>& used_decl_ids) -> SemIR::InstId {
  115. const auto& interface = context.interfaces().Get(interface_type.interface_id);
  116. if (!context.TryToDefineType(interface_type_id, [&] {
  117. CARBON_DIAGNOSTIC(ImplOfUndefinedInterface, Error,
  118. "Implementation of undefined interface {0}.",
  119. SemIR::NameId);
  120. return context.emitter().Build(
  121. impl.definition_id, ImplOfUndefinedInterface, interface.name_id);
  122. })) {
  123. return SemIR::InstId::BuiltinError;
  124. }
  125. auto& impl_scope = context.name_scopes().Get(impl.scope_id);
  126. llvm::SmallVector<SemIR::InstId> table;
  127. auto assoc_entities =
  128. context.inst_blocks().Get(interface.associated_entities_id);
  129. table.reserve(assoc_entities.size());
  130. for (auto decl_id : assoc_entities) {
  131. LoadImportRef(context, decl_id);
  132. decl_id =
  133. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  134. context.sem_ir(), interface_type.specific_id, decl_id));
  135. CARBON_CHECK(decl_id.is_valid()) << "Non-constant associated entity";
  136. auto decl = context.insts().Get(decl_id);
  137. CARBON_KIND_SWITCH(decl) {
  138. case CARBON_KIND(SemIR::StructValue struct_value): {
  139. if (struct_value.type_id == SemIR::TypeId::Error) {
  140. return SemIR::InstId::BuiltinError;
  141. }
  142. auto type_inst = context.types().GetAsInst(struct_value.type_id);
  143. auto fn_type = type_inst.TryAs<SemIR::FunctionType>();
  144. if (!fn_type) {
  145. CARBON_FATAL() << "Unexpected type: " << type_inst;
  146. }
  147. auto& fn = context.functions().Get(fn_type->function_id);
  148. auto impl_decl_id = context.LookupNameInExactScope(
  149. decl_id, fn.name_id, impl.scope_id, impl_scope);
  150. if (impl_decl_id.is_valid()) {
  151. used_decl_ids.push_back(impl_decl_id);
  152. table.push_back(CheckAssociatedFunctionImplementation(
  153. context, *fn_type, impl_decl_id, impl.self_id));
  154. } else {
  155. CARBON_DIAGNOSTIC(
  156. ImplMissingFunction, Error,
  157. "Missing implementation of {0} in impl of interface {1}.",
  158. SemIR::NameId, SemIR::NameId);
  159. auto builder =
  160. context.emitter().Build(impl.definition_id, ImplMissingFunction,
  161. fn.name_id, interface.name_id);
  162. NoteAssociatedFunction(context, builder, fn_type->function_id);
  163. builder.Emit();
  164. table.push_back(SemIR::InstId::BuiltinError);
  165. }
  166. break;
  167. }
  168. case SemIR::AssociatedConstantDecl::Kind:
  169. // TODO: Check we have a value for this constant in the constraint.
  170. context.TODO(impl.definition_id,
  171. "impl of interface with associated constant");
  172. return SemIR::InstId::BuiltinError;
  173. default:
  174. CARBON_CHECK(decl_id == SemIR::InstId::BuiltinError)
  175. << "Unexpected kind of associated entity " << decl;
  176. table.push_back(SemIR::InstId::BuiltinError);
  177. break;
  178. }
  179. }
  180. auto table_id = context.inst_blocks().Add(table);
  181. return context.AddInstReusingLoc<SemIR::InterfaceWitness>(
  182. context.insts().GetLocId(impl.definition_id),
  183. {.type_id = context.GetBuiltinType(SemIR::BuiltinInstKind::WitnessType),
  184. .elements_id = table_id});
  185. }
  186. auto BuildImplWitness(Context& context, SemIR::ImplId impl_id)
  187. -> SemIR::InstId {
  188. auto& impl = context.impls().Get(impl_id);
  189. CARBON_CHECK(impl.is_being_defined());
  190. // TODO: Handle non-interface constraints.
  191. auto interface_type =
  192. context.types().TryGetAs<SemIR::InterfaceType>(impl.constraint_id);
  193. if (!interface_type) {
  194. context.TODO(impl.definition_id, "impl as non-interface");
  195. return SemIR::InstId::BuiltinError;
  196. }
  197. llvm::SmallVector<SemIR::InstId> used_decl_ids;
  198. auto witness_id = BuildInterfaceWitness(context, impl, impl.constraint_id,
  199. *interface_type, used_decl_ids);
  200. // TODO: Diagnose if any declarations in the impl are not in used_decl_ids.
  201. return witness_id;
  202. }
  203. } // namespace Carbon::Check