impl.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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, SemIRLoc loc, SemIR::SpecificId enclosing_specific_id,
  32. SemIR::GenericId generic_id, SemIR::TypeId self_type_id,
  33. SemIR::InstId witness_inst_id) -> 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`. Note that the witness is incomplete
  57. // since we haven't finished defining the implementation here.
  58. auto type_inst_id = context.types().GetInstId(self_type_id);
  59. auto facet_value_const_id =
  60. TryEvalInst(context, SemIR::InstId::Invalid,
  61. SemIR::FacetValue{.type_id = self_binding.type_id,
  62. .type_inst_id = type_inst_id,
  63. .witness_inst_id = witness_inst_id});
  64. arg_ids.push_back(context.constant_values().GetInstId(facet_value_const_id));
  65. // Take any trailing argument values from the self specific.
  66. // TODO: If these refer to outer arguments, for example in their types, we may
  67. // need to perform extra substitutions here.
  68. auto self_specific_args = context.inst_blocks().Get(
  69. context.specifics().Get(generic.self_specific_id).args_id);
  70. for (auto arg_id : self_specific_args.drop_front(arg_ids.size())) {
  71. arg_ids.push_back(context.constant_values().GetConstantInstId(arg_id));
  72. }
  73. auto args_id = context.inst_blocks().AddCanonical(arg_ids);
  74. return MakeSpecific(context, loc, generic_id, args_id);
  75. }
  76. // Checks that `impl_function_id` is a valid implementation of the function
  77. // described in the interface as `interface_function_id`. Returns the value to
  78. // put into the corresponding slot in the witness table, which can be
  79. // `BuiltinErrorInst` if the function is not usable.
  80. static auto CheckAssociatedFunctionImplementation(
  81. Context& context, SemIR::FunctionType interface_function_type,
  82. SemIR::InstId impl_decl_id, SemIR::TypeId self_type_id,
  83. SemIR::InstId witness_inst_id) -> SemIR::InstId {
  84. auto impl_function_decl =
  85. context.insts().TryGetAs<SemIR::FunctionDecl>(impl_decl_id);
  86. if (!impl_function_decl) {
  87. CARBON_DIAGNOSTIC(ImplFunctionWithNonFunction, Error,
  88. "associated function {0} implemented by non-function",
  89. SemIR::NameId);
  90. auto builder = context.emitter().Build(
  91. impl_decl_id, ImplFunctionWithNonFunction,
  92. context.functions().Get(interface_function_type.function_id).name_id);
  93. NoteAssociatedFunction(context, builder,
  94. interface_function_type.function_id);
  95. builder.Emit();
  96. return SemIR::ErrorInst::SingletonInstId;
  97. }
  98. // Map from the specific for the function type to the specific for the
  99. // function signature. The function signature may have additional generic
  100. // parameters.
  101. auto interface_function_specific_id =
  102. GetSelfSpecificForInterfaceMemberWithSelfType(
  103. context, impl_decl_id, interface_function_type.specific_id,
  104. context.functions()
  105. .Get(interface_function_type.function_id)
  106. .generic_id,
  107. self_type_id, witness_inst_id);
  108. // TODO: This should be a semantic check rather than a syntactic one. The
  109. // functions should be allowed to have different signatures as long as we can
  110. // synthesize a suitable thunk.
  111. if (!CheckFunctionTypeMatches(
  112. context, context.functions().Get(impl_function_decl->function_id),
  113. context.functions().Get(interface_function_type.function_id),
  114. interface_function_specific_id,
  115. /*check_syntax=*/false)) {
  116. return SemIR::ErrorInst::SingletonInstId;
  117. }
  118. return impl_decl_id;
  119. }
  120. // Builds an initial empty witness.
  121. auto ImplWitnessForDeclaration(Context& context, const SemIR::Impl& impl)
  122. -> SemIR::InstId {
  123. CARBON_CHECK(!impl.has_definition_started());
  124. auto facet_type_id = context.GetTypeIdForTypeInst(impl.constraint_id);
  125. if (facet_type_id == SemIR::ErrorInst::SingletonTypeId) {
  126. return SemIR::ErrorInst::SingletonInstId;
  127. }
  128. auto facet_type = context.types().TryGetAs<SemIR::FacetType>(facet_type_id);
  129. if (!facet_type) {
  130. CARBON_DIAGNOSTIC(ImplAsNonFacetType, Error, "impl as non-facet type {0}",
  131. InstIdAsType);
  132. context.emitter().Emit(impl.latest_decl_id(), ImplAsNonFacetType,
  133. impl.constraint_id);
  134. return SemIR::ErrorInst::SingletonInstId;
  135. }
  136. const SemIR::FacetTypeInfo& facet_type_info =
  137. context.facet_types().Get(facet_type->facet_type_id);
  138. auto interface_type = facet_type_info.TryAsSingleInterface();
  139. if (!interface_type) {
  140. context.TODO(impl.latest_decl_id(), "impl as not 1 interface");
  141. return SemIR::ErrorInst::SingletonInstId;
  142. }
  143. const auto& interface =
  144. context.interfaces().Get(interface_type->interface_id);
  145. // TODO: This is going to try and define all the interfaces for this facet
  146. // type, and so once we support impl of a facet type with more than one
  147. // interface, it might give the wrong name in the diagnostic.
  148. if (!context.RequireDefinedType(
  149. facet_type_id, context.insts().GetLocId(impl.latest_decl_id()), [&] {
  150. CARBON_DIAGNOSTIC(ImplOfUndefinedInterface, Error,
  151. "implementation of undefined interface {0}",
  152. SemIR::NameId);
  153. return context.emitter().Build(impl.latest_decl_id(),
  154. ImplOfUndefinedInterface,
  155. interface.name_id);
  156. })) {
  157. return SemIR::ErrorInst::SingletonInstId;
  158. }
  159. llvm::SmallVector<SemIR::InstId> table;
  160. auto assoc_entities =
  161. context.inst_blocks().Get(interface.associated_entities_id);
  162. table.reserve(assoc_entities.size());
  163. for (auto decl_id : assoc_entities) {
  164. LoadImportRef(context, decl_id);
  165. decl_id =
  166. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  167. context.sem_ir(), interface_type->specific_id, decl_id));
  168. CARBON_CHECK(decl_id.is_valid(), "Non-constant associated entity");
  169. auto decl = context.insts().Get(decl_id);
  170. CARBON_KIND_SWITCH(decl) {
  171. case CARBON_KIND(SemIR::StructValue struct_value): {
  172. if (struct_value.type_id == SemIR::ErrorInst::SingletonTypeId) {
  173. table.push_back(SemIR::ErrorInst::SingletonInstId);
  174. break;
  175. }
  176. auto type_inst = context.types().GetAsInst(struct_value.type_id);
  177. auto fn_type = type_inst.TryAs<SemIR::FunctionType>();
  178. if (!fn_type) {
  179. CARBON_FATAL("Unexpected type: {0}", type_inst);
  180. }
  181. table.push_back(SemIR::InstId::Invalid);
  182. break;
  183. }
  184. case CARBON_KIND(SemIR::AssociatedConstantDecl associated): {
  185. // TODO: Allow these using:
  186. // table.push_back(SemIR::InstId::Invalid);
  187. // break;
  188. context.TODO(
  189. impl.latest_decl_id(),
  190. "impl of interface with associated constant " +
  191. context.names().GetFormatted(associated.name_id).str());
  192. return SemIR::ErrorInst::SingletonInstId;
  193. }
  194. default:
  195. CARBON_CHECK(decl_id == SemIR::ErrorInst::SingletonInstId,
  196. "Unexpected kind of associated entity {0}", decl);
  197. table.push_back(SemIR::ErrorInst::SingletonInstId);
  198. break;
  199. }
  200. }
  201. auto table_id = context.inst_blocks().Add(table);
  202. return context.AddInst<SemIR::ImplWitness>(
  203. context.insts().GetLocId(impl.latest_decl_id()),
  204. {.type_id = context.GetSingletonType(SemIR::WitnessType::SingletonInstId),
  205. .elements_id = table_id,
  206. .specific_id = context.generics().GetSelfSpecific(impl.generic_id)});
  207. }
  208. auto ImplWitnessStartDefinition(Context& /*context*/, SemIR::Impl& impl)
  209. -> void {
  210. CARBON_CHECK(impl.is_being_defined());
  211. // TODO: Check we have a value for all non-function associated constants in
  212. // the constraint, and fill the witness with them.
  213. }
  214. // Adds functions to the witness that the specified impl implements the given
  215. // interface.
  216. auto FinishImplWitness(Context& context, SemIR::Impl& impl) -> void {
  217. CARBON_CHECK(impl.is_being_defined());
  218. if (impl.witness_id == SemIR::ErrorInst::SingletonInstId) {
  219. return;
  220. }
  221. auto facet_type_id = context.GetTypeIdForTypeInst(impl.constraint_id);
  222. CARBON_CHECK(facet_type_id != SemIR::ErrorInst::SingletonTypeId);
  223. auto facet_type = context.types().GetAs<SemIR::FacetType>(facet_type_id);
  224. const SemIR::FacetTypeInfo& facet_type_info =
  225. context.facet_types().Get(facet_type.facet_type_id);
  226. auto interface_type = facet_type_info.TryAsSingleInterface();
  227. CARBON_CHECK(interface_type.has_value());
  228. const auto& interface =
  229. context.interfaces().Get(interface_type->interface_id);
  230. auto witness = context.insts().GetAs<SemIR::ImplWitness>(impl.witness_id);
  231. auto witness_block = context.inst_blocks().GetMutable(witness.elements_id);
  232. auto& impl_scope = context.name_scopes().Get(impl.scope_id);
  233. auto self_type_id = context.GetTypeIdForTypeInst(impl.self_id);
  234. auto assoc_entities =
  235. context.inst_blocks().Get(interface.associated_entities_id);
  236. llvm::SmallVector<SemIR::InstId> used_decl_ids;
  237. for (auto index : llvm::seq(assoc_entities.size())) {
  238. auto decl_id = assoc_entities[index];
  239. decl_id =
  240. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  241. context.sem_ir(), interface_type->specific_id, decl_id));
  242. CARBON_CHECK(decl_id.is_valid(), "Non-constant associated entity");
  243. auto decl = context.insts().Get(decl_id);
  244. CARBON_KIND_SWITCH(decl) {
  245. case CARBON_KIND(SemIR::StructValue struct_value): {
  246. if (struct_value.type_id == SemIR::ErrorInst::SingletonTypeId) {
  247. break;
  248. }
  249. auto type_inst = context.types().GetAsInst(struct_value.type_id);
  250. auto fn_type = type_inst.As<SemIR::FunctionType>();
  251. auto& fn = context.functions().Get(fn_type.function_id);
  252. auto [impl_decl_id, _] = context.LookupNameInExactScope(
  253. decl_id, fn.name_id, impl.scope_id, impl_scope);
  254. if (impl_decl_id.is_valid()) {
  255. used_decl_ids.push_back(impl_decl_id);
  256. witness_block[index] = CheckAssociatedFunctionImplementation(
  257. context, fn_type, impl_decl_id, self_type_id, impl.witness_id);
  258. } else {
  259. CARBON_DIAGNOSTIC(
  260. ImplMissingFunction, Error,
  261. "missing implementation of {0} in impl of interface {1}",
  262. SemIR::NameId, SemIR::NameId);
  263. auto builder =
  264. context.emitter().Build(impl.definition_id, ImplMissingFunction,
  265. fn.name_id, interface.name_id);
  266. NoteAssociatedFunction(context, builder, fn_type.function_id);
  267. builder.Emit();
  268. witness_block[index] = SemIR::ErrorInst::SingletonInstId;
  269. }
  270. break;
  271. }
  272. case SemIR::AssociatedConstantDecl::Kind: {
  273. // These are set to their final values already.
  274. break;
  275. }
  276. default:
  277. CARBON_CHECK(decl_id == SemIR::ErrorInst::SingletonInstId,
  278. "Unexpected kind of associated entity {0}", decl);
  279. // These are set to their final values already.
  280. break;
  281. }
  282. }
  283. // TODO: Diagnose if any declarations in the impl are not in used_decl_ids.
  284. }
  285. auto FillImplWitnessWithErrors(Context& context, SemIR::Impl& impl) -> void {
  286. if (impl.witness_id.is_valid() &&
  287. impl.witness_id != SemIR::ErrorInst::SingletonInstId) {
  288. auto witness = context.insts().GetAs<SemIR::ImplWitness>(impl.witness_id);
  289. auto witness_block = context.inst_blocks().GetMutable(witness.elements_id);
  290. for (auto& elem : witness_block) {
  291. if (!elem.is_valid()) {
  292. elem = SemIR::ErrorInst::SingletonInstId;
  293. }
  294. }
  295. }
  296. }
  297. } // namespace Carbon::Check