impl.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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/convert.h"
  8. #include "toolchain/check/eval.h"
  9. #include "toolchain/check/function.h"
  10. #include "toolchain/check/generic.h"
  11. #include "toolchain/check/import_ref.h"
  12. #include "toolchain/check/interface.h"
  13. #include "toolchain/check/type_completion.h"
  14. #include "toolchain/diagnostics/diagnostic_emitter.h"
  15. #include "toolchain/sem_ir/generic.h"
  16. #include "toolchain/sem_ir/ids.h"
  17. #include "toolchain/sem_ir/impl.h"
  18. #include "toolchain/sem_ir/inst.h"
  19. #include "toolchain/sem_ir/typed_insts.h"
  20. namespace Carbon::Check {
  21. // Adds the location of the associated function to a diagnostic.
  22. static auto NoteAssociatedFunction(Context& context,
  23. Context::DiagnosticBuilder& builder,
  24. SemIR::FunctionId function_id) -> void {
  25. CARBON_DIAGNOSTIC(AssociatedFunctionHere, Note,
  26. "associated function {0} declared here", SemIR::NameId);
  27. const auto& function = context.functions().Get(function_id);
  28. builder.Note(function.latest_decl_id(), AssociatedFunctionHere,
  29. function.name_id);
  30. }
  31. // Checks that `impl_function_id` is a valid implementation of the function
  32. // described in the interface as `interface_function_id`. Returns the value to
  33. // put into the corresponding slot in the witness table, which can be
  34. // `BuiltinErrorInst` if the function is not usable.
  35. static auto CheckAssociatedFunctionImplementation(
  36. Context& context, SemIR::FunctionType interface_function_type,
  37. SemIR::InstId impl_decl_id, SemIR::TypeId self_type_id,
  38. SemIR::InstId witness_inst_id) -> SemIR::InstId {
  39. auto impl_function_decl =
  40. context.insts().TryGetAs<SemIR::FunctionDecl>(impl_decl_id);
  41. if (!impl_function_decl) {
  42. CARBON_DIAGNOSTIC(ImplFunctionWithNonFunction, Error,
  43. "associated function {0} implemented by non-function",
  44. SemIR::NameId);
  45. auto builder = context.emitter().Build(
  46. impl_decl_id, ImplFunctionWithNonFunction,
  47. context.functions().Get(interface_function_type.function_id).name_id);
  48. NoteAssociatedFunction(context, builder,
  49. interface_function_type.function_id);
  50. builder.Emit();
  51. return SemIR::ErrorInst::SingletonInstId;
  52. }
  53. // Map from the specific for the function type to the specific for the
  54. // function signature. The function signature may have additional generic
  55. // parameters.
  56. auto interface_function_specific_id =
  57. GetSelfSpecificForInterfaceMemberWithSelfType(
  58. context, impl_decl_id, interface_function_type.specific_id,
  59. context.functions()
  60. .Get(interface_function_type.function_id)
  61. .generic_id,
  62. self_type_id, witness_inst_id);
  63. if (!CheckFunctionTypeMatches(
  64. context, context.functions().Get(impl_function_decl->function_id),
  65. context.functions().Get(interface_function_type.function_id),
  66. interface_function_specific_id,
  67. /*check_syntax=*/false)) {
  68. return SemIR::ErrorInst::SingletonInstId;
  69. }
  70. return impl_decl_id;
  71. }
  72. // Builds an initial empty witness.
  73. // TODO: Fill the witness with the rewrites from the declaration.
  74. auto ImplWitnessForDeclaration(Context& context, const SemIR::Impl& impl)
  75. -> SemIR::InstId {
  76. CARBON_CHECK(!impl.has_definition_started());
  77. auto facet_type_id = context.GetTypeIdForTypeInst(impl.constraint_id);
  78. if (facet_type_id == SemIR::ErrorInst::SingletonTypeId) {
  79. return SemIR::ErrorInst::SingletonInstId;
  80. }
  81. auto facet_type = context.types().TryGetAs<SemIR::FacetType>(facet_type_id);
  82. if (!facet_type) {
  83. CARBON_DIAGNOSTIC(ImplAsNonFacetType, Error, "impl as non-facet type {0}",
  84. InstIdAsType);
  85. context.emitter().Emit(impl.latest_decl_id(), ImplAsNonFacetType,
  86. impl.constraint_id);
  87. return SemIR::ErrorInst::SingletonInstId;
  88. }
  89. const SemIR::FacetTypeInfo& facet_type_info =
  90. context.facet_types().Get(facet_type->facet_type_id);
  91. auto interface_type = facet_type_info.TryAsSingleInterface();
  92. if (!interface_type) {
  93. context.TODO(impl.latest_decl_id(), "impl as not 1 interface");
  94. return SemIR::ErrorInst::SingletonInstId;
  95. }
  96. const auto& interface =
  97. context.interfaces().Get(interface_type->interface_id);
  98. // TODO: This should be done as part of facet type resolution.
  99. if (!RequireDefinedType(context, facet_type_id,
  100. context.insts().GetLocId(impl.latest_decl_id()), [&] {
  101. CARBON_DIAGNOSTIC(
  102. ImplOfUndefinedInterface, Error,
  103. "implementation of undefined interface {0}",
  104. SemIR::NameId);
  105. return context.emitter().Build(
  106. impl.latest_decl_id(), ImplOfUndefinedInterface,
  107. interface.name_id);
  108. })) {
  109. return SemIR::ErrorInst::SingletonInstId;
  110. }
  111. auto assoc_entities =
  112. context.inst_blocks().Get(interface.associated_entities_id);
  113. for (auto decl_id : assoc_entities) {
  114. LoadImportRef(context, decl_id);
  115. }
  116. llvm::SmallVector<SemIR::InstId> table(assoc_entities.size(),
  117. SemIR::InstId::None);
  118. auto table_id = context.inst_blocks().Add(table);
  119. return context.AddInst<SemIR::ImplWitness>(
  120. context.insts().GetLocId(impl.latest_decl_id()),
  121. {.type_id = context.GetSingletonType(SemIR::WitnessType::SingletonInstId),
  122. .elements_id = table_id,
  123. .specific_id = context.generics().GetSelfSpecific(impl.generic_id)});
  124. }
  125. // Returns `true` if the `FacetAccessWitness` of `witness_id` matches
  126. // `interface`.
  127. static auto WitnessAccessMatchesInterface(
  128. Context& context, SemIR::InstId witness_id,
  129. SemIR::FacetTypeInfo::ImplsConstraint interface) -> bool {
  130. auto access = context.insts().GetAs<SemIR::FacetAccessWitness>(witness_id);
  131. auto type_id = context.insts().Get(access.facet_value_inst_id).type_id();
  132. auto facet_type = context.types().GetAs<SemIR::FacetType>(type_id);
  133. const auto& facet_info = context.facet_types().Get(facet_type.facet_type_id);
  134. if (auto impls = facet_info.TryAsSingleInterface()) {
  135. return *impls == interface;
  136. }
  137. return false;
  138. }
  139. // TODO: Merge this function into `ImplWitnessForDeclaration`.
  140. auto AddConstantsToImplWitnessFromConstraint(Context& context,
  141. const SemIR::Impl& impl,
  142. SemIR::InstId witness_id) -> void {
  143. CARBON_CHECK(!impl.has_definition_started());
  144. CARBON_CHECK(witness_id.has_value());
  145. if (witness_id == SemIR::ErrorInst::SingletonInstId) {
  146. return;
  147. }
  148. auto facet_type_id = context.GetTypeIdForTypeInst(impl.constraint_id);
  149. CARBON_CHECK(facet_type_id != SemIR::ErrorInst::SingletonTypeId);
  150. auto facet_type = context.types().GetAs<SemIR::FacetType>(facet_type_id);
  151. const SemIR::FacetTypeInfo& facet_type_info =
  152. context.facet_types().Get(facet_type.facet_type_id);
  153. auto interface_type = facet_type_info.TryAsSingleInterface();
  154. CARBON_CHECK(interface_type.has_value());
  155. const auto& interface =
  156. context.interfaces().Get(interface_type->interface_id);
  157. auto witness = context.insts().GetAs<SemIR::ImplWitness>(witness_id);
  158. auto witness_block = context.inst_blocks().GetMutable(witness.elements_id);
  159. auto assoc_entities =
  160. context.inst_blocks().Get(interface.associated_entities_id);
  161. CARBON_CHECK(witness_block.size() == assoc_entities.size());
  162. // Scan through rewrites, produce map from element index to constant value.
  163. // TODO: Perhaps move this into facet type resolution?
  164. llvm::SmallVector<SemIR::ConstantId> rewrite_values(assoc_entities.size(),
  165. SemIR::ConstantId::None);
  166. for (auto rewrite : facet_type_info.rewrite_constraints) {
  167. auto inst_id = context.constant_values().GetInstId(rewrite.lhs_const_id);
  168. auto access = context.insts().GetAs<SemIR::ImplWitnessAccess>(inst_id);
  169. if (!WitnessAccessMatchesInterface(context, access.witness_id,
  170. *interface_type)) {
  171. // Skip rewrite constraints that apply to associated constants of
  172. // a different interface than the one being implemented.
  173. continue;
  174. }
  175. CARBON_CHECK(access.index.index >= 0);
  176. CARBON_CHECK(access.index.index <
  177. static_cast<int32_t>(rewrite_values.size()));
  178. auto& rewrite_value = rewrite_values[access.index.index];
  179. if (rewrite_value.has_value() &&
  180. rewrite_value != SemIR::ErrorInst::SingletonConstantId) {
  181. if (rewrite_value != rewrite.rhs_const_id &&
  182. rewrite.rhs_const_id != SemIR::ErrorInst::SingletonConstantId) {
  183. // TODO: Do at least this checking as part of facet type resolution
  184. // instead.
  185. // TODO: Figure out how to print the two different values
  186. // `rewrite_value` & `rewrite.rhs_const_id` in the diagnostic message.
  187. CARBON_DIAGNOSTIC(AssociatedConstantWithDifferentValues, Error,
  188. "associated constant {0} given two different values",
  189. SemIR::NameId);
  190. auto decl_id = context.constant_values().GetConstantInstId(
  191. assoc_entities[access.index.index]);
  192. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  193. auto decl =
  194. context.insts().GetAs<SemIR::AssociatedConstantDecl>(decl_id);
  195. context.emitter().Emit(
  196. impl.constraint_id, AssociatedConstantWithDifferentValues,
  197. context.associated_constants().Get(decl.assoc_const_id).name_id);
  198. }
  199. } else {
  200. rewrite_value = rewrite.rhs_const_id;
  201. }
  202. }
  203. // For each non-function associated constant, set the witness entry.
  204. for (auto index : llvm::seq(assoc_entities.size())) {
  205. auto decl_id =
  206. context.constant_values().GetConstantInstId(assoc_entities[index]);
  207. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  208. if (auto decl =
  209. context.insts().TryGetAs<SemIR::AssociatedConstantDecl>(decl_id)) {
  210. auto rewrite_value = rewrite_values[index];
  211. // If the associated constant has a symbolic type, convert the rewrite
  212. // value to that type now we know the value of `Self`.
  213. SemIR::TypeId assoc_const_type_id = decl->type_id;
  214. if (context.types().GetConstantId(assoc_const_type_id).is_symbolic()) {
  215. // Get the type of the associated constant in this interface with this
  216. // value for `Self`.
  217. assoc_const_type_id = GetTypeForSpecificAssociatedEntity(
  218. context, impl.constraint_id, interface_type->specific_id, decl_id,
  219. context.GetTypeIdForTypeInst(impl.self_id), witness_id);
  220. // Perform the conversion of the value to the type. We skipped this when
  221. // forming the facet type because the type of the associated constant
  222. // was symbolic.
  223. auto converted_inst_id = ConvertToValueOfType(
  224. context, context.insts().GetLocId(impl.constraint_id),
  225. context.constant_values().GetInstId(rewrite_value),
  226. assoc_const_type_id);
  227. rewrite_value = context.constant_values().Get(converted_inst_id);
  228. // The result of conversion can be non-constant even if the original
  229. // value was constant.
  230. if (!rewrite_value.is_constant() &&
  231. rewrite_value != SemIR::ErrorInst::SingletonConstantId) {
  232. const auto& assoc_const =
  233. context.associated_constants().Get(decl->assoc_const_id);
  234. CARBON_DIAGNOSTIC(
  235. AssociatedConstantNotConstantAfterConversion, Error,
  236. "associated constant {0} given value that is not constant "
  237. "after conversion to {1}",
  238. SemIR::NameId, SemIR::TypeId);
  239. context.emitter().Emit(impl.constraint_id,
  240. AssociatedConstantNotConstantAfterConversion,
  241. assoc_const.name_id, assoc_const_type_id);
  242. rewrite_value = SemIR::ErrorInst::SingletonConstantId;
  243. }
  244. }
  245. if (rewrite_value.has_value()) {
  246. witness_block[index] =
  247. context.constant_values().GetInstId(rewrite_value);
  248. }
  249. }
  250. }
  251. }
  252. auto ImplWitnessStartDefinition(Context& context, SemIR::Impl& impl) -> void {
  253. CARBON_CHECK(impl.is_being_defined());
  254. CARBON_CHECK(impl.witness_id.has_value());
  255. if (impl.witness_id == SemIR::ErrorInst::SingletonInstId) {
  256. return;
  257. }
  258. auto facet_type_id = context.GetTypeIdForTypeInst(impl.constraint_id);
  259. CARBON_CHECK(facet_type_id != SemIR::ErrorInst::SingletonTypeId);
  260. auto facet_type = context.types().GetAs<SemIR::FacetType>(facet_type_id);
  261. const SemIR::FacetTypeInfo& facet_type_info =
  262. context.facet_types().Get(facet_type.facet_type_id);
  263. auto interface_type = facet_type_info.TryAsSingleInterface();
  264. CARBON_CHECK(interface_type.has_value());
  265. const auto& interface =
  266. context.interfaces().Get(interface_type->interface_id);
  267. auto witness = context.insts().GetAs<SemIR::ImplWitness>(impl.witness_id);
  268. auto witness_block = context.inst_blocks().GetMutable(witness.elements_id);
  269. auto assoc_entities =
  270. context.inst_blocks().Get(interface.associated_entities_id);
  271. CARBON_CHECK(witness_block.size() == assoc_entities.size());
  272. // Check we have a value for all non-function associated constants in the
  273. // witness.
  274. for (auto index : llvm::seq(assoc_entities.size())) {
  275. auto decl_id = assoc_entities[index];
  276. decl_id = context.constant_values().GetConstantInstId(decl_id);
  277. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  278. if (auto decl =
  279. context.insts().TryGetAs<SemIR::AssociatedConstantDecl>(decl_id)) {
  280. auto& witness_value = witness_block[index];
  281. if (!witness_value.has_value()) {
  282. CARBON_DIAGNOSTIC(ImplAssociatedConstantNeedsValue, Error,
  283. "associated constant {0} not given a value in impl "
  284. "of interface {1}",
  285. SemIR::NameId, SemIR::NameId);
  286. CARBON_DIAGNOSTIC(AssociatedConstantHere, Note,
  287. "associated constant declared here");
  288. context.emitter()
  289. .Build(impl.constraint_id, ImplAssociatedConstantNeedsValue,
  290. context.associated_constants()
  291. .Get(decl->assoc_const_id)
  292. .name_id,
  293. interface.name_id)
  294. .Note(assoc_entities[index], AssociatedConstantHere)
  295. .Emit();
  296. witness_value = SemIR::ErrorInst::SingletonInstId;
  297. }
  298. }
  299. }
  300. }
  301. // Adds functions to the witness that the specified impl implements the given
  302. // interface.
  303. auto FinishImplWitness(Context& context, SemIR::Impl& impl) -> void {
  304. CARBON_CHECK(impl.is_being_defined());
  305. CARBON_CHECK(impl.witness_id.has_value());
  306. if (impl.witness_id == SemIR::ErrorInst::SingletonInstId) {
  307. return;
  308. }
  309. auto facet_type_id = context.GetTypeIdForTypeInst(impl.constraint_id);
  310. CARBON_CHECK(facet_type_id != SemIR::ErrorInst::SingletonTypeId);
  311. auto facet_type = context.types().GetAs<SemIR::FacetType>(facet_type_id);
  312. const SemIR::FacetTypeInfo& facet_type_info =
  313. context.facet_types().Get(facet_type.facet_type_id);
  314. auto interface_type = facet_type_info.TryAsSingleInterface();
  315. CARBON_CHECK(interface_type.has_value());
  316. const auto& interface =
  317. context.interfaces().Get(interface_type->interface_id);
  318. auto witness = context.insts().GetAs<SemIR::ImplWitness>(impl.witness_id);
  319. auto witness_block = context.inst_blocks().GetMutable(witness.elements_id);
  320. auto& impl_scope = context.name_scopes().Get(impl.scope_id);
  321. auto self_type_id = context.GetTypeIdForTypeInst(impl.self_id);
  322. auto assoc_entities =
  323. context.inst_blocks().Get(interface.associated_entities_id);
  324. llvm::SmallVector<SemIR::InstId> used_decl_ids;
  325. for (auto index : llvm::seq(assoc_entities.size())) {
  326. auto decl_id = assoc_entities[index];
  327. decl_id =
  328. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  329. context.sem_ir(), interface_type->specific_id, decl_id));
  330. CARBON_CHECK(decl_id.has_value(), "Non-constant associated entity");
  331. auto decl = context.insts().Get(decl_id);
  332. CARBON_KIND_SWITCH(decl) {
  333. case CARBON_KIND(SemIR::StructValue struct_value): {
  334. if (struct_value.type_id == SemIR::ErrorInst::SingletonTypeId) {
  335. witness_block[index] = SemIR::ErrorInst::SingletonInstId;
  336. break;
  337. }
  338. auto type_inst = context.types().GetAsInst(struct_value.type_id);
  339. auto fn_type = type_inst.TryAs<SemIR::FunctionType>();
  340. if (!fn_type) {
  341. CARBON_FATAL("Unexpected type: {0}", type_inst);
  342. }
  343. auto& fn = context.functions().Get(fn_type->function_id);
  344. auto lookup_result = context.LookupNameInExactScope(
  345. context.insts().GetLocId(decl_id), fn.name_id, impl.scope_id,
  346. impl_scope);
  347. if (lookup_result.is_found()) {
  348. used_decl_ids.push_back(lookup_result.target_inst_id());
  349. witness_block[index] = CheckAssociatedFunctionImplementation(
  350. context, *fn_type, lookup_result.target_inst_id(), self_type_id,
  351. impl.witness_id);
  352. } else {
  353. CARBON_DIAGNOSTIC(
  354. ImplMissingFunction, Error,
  355. "missing implementation of {0} in impl of interface {1}",
  356. SemIR::NameId, SemIR::NameId);
  357. auto builder =
  358. context.emitter().Build(impl.definition_id, ImplMissingFunction,
  359. fn.name_id, interface.name_id);
  360. NoteAssociatedFunction(context, builder, fn_type->function_id);
  361. builder.Emit();
  362. witness_block[index] = SemIR::ErrorInst::SingletonInstId;
  363. }
  364. break;
  365. }
  366. case SemIR::AssociatedConstantDecl::Kind: {
  367. // These are set to their final values already.
  368. break;
  369. }
  370. default:
  371. CARBON_CHECK(decl_id == SemIR::ErrorInst::SingletonInstId,
  372. "Unexpected kind of associated entity {0}", decl);
  373. witness_block[index] = SemIR::ErrorInst::SingletonInstId;
  374. break;
  375. }
  376. }
  377. // TODO: Diagnose if any declarations in the impl are not in used_decl_ids.
  378. }
  379. auto FillImplWitnessWithErrors(Context& context, SemIR::Impl& impl) -> void {
  380. if (impl.witness_id.has_value() &&
  381. impl.witness_id != SemIR::ErrorInst::SingletonInstId) {
  382. auto witness = context.insts().GetAs<SemIR::ImplWitness>(impl.witness_id);
  383. auto witness_block = context.inst_blocks().GetMutable(witness.elements_id);
  384. for (auto& elem : witness_block) {
  385. if (!elem.has_value()) {
  386. elem = SemIR::ErrorInst::SingletonInstId;
  387. }
  388. }
  389. }
  390. }
  391. } // namespace Carbon::Check