impl.cpp 9.6 KB

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