impl_lookup.cpp 18 KB

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