impl_lookup.cpp 17 KB

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