impl.cpp 19 KB

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