impl_lookup.cpp 9.0 KB

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