impl.cpp 19 KB

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