impl.cpp 19 KB

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