impl.cpp 9.4 KB

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