impl.cpp 19 KB

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