impl_lookup.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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_lookup.h"
  5. #include "toolchain/check/deduce.h"
  6. #include "toolchain/check/generic.h"
  7. #include "toolchain/check/import_ref.h"
  8. #include "toolchain/check/type_completion.h"
  9. #include "toolchain/sem_ir/ids.h"
  10. #include "toolchain/sem_ir/impl.h"
  11. #include "toolchain/sem_ir/inst.h"
  12. #include "toolchain/sem_ir/typed_insts.h"
  13. namespace Carbon::Check {
  14. static auto FindAssociatedImportIRs(Context& context,
  15. SemIR::ConstantId type_const_id,
  16. SemIR::ConstantId interface_const_id)
  17. -> llvm::SmallVector<SemIR::ImportIRId> {
  18. llvm::SmallVector<SemIR::ImportIRId> result;
  19. // Add an entity to our result.
  20. auto add_entity = [&](const SemIR::EntityWithParamsBase& entity) {
  21. // We will look for impls in the import IR associated with the first owning
  22. // declaration.
  23. auto decl_id = entity.first_owning_decl_id;
  24. if (!decl_id.has_value()) {
  25. return;
  26. }
  27. if (auto ir_id = GetCanonicalImportIRInst(context, decl_id).ir_id;
  28. ir_id.has_value()) {
  29. result.push_back(ir_id);
  30. }
  31. };
  32. llvm::SmallVector<SemIR::InstId> worklist;
  33. worklist.push_back(context.constant_values().GetInstId(type_const_id));
  34. worklist.push_back(context.constant_values().GetInstId(interface_const_id));
  35. // Push the contents of an instruction block onto our worklist.
  36. auto push_block = [&](SemIR::InstBlockId block_id) {
  37. if (block_id.has_value()) {
  38. llvm::append_range(worklist, context.inst_blocks().Get(block_id));
  39. }
  40. };
  41. // Add the arguments of a specific to the worklist.
  42. auto push_args = [&](SemIR::SpecificId specific_id) {
  43. if (specific_id.has_value()) {
  44. push_block(context.specifics().Get(specific_id).args_id);
  45. }
  46. };
  47. while (!worklist.empty()) {
  48. auto inst_id = worklist.pop_back_val();
  49. // Visit the operands of the constant.
  50. auto inst = context.insts().Get(inst_id);
  51. auto [arg0_kind, arg1_kind] = inst.ArgKinds();
  52. for (auto [arg, kind] :
  53. {std::pair{inst.arg0(), arg0_kind}, {inst.arg1(), arg1_kind}}) {
  54. switch (kind) {
  55. case SemIR::IdKind::For<SemIR::InstId>: {
  56. if (auto id = SemIR::InstId(arg); id.has_value()) {
  57. worklist.push_back(id);
  58. }
  59. break;
  60. }
  61. case SemIR::IdKind::For<SemIR::InstBlockId>: {
  62. push_block(SemIR::InstBlockId(arg));
  63. break;
  64. }
  65. case SemIR::IdKind::For<SemIR::ClassId>: {
  66. add_entity(context.classes().Get(SemIR::ClassId(arg)));
  67. break;
  68. }
  69. case SemIR::IdKind::For<SemIR::InterfaceId>: {
  70. add_entity(context.interfaces().Get(SemIR::InterfaceId(arg)));
  71. break;
  72. }
  73. case SemIR::IdKind::For<SemIR::FacetTypeId>: {
  74. const auto& facet_type_info =
  75. context.facet_types().Get(SemIR::FacetTypeId(arg));
  76. for (const auto& impl : facet_type_info.impls_constraints) {
  77. add_entity(context.interfaces().Get(impl.interface_id));
  78. push_args(impl.specific_id);
  79. }
  80. break;
  81. }
  82. case SemIR::IdKind::For<SemIR::FunctionId>: {
  83. add_entity(context.functions().Get(SemIR::FunctionId(arg)));
  84. break;
  85. }
  86. case SemIR::IdKind::For<SemIR::SpecificId>: {
  87. push_args(SemIR::SpecificId(arg));
  88. break;
  89. }
  90. default: {
  91. break;
  92. }
  93. }
  94. }
  95. }
  96. // Deduplicate.
  97. llvm::sort(result, [](SemIR::ImportIRId a, SemIR::ImportIRId b) {
  98. return a.index < b.index;
  99. });
  100. result.erase(llvm::unique(result), result.end());
  101. return result;
  102. }
  103. static auto GetWitnessIdForImpl(Context& context, SemIR::LocId loc_id,
  104. SemIR::ConstantId type_const_id,
  105. SemIR::ConstantId interface_const_id,
  106. SemIR::InterfaceId interface_id,
  107. const SemIR::Impl& impl) -> SemIR::InstId {
  108. // If impl.constraint_id is not symbolic, and doesn't match the query, then
  109. // we don't need to proceed.
  110. auto impl_interface_const_id =
  111. context.constant_values().Get(impl.constraint_id);
  112. if (!impl_interface_const_id.is_symbolic() &&
  113. interface_const_id != impl_interface_const_id) {
  114. return SemIR::InstId::None;
  115. }
  116. // This is the (single) interface named in the query `interface_const_id`.
  117. // If the impl's interface_id differs from the query, then this impl can not
  118. // possibly provide the queried interface, and we don't need to proceed.
  119. // Unlike the early-out above comparing the `impl.constraint_id`, this also
  120. // elides looking at impls of generic interfaces where the interface itself
  121. // does not match the query.
  122. if (impl.interface.interface_id != interface_id) {
  123. return SemIR::InstId::None;
  124. }
  125. auto specific_id = SemIR::SpecificId::None;
  126. // This check comes first to avoid deduction with an invalid impl. We use an
  127. // error value to indicate an error during creation of the impl, such as a
  128. // recursive impl which will cause deduction to recurse infinitely.
  129. if (impl.witness_id == SemIR::ErrorInst::SingletonInstId) {
  130. return SemIR::InstId::None;
  131. }
  132. if (impl.generic_id.has_value()) {
  133. specific_id = DeduceImplArguments(context, loc_id, impl, type_const_id,
  134. interface_const_id);
  135. if (!specific_id.has_value()) {
  136. return SemIR::InstId::None;
  137. }
  138. }
  139. if (!context.constant_values().AreEqualAcrossDeclarations(
  140. SemIR::GetConstantValueInSpecific(context.sem_ir(), specific_id,
  141. impl.self_id),
  142. type_const_id)) {
  143. return SemIR::InstId::None;
  144. }
  145. if (!context.constant_values().AreEqualAcrossDeclarations(
  146. SemIR::GetConstantValueInSpecific(context.sem_ir(), specific_id,
  147. impl.constraint_id),
  148. interface_const_id)) {
  149. // TODO: An impl of a constraint type should be treated as implementing
  150. // the constraint's interfaces.
  151. return SemIR::InstId::None;
  152. }
  153. if (!impl.witness_id.has_value()) {
  154. // TODO: Diagnose if the impl isn't defined yet?
  155. return SemIR::InstId::None;
  156. }
  157. LoadImportRef(context, impl.witness_id);
  158. if (specific_id.has_value()) {
  159. // We need a definition of the specific `impl` so we can access its
  160. // witness.
  161. ResolveSpecificDefinition(context, loc_id, specific_id);
  162. }
  163. return context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  164. context.sem_ir(), specific_id, impl.witness_id));
  165. }
  166. auto LookupImplWitness(Context& context, SemIR::LocId loc_id,
  167. SemIR::ConstantId type_const_id,
  168. SemIR::ConstantId interface_const_id) -> SemIR::InstId {
  169. if (type_const_id == SemIR::ErrorInst::SingletonConstantId ||
  170. interface_const_id == SemIR::ErrorInst::SingletonConstantId) {
  171. return SemIR::ErrorInst::SingletonInstId;
  172. }
  173. auto import_irs =
  174. FindAssociatedImportIRs(context, type_const_id, interface_const_id);
  175. for (auto import_ir : import_irs) {
  176. // TODO: Instead of importing all impls, only import ones that are in some
  177. // way connected to this query.
  178. for (auto impl_index : llvm::seq(
  179. context.import_irs().Get(import_ir).sem_ir->impls().size())) {
  180. // TODO: Track the relevant impls and only consider those ones and any
  181. // local impls, rather than looping over all impls below.
  182. ImportImpl(context, import_ir, SemIR::ImplId(impl_index));
  183. }
  184. }
  185. auto& stack = context.impl_lookup_stack();
  186. // Deduction of the interface parameters can do further impl lookups, and we
  187. // need to ensure we terminate.
  188. //
  189. // https://docs.carbon-lang.dev/docs/design/generics/details.html#acyclic-rule
  190. // - We look for violations of the acyclic rule by seeing if a previous lookup
  191. // had all the same type inputs.
  192. // - The `interface_const_id` encodes the entire facet type being looked up,
  193. // including any specific parameters for a generic interface.
  194. //
  195. // TODO: Implement the termination rule, which requires looking at the
  196. // complexity of the types on the top of (or throughout?) the stack:
  197. // https://docs.carbon-lang.dev/docs/design/generics/details.html#termination-rule
  198. for (auto entry : stack) {
  199. if (entry.type_const_id == type_const_id &&
  200. entry.interface_const_id == interface_const_id) {
  201. CARBON_DIAGNOSTIC(ImplLookupCycle, Error,
  202. "cycle found in lookup of interface {0} for type {1}",
  203. std::string, SemIR::TypeId);
  204. context.emitter()
  205. .Build(loc_id, ImplLookupCycle, "<TODO: interface name>",
  206. context.types().GetTypeIdForTypeConstantId(type_const_id))
  207. .Emit();
  208. return SemIR::ErrorInst::SingletonInstId;
  209. }
  210. }
  211. // The `interface_id` is the single interface in the `interface_const_id`
  212. // facet type. In the future, a facet type may include more than a single
  213. // interface, but for now that is unhandled with a TODO.
  214. auto interface_id = [&] {
  215. auto facet_type_inst_id =
  216. context.constant_values().GetInstId(interface_const_id);
  217. auto facet_type_id = context.insts()
  218. .GetAs<SemIR::FacetType>(facet_type_inst_id)
  219. .facet_type_id;
  220. const auto& facet_type_info = context.facet_types().Get(facet_type_id);
  221. if (facet_type_info.impls_constraints.empty()) {
  222. context.TODO(loc_id,
  223. "impl lookup for a FacetType with no interface (using "
  224. "`where .Self impls ...` instead?)");
  225. return SemIR::InterfaceId::None;
  226. }
  227. if (facet_type_info.impls_constraints.size() > 1) {
  228. context.TODO(loc_id,
  229. "impl lookup for a FacetType with more than one interface");
  230. return SemIR::InterfaceId::None;
  231. }
  232. return facet_type_info.impls_constraints[0].interface_id;
  233. }();
  234. auto witness_id = SemIR::InstId::None;
  235. stack.push_back({
  236. .type_const_id = type_const_id,
  237. .interface_const_id = interface_const_id,
  238. });
  239. for (const auto& impl : context.impls().array_ref()) {
  240. witness_id = GetWitnessIdForImpl(context, loc_id, type_const_id,
  241. interface_const_id, interface_id, impl);
  242. if (witness_id.has_value()) {
  243. // We found a matching impl, don't keep looking.
  244. break;
  245. }
  246. }
  247. stack.pop_back();
  248. return witness_id;
  249. }
  250. } // namespace Carbon::Check