impl_lookup.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 query_self_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(query_self_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 query_self_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.query_self_const_id == query_self_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(query_self_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: This needs to match the order of witnesses for the facet type, which
  163. // will need to be maintained once we add support for named constraints.
  164. return facet_type_info.impls_constraints;
  165. }
  166. static auto GetWitnessIdForImpl(Context& context, SemIR::LocId loc_id,
  167. SemIR::ConstantId query_self_const_id,
  168. const SemIR::SpecificInterface& interface,
  169. SemIR::ImplId impl_id) -> SemIR::InstId {
  170. // The impl may have generic arguments, in which case we need to deduce them
  171. // to find what they are given the specific type and interface query. We use
  172. // that specific to map values in the impl to the deduced values.
  173. auto specific_id = SemIR::SpecificId::None;
  174. {
  175. // DeduceImplArguments can import new impls which can invalidate any
  176. // pointers into `context.impls()`.
  177. const SemIR::Impl& impl = context.impls().Get(impl_id);
  178. if (impl.generic_id.has_value()) {
  179. specific_id =
  180. DeduceImplArguments(context, loc_id,
  181. {.self_id = impl.self_id,
  182. .generic_id = impl.generic_id,
  183. .specific_id = impl.interface.specific_id},
  184. query_self_const_id, interface.specific_id);
  185. if (!specific_id.has_value()) {
  186. return SemIR::InstId::None;
  187. }
  188. }
  189. }
  190. // Get a pointer again after DeduceImplArguments() is complete.
  191. const SemIR::Impl& impl = context.impls().Get(impl_id);
  192. // The self type of the impl must match the type in the query, or this is an
  193. // `impl T as ...` for some other type `T` and should not be considered.
  194. auto deduced_self_const_id = SemIR::GetConstantValueInSpecific(
  195. context.sem_ir(), specific_id, impl.self_id);
  196. if (query_self_const_id != deduced_self_const_id) {
  197. return SemIR::InstId::None;
  198. }
  199. // The impl's constraint is a facet type which it is implementing for the self
  200. // type: the `I` in `impl ... as I`. The deduction step may be unable to be
  201. // fully applied to the types in the constraint and result in an error here,
  202. // in which case it does not match the query.
  203. auto deduced_constraint_id =
  204. context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  205. context.sem_ir(), specific_id, impl.constraint_id));
  206. if (deduced_constraint_id == SemIR::ErrorInst::SingletonInstId) {
  207. return SemIR::InstId::None;
  208. }
  209. auto deduced_constraint_facet_type_id =
  210. context.insts()
  211. .GetAs<SemIR::FacetType>(deduced_constraint_id)
  212. .facet_type_id;
  213. const auto& deduced_constraint_facet_type_info =
  214. context.facet_types().Get(deduced_constraint_facet_type_id);
  215. CARBON_CHECK(deduced_constraint_facet_type_info.impls_constraints.size() ==
  216. 1);
  217. if (deduced_constraint_facet_type_info.other_requirements) {
  218. // TODO: Remove this when other requirements goes away.
  219. return SemIR::InstId::None;
  220. }
  221. // The specifics in the queried interface must match the deduced specifics in
  222. // the impl's constraint facet type.
  223. auto impl_interface_specific_id =
  224. deduced_constraint_facet_type_info.impls_constraints[0].specific_id;
  225. auto query_interface_specific_id = interface.specific_id;
  226. if (impl_interface_specific_id != query_interface_specific_id) {
  227. return SemIR::InstId::None;
  228. }
  229. LoadImportRef(context, impl.witness_id);
  230. if (specific_id.has_value()) {
  231. // We need a definition of the specific `impl` so we can access its
  232. // witness.
  233. ResolveSpecificDefinition(context, loc_id, specific_id);
  234. }
  235. return context.constant_values().GetInstId(SemIR::GetConstantValueInSpecific(
  236. context.sem_ir(), specific_id, impl.witness_id));
  237. }
  238. // In the case where `facet_const_id` is a facet, see if its facet type requires
  239. // that `specific_interface` is implemented. If so, return the witness from the
  240. // facet.
  241. static auto FindWitnessInFacet(
  242. Context& context, SemIR::LocId loc_id, SemIR::ConstantId facet_const_id,
  243. const SemIR::SpecificInterface& specific_interface) -> SemIR::InstId {
  244. SemIR::InstId facet_inst_id =
  245. context.constant_values().GetInstId(facet_const_id);
  246. if (auto access =
  247. context.insts().TryGetAs<SemIR::FacetAccessType>(facet_inst_id)) {
  248. facet_inst_id = context.constant_values().GetConstantInstId(
  249. access->facet_value_inst_id);
  250. }
  251. SemIR::TypeId facet_type_id = context.insts().Get(facet_inst_id).type_id();
  252. if (auto facet_type_inst =
  253. context.types().TryGetAs<SemIR::FacetType>(facet_type_id)) {
  254. const auto& facet_type_info =
  255. context.facet_types().Get(facet_type_inst->facet_type_id);
  256. // TODO: This depends on the index into `impls_constraints` matching
  257. // the index into the facet type witness. This will have to be maintained
  258. // even for facet types that include named constraints, once that is
  259. // supported.
  260. for (auto [index, interface] :
  261. llvm::enumerate(facet_type_info.impls_constraints)) {
  262. if (interface == specific_interface) {
  263. return GetOrAddInst(
  264. context, loc_id,
  265. SemIR::FacetAccessWitness{
  266. .type_id = GetSingletonType(
  267. context, SemIR::WitnessType::SingletonInstId),
  268. .facet_value_inst_id = facet_inst_id,
  269. .index = SemIR::ElementIndex(index)});
  270. }
  271. }
  272. }
  273. return SemIR::InstId::None;
  274. }
  275. static auto FindWitnessInImpls(
  276. Context& context, SemIR::LocId loc_id,
  277. SemIR::ConstantId query_self_const_id,
  278. const SemIR::SpecificInterface& specific_interface) -> SemIR::InstId {
  279. auto& stack = context.impl_lookup_stack();
  280. // TODO: Build this candidate list by matching against type structures to
  281. // narrow it down.
  282. llvm::SmallVector<std::pair<SemIR::ImplId, SemIR::InstId>> candidate_impl_ids;
  283. for (auto [id, impl] : context.impls().enumerate()) {
  284. // If the impl's interface_id differs from the query, then this impl can not
  285. // possibly provide the queried interface.
  286. if (impl.interface.interface_id != specific_interface.interface_id) {
  287. continue;
  288. }
  289. // When the impl's interface_id matches, but the interface is generic, the
  290. // impl may or may not match based on restrictions in the generic parameters
  291. // of the impl.
  292. //
  293. // As a shortcut, if the impl's constraint is not symbolic (does not depend
  294. // on any generic parameters), then we can determine that we match if the
  295. // specific ids match exactly.
  296. auto impl_interface_const_id =
  297. context.constant_values().Get(impl.constraint_id);
  298. if (!impl_interface_const_id.is_symbolic()) {
  299. if (impl.interface.specific_id != specific_interface.specific_id) {
  300. continue;
  301. }
  302. }
  303. // This check comes first to avoid deduction with an invalid impl. We use an
  304. // error value to indicate an error during creation of the impl, such as a
  305. // recursive impl which will cause deduction to recurse infinitely.
  306. if (impl.witness_id == SemIR::ErrorInst::SingletonInstId) {
  307. continue;
  308. }
  309. CARBON_CHECK(impl.witness_id.has_value());
  310. candidate_impl_ids.push_back({id, impl.definition_id});
  311. }
  312. for (auto [impl_id, loc_inst_id] : candidate_impl_ids) {
  313. stack.back().impl_loc = loc_inst_id;
  314. // NOTE: GetWitnessIdForImpl() does deduction, which can cause new impls to
  315. // be imported, invalidating any pointer into `context.impls()`.
  316. auto result_witness_id = GetWitnessIdForImpl(
  317. context, loc_id, query_self_const_id, specific_interface, impl_id);
  318. if (result_witness_id.has_value()) {
  319. // We found a matching impl; don't keep looking for this interface.
  320. return result_witness_id;
  321. }
  322. }
  323. return SemIR::InstId::None;
  324. }
  325. auto LookupImplWitness(Context& context, SemIR::LocId loc_id,
  326. SemIR::ConstantId query_self_const_id,
  327. SemIR::ConstantId query_facet_type_const_id)
  328. -> SemIR::InstBlockIdOrError {
  329. if (query_self_const_id == SemIR::ErrorInst::SingletonConstantId ||
  330. query_facet_type_const_id == SemIR::ErrorInst::SingletonConstantId) {
  331. return SemIR::InstBlockIdOrError::MakeError();
  332. }
  333. {
  334. // The query self value is a type value or a facet value.
  335. auto query_self_type_id =
  336. context.insts()
  337. .Get(context.constant_values().GetInstId(query_self_const_id))
  338. .type_id();
  339. CARBON_CHECK(context.types().Is<SemIR::TypeType>(query_self_type_id) ||
  340. context.types().Is<SemIR::FacetType>(query_self_type_id));
  341. // The query facet type value is indeed a facet type.
  342. CARBON_CHECK(context.insts().Is<SemIR::FacetType>(
  343. context.constant_values().GetInstId(query_facet_type_const_id)));
  344. }
  345. auto import_irs = FindAssociatedImportIRs(context, query_self_const_id,
  346. query_facet_type_const_id);
  347. for (auto import_ir : import_irs) {
  348. // TODO: Instead of importing all impls, only import ones that are in some
  349. // way connected to this query.
  350. for (auto impl_index : llvm::seq(
  351. context.import_irs().Get(import_ir).sem_ir->impls().size())) {
  352. // TODO: Track the relevant impls and only consider those ones and any
  353. // local impls, rather than looping over all impls below.
  354. ImportImpl(context, import_ir, SemIR::ImplId(impl_index));
  355. }
  356. }
  357. if (FindAndDiagnoseImplLookupCycle(context, context.impl_lookup_stack(),
  358. loc_id, query_self_const_id,
  359. query_facet_type_const_id)) {
  360. return SemIR::InstBlockIdOrError::MakeError();
  361. }
  362. bool has_other_requirements = false;
  363. auto interfaces = GetInterfacesFromConstantId(
  364. context, query_facet_type_const_id, has_other_requirements);
  365. if (has_other_requirements) {
  366. // TODO: Remove this when other requirements go away.
  367. return SemIR::InstBlockId::None;
  368. }
  369. if (interfaces.empty()) {
  370. return SemIR::InstBlockId::Empty;
  371. }
  372. llvm::SmallVector<SemIR::InstId> result_witness_ids;
  373. auto& stack = context.impl_lookup_stack();
  374. stack.push_back({
  375. .query_self_const_id = query_self_const_id,
  376. .query_facet_type_const_id = query_facet_type_const_id,
  377. });
  378. // We need to find a witness for each interface in `interfaces`. Every
  379. // consumer of a facet type needs to agree on the order of interfaces used for
  380. // its witnesses.
  381. for (const auto& interface : interfaces) {
  382. // TODO: Since both `interfaces` and `query_self_const_id` are sorted lists,
  383. // do an O(N+M) merge instead of O(N*M) nested loops.
  384. auto result_witness_id =
  385. FindWitnessInFacet(context, loc_id, query_self_const_id, interface);
  386. if (!result_witness_id.has_value()) {
  387. result_witness_id =
  388. FindWitnessInImpls(context, loc_id, query_self_const_id, interface);
  389. }
  390. if (result_witness_id.has_value()) {
  391. result_witness_ids.push_back(result_witness_id);
  392. } else {
  393. // At least one queried interface in the facet type has no witness for the
  394. // given type, we can stop looking for more.
  395. break;
  396. }
  397. }
  398. stack.pop_back();
  399. // TODO: Validate that the witness satisfies the other requirements in
  400. // `interface_const_id`.
  401. // All interfaces in the query facet type must have been found to be available
  402. // through some impl, or directly on the value's facet type if
  403. // `query_self_const_id` is a facet value.
  404. if (result_witness_ids.size() != interfaces.size()) {
  405. return SemIR::InstBlockId::None;
  406. }
  407. return context.inst_blocks().AddCanonical(result_witness_ids);
  408. }
  409. } // namespace Carbon::Check