impl_lookup.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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/diagnostic_helpers.h"
  7. #include "toolchain/check/generic.h"
  8. #include "toolchain/check/import_ref.h"
  9. #include "toolchain/check/inst.h"
  10. #include "toolchain/check/type.h"
  11. #include "toolchain/check/type_completion.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/impl.h"
  14. #include "toolchain/sem_ir/inst.h"
  15. #include "toolchain/sem_ir/typed_insts.h"
  16. namespace Carbon::Check {
  17. static auto FindAssociatedImportIRs(Context& context,
  18. SemIR::ConstantId type_const_id,
  19. SemIR::ConstantId query_facet_type_const_id)
  20. -> llvm::SmallVector<SemIR::ImportIRId> {
  21. llvm::SmallVector<SemIR::ImportIRId> result;
  22. // Add an entity to our result.
  23. auto add_entity = [&](const SemIR::EntityWithParamsBase& entity) {
  24. // We will look for impls in the import IR associated with the first owning
  25. // declaration.
  26. auto decl_id = entity.first_owning_decl_id;
  27. if (!decl_id.has_value()) {
  28. return;
  29. }
  30. if (auto ir_id = GetCanonicalImportIRInst(context, decl_id).ir_id;
  31. ir_id.has_value()) {
  32. result.push_back(ir_id);
  33. }
  34. };
  35. llvm::SmallVector<SemIR::InstId> worklist;
  36. worklist.push_back(context.constant_values().GetInstId(type_const_id));
  37. worklist.push_back(
  38. context.constant_values().GetInstId(query_facet_type_const_id));
  39. // Push the contents of an instruction block onto our worklist.
  40. auto push_block = [&](SemIR::InstBlockId block_id) {
  41. if (block_id.has_value()) {
  42. llvm::append_range(worklist, context.inst_blocks().Get(block_id));
  43. }
  44. };
  45. // Add the arguments of a specific to the worklist.
  46. auto push_args = [&](SemIR::SpecificId specific_id) {
  47. if (specific_id.has_value()) {
  48. push_block(context.specifics().Get(specific_id).args_id);
  49. }
  50. };
  51. while (!worklist.empty()) {
  52. auto inst_id = worklist.pop_back_val();
  53. // Visit the operands of the constant.
  54. auto inst = context.insts().Get(inst_id);
  55. auto [arg0_kind, arg1_kind] = inst.ArgKinds();
  56. for (auto [arg, kind] :
  57. {std::pair{inst.arg0(), arg0_kind}, {inst.arg1(), arg1_kind}}) {
  58. switch (kind) {
  59. case SemIR::IdKind::For<SemIR::InstId>: {
  60. if (auto id = SemIR::InstId(arg); id.has_value()) {
  61. worklist.push_back(id);
  62. }
  63. break;
  64. }
  65. case SemIR::IdKind::For<SemIR::InstBlockId>: {
  66. push_block(SemIR::InstBlockId(arg));
  67. break;
  68. }
  69. case SemIR::IdKind::For<SemIR::ClassId>: {
  70. add_entity(context.classes().Get(SemIR::ClassId(arg)));
  71. break;
  72. }
  73. case SemIR::IdKind::For<SemIR::InterfaceId>: {
  74. add_entity(context.interfaces().Get(SemIR::InterfaceId(arg)));
  75. break;
  76. }
  77. case SemIR::IdKind::For<SemIR::FacetTypeId>: {
  78. const auto& facet_type_info =
  79. context.facet_types().Get(SemIR::FacetTypeId(arg));
  80. for (const auto& impl : facet_type_info.impls_constraints) {
  81. add_entity(context.interfaces().Get(impl.interface_id));
  82. push_args(impl.specific_id);
  83. }
  84. break;
  85. }
  86. case SemIR::IdKind::For<SemIR::FunctionId>: {
  87. add_entity(context.functions().Get(SemIR::FunctionId(arg)));
  88. break;
  89. }
  90. case SemIR::IdKind::For<SemIR::SpecificId>: {
  91. push_args(SemIR::SpecificId(arg));
  92. break;
  93. }
  94. default: {
  95. break;
  96. }
  97. }
  98. }
  99. }
  100. // Deduplicate.
  101. llvm::sort(result, [](SemIR::ImportIRId a, SemIR::ImportIRId b) {
  102. return a.index < b.index;
  103. });
  104. result.erase(llvm::unique(result), result.end());
  105. return result;
  106. }
  107. // Returns true if a cycle was found and diagnosed.
  108. static auto FindAndDiagnoseImplLookupCycle(
  109. Context& context,
  110. const llvm::SmallVector<Context::ImplLookupStackEntry>& stack,
  111. SemIR::LocId loc_id, SemIR::ConstantId type_const_id,
  112. SemIR::ConstantId query_facet_type_const_id) -> bool {
  113. // Deduction of the interface parameters can do further impl lookups, and we
  114. // need to ensure we terminate.
  115. //
  116. // https://docs.carbon-lang.dev/docs/design/generics/details.html#acyclic-rule
  117. // - We look for violations of the acyclic rule by seeing if a previous lookup
  118. // had all the same type inputs.
  119. // - The `query_facet_type_const_id` encodes the entire facet type being
  120. // looked up, including any specific parameters for a generic interface.
  121. //
  122. // TODO: Implement the termination rule, which requires looking at the
  123. // complexity of the types on the top of (or throughout?) the stack:
  124. // https://docs.carbon-lang.dev/docs/design/generics/details.html#termination-rule
  125. for (auto [i, entry] : llvm::enumerate(stack)) {
  126. if (entry.type_const_id == type_const_id &&
  127. entry.query_facet_type_const_id == query_facet_type_const_id) {
  128. auto facet_type_type_id =
  129. context.types().GetTypeIdForTypeConstantId(query_facet_type_const_id);
  130. CARBON_DIAGNOSTIC(ImplLookupCycle, Error,
  131. "cycle found in search for impl of {0} for type {1}",
  132. SemIR::TypeId, SemIR::TypeId);
  133. auto builder = context.emitter().Build(
  134. loc_id, ImplLookupCycle, facet_type_type_id,
  135. context.types().GetTypeIdForTypeConstantId(type_const_id));
  136. for (const auto& active_entry : llvm::drop_begin(stack, i)) {
  137. if (active_entry.impl_loc.has_value()) {
  138. CARBON_DIAGNOSTIC(ImplLookupCycleNote, Note,
  139. "determining if this impl clause matches", );
  140. builder.Note(active_entry.impl_loc, ImplLookupCycleNote);
  141. }
  142. }
  143. builder.Emit();
  144. return true;
  145. }
  146. }
  147. return false;
  148. }
  149. // Gets the set of `SpecificInterface`s that are required by a facet type
  150. // (as a constant value).
  151. static auto GetInterfacesFromConstantId(
  152. Context& context, SemIR::ConstantId query_facet_type_const_id,
  153. bool& has_other_requirements)
  154. -> llvm::SmallVector<SemIR::SpecificInterface> {
  155. auto facet_type_inst_id =
  156. context.constant_values().GetInstId(query_facet_type_const_id);
  157. auto facet_type_inst =
  158. context.insts().GetAs<SemIR::FacetType>(facet_type_inst_id);
  159. const auto& facet_type_info =
  160. context.facet_types().Get(facet_type_inst.facet_type_id);
  161. has_other_requirements = facet_type_info.other_requirements;
  162. // TODO: Once we add support for named constraints, we will need to change
  163. // this to return the same interfaces as in the complete facet type.
  164. return facet_type_info.impls_constraints;
  165. }
  166. static auto GetWitnessIdForImpl(
  167. Context& context, SemIR::LocId loc_id, SemIR::ConstantId type_const_id,
  168. const SemIR::CompleteFacetType::RequiredInterface& interface,
  169. const SemIR::Impl& impl) -> SemIR::InstId {
  170. // If the impl's interface_id differs from the query, then this impl can not
  171. // possibly provide the queried interface, and we don't need to proceed.
  172. if (impl.interface.interface_id != interface.interface_id) {
  173. return SemIR::InstId::None;
  174. }
  175. // When the impl's interface_id matches, but the interface is generic, the
  176. // impl may or may not match based on restrictions in the generic parameters
  177. // of the impl.
  178. //
  179. // As a shortcut, if the impl's constraint is not symbolic (does not depend on
  180. // any generic parameters), then we can determine that we match if the
  181. // specific ids match exactly.
  182. auto impl_interface_const_id =
  183. context.constant_values().Get(impl.constraint_id);
  184. if (!impl_interface_const_id.is_symbolic()) {
  185. if (impl.interface.specific_id != interface.specific_id) {
  186. return SemIR::InstId::None;
  187. }
  188. }
  189. // This check comes first to avoid deduction with an invalid impl. We use an
  190. // error value to indicate an error during creation of the impl, such as a
  191. // recursive impl which will cause deduction to recurse infinitely.
  192. if (impl.witness_id == SemIR::ErrorInst::SingletonInstId) {
  193. return SemIR::InstId::None;
  194. }
  195. CARBON_CHECK(impl.witness_id.has_value());
  196. // The impl may have generic arguments, in which case we need to deduce them
  197. // to find what they are given the specific type and interface query. We use
  198. // that specific to map values in the impl to the deduced values.
  199. auto specific_id = SemIR::SpecificId::None;
  200. if (impl.generic_id.has_value()) {
  201. specific_id = DeduceImplArguments(context, loc_id, impl, type_const_id,
  202. interface.specific_id);
  203. if (!specific_id.has_value()) {
  204. return SemIR::InstId::None;
  205. }
  206. }
  207. // The self type of the impl must match the type in the query, or this is an
  208. // `impl T as ...` for some other type `T` and should not be considered.
  209. auto deduced_self_const_id = SemIR::GetConstantValueInSpecific(
  210. context.sem_ir(), specific_id, impl.self_id);
  211. if (type_const_id != deduced_self_const_id) {
  212. return SemIR::InstId::None;
  213. }
  214. // The impl's constraint is a facet type which it is implementing for the self
  215. // type: the `I` in `impl ... as I`. The deduction step may be unable to be
  216. // fully applied to the types in the constraint and result in an error here,
  217. // in which case it does not match the query.
  218. auto deduced_constraint_id =
  219. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  220. context.sem_ir(), specific_id, impl.constraint_id));
  221. if (deduced_constraint_id == SemIR::ErrorInst::SingletonInstId) {
  222. return SemIR::InstId::None;
  223. }
  224. auto deduced_constraint_facet_type_id =
  225. context.insts()
  226. .GetAs<SemIR::FacetType>(deduced_constraint_id)
  227. .facet_type_id;
  228. const auto& deduced_constraint_facet_type_info =
  229. context.facet_types().Get(deduced_constraint_facet_type_id);
  230. CARBON_CHECK(deduced_constraint_facet_type_info.impls_constraints.size() ==
  231. 1);
  232. if (deduced_constraint_facet_type_info.other_requirements) {
  233. // TODO: Remove this when other requirements goes away.
  234. return SemIR::InstId::None;
  235. }
  236. // The specifics in the queried interface must match the deduced specifics in
  237. // the impl's constraint facet type.
  238. auto impl_interface_specific_id =
  239. deduced_constraint_facet_type_info.impls_constraints[0].specific_id;
  240. auto query_interface_specific_id = interface.specific_id;
  241. if (impl_interface_specific_id != query_interface_specific_id) {
  242. return SemIR::InstId::None;
  243. }
  244. LoadImportRef(context, impl.witness_id);
  245. if (specific_id.has_value()) {
  246. // We need a definition of the specific `impl` so we can access its
  247. // witness.
  248. ResolveSpecificDefinition(context, loc_id, specific_id);
  249. }
  250. return context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  251. context.sem_ir(), specific_id, impl.witness_id));
  252. }
  253. // In the case where `facet_const_id` is a facet, see if its facet type requires
  254. // that `specific_interface` is implemented. If so, return the witness from the
  255. // facet.
  256. static auto FindWitnessInFacet(
  257. Context& context, SemIR::LocId loc_id, SemIR::ConstantId facet_const_id,
  258. const SemIR::SpecificInterface& specific_interface) -> SemIR::InstId {
  259. SemIR::InstId facet_inst_id =
  260. context.constant_values().GetInstId(facet_const_id);
  261. // TODO: Should we convert from a FacetAccessType to its facet here?
  262. SemIR::TypeId facet_type_id = context.insts().Get(facet_inst_id).type_id();
  263. if (auto facet_type_inst =
  264. context.types().TryGetAs<SemIR::FacetType>(facet_type_id)) {
  265. auto complete_facet_type_id = RequireCompleteFacetType(
  266. context, facet_type_id, loc_id, *facet_type_inst,
  267. [&]() -> DiagnosticBuilder {
  268. // TODO: Find test that triggers this code path.
  269. CARBON_FATAL("impl lookup for with incomplete facet type");
  270. });
  271. if (complete_facet_type_id.has_value()) {
  272. const auto& complete_facet_type =
  273. context.complete_facet_types().Get(complete_facet_type_id);
  274. for (auto [index, interface] :
  275. llvm::enumerate(complete_facet_type.required_interfaces)) {
  276. if (interface == specific_interface) {
  277. return GetOrAddInst(
  278. context, loc_id,
  279. SemIR::FacetAccessWitness{
  280. .type_id = GetSingletonType(
  281. context, SemIR::WitnessType::SingletonInstId),
  282. .facet_value_inst_id = facet_inst_id,
  283. .index = SemIR::ElementIndex(index)});
  284. }
  285. }
  286. }
  287. }
  288. return SemIR::InstId::None;
  289. }
  290. static auto FindWitnessInImpls(
  291. Context& context, SemIR::LocId loc_id, SemIR::ConstantId type_const_id,
  292. const SemIR::SpecificInterface& specific_interface) -> SemIR::InstId {
  293. auto& stack = context.impl_lookup_stack();
  294. for (const auto& impl : context.impls().array_ref()) {
  295. stack.back().impl_loc = impl.definition_id;
  296. auto result_witness_id = GetWitnessIdForImpl(context, loc_id, type_const_id,
  297. specific_interface, impl);
  298. if (result_witness_id.has_value()) {
  299. // We found a matching impl; don't keep looking for this interface.
  300. return result_witness_id;
  301. }
  302. }
  303. return SemIR::InstId::None;
  304. }
  305. auto LookupImplWitness(Context& context, SemIR::LocId loc_id,
  306. SemIR::ConstantId type_const_id,
  307. SemIR::ConstantId query_facet_type_const_id)
  308. -> SemIR::InstBlockIdOrError {
  309. if (type_const_id == SemIR::ErrorInst::SingletonConstantId ||
  310. query_facet_type_const_id == SemIR::ErrorInst::SingletonConstantId) {
  311. return SemIR::InstBlockIdOrError::MakeError();
  312. }
  313. auto import_irs = FindAssociatedImportIRs(context, type_const_id,
  314. query_facet_type_const_id);
  315. for (auto import_ir : import_irs) {
  316. // TODO: Instead of importing all impls, only import ones that are in some
  317. // way connected to this query.
  318. for (auto impl_index : llvm::seq(
  319. context.import_irs().Get(import_ir).sem_ir->impls().size())) {
  320. // TODO: Track the relevant impls and only consider those ones and any
  321. // local impls, rather than looping over all impls below.
  322. ImportImpl(context, import_ir, SemIR::ImplId(impl_index));
  323. }
  324. }
  325. if (FindAndDiagnoseImplLookupCycle(context, context.impl_lookup_stack(),
  326. loc_id, type_const_id,
  327. query_facet_type_const_id)) {
  328. return SemIR::InstBlockIdOrError::MakeError();
  329. }
  330. bool has_other_requirements = false;
  331. auto interfaces = GetInterfacesFromConstantId(
  332. context, query_facet_type_const_id, has_other_requirements);
  333. if (has_other_requirements) {
  334. // TODO: Remove this when other requirements go away.
  335. return SemIR::InstBlockId::None;
  336. }
  337. if (interfaces.empty()) {
  338. return SemIR::InstBlockId::Empty;
  339. }
  340. llvm::SmallVector<SemIR::InstId> result_witness_ids;
  341. auto& stack = context.impl_lookup_stack();
  342. stack.push_back({
  343. .type_const_id = type_const_id,
  344. .query_facet_type_const_id = query_facet_type_const_id,
  345. });
  346. // We need to find a witness for each interface in `interfaces`. We return
  347. // them in the same order as they are found in the `CompleteFacetType`, which
  348. // is the same order as in `interfaces` here.
  349. for (const auto& interface : interfaces) {
  350. // TODO: Since both `interfaces` and `type_const_id` are sorted lists, do an
  351. // O(N+M) merge instead of O(N*M) nested loops.
  352. auto result_witness_id =
  353. FindWitnessInFacet(context, loc_id, type_const_id, interface);
  354. if (!result_witness_id.has_value()) {
  355. result_witness_id =
  356. FindWitnessInImpls(context, loc_id, type_const_id, interface);
  357. }
  358. if (result_witness_id.has_value()) {
  359. result_witness_ids.push_back(result_witness_id);
  360. } else {
  361. // At least one queried interface in the facet type has no witness for the
  362. // given type, we can stop looking for more.
  363. break;
  364. }
  365. }
  366. stack.pop_back();
  367. // TODO: Validate that the witness satisfies the other requirements in
  368. // `interface_const_id`.
  369. // All interfaces in the query facet type must have been found to be available
  370. // through some impl (TODO: or directly on the type itself if `type_const_id`
  371. // is a facet type).
  372. if (result_witness_ids.size() != interfaces.size()) {
  373. return SemIR::InstBlockId::None;
  374. }
  375. return context.inst_blocks().AddCanonical(result_witness_ids);
  376. }
  377. } // namespace Carbon::Check