impl_scope.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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 "explorer/interpreter/impl_scope.h"
  5. #include "explorer/ast/value.h"
  6. #include "explorer/interpreter/type_checker.h"
  7. #include "llvm/ADT/StringExtras.h"
  8. #include "llvm/Support/Casting.h"
  9. using llvm::cast;
  10. using llvm::dyn_cast;
  11. namespace Carbon {
  12. void ImplScope::Add(Nonnull<const Value*> iface, Nonnull<const Value*> type,
  13. Nonnull<const Witness*> witness,
  14. const TypeChecker& type_checker) {
  15. Add(iface, {}, type, {}, witness, type_checker);
  16. }
  17. void ImplScope::Add(Nonnull<const Value*> iface,
  18. llvm::ArrayRef<Nonnull<const GenericBinding*>> deduced,
  19. Nonnull<const Value*> type,
  20. llvm::ArrayRef<Nonnull<const ImplBinding*>> impl_bindings,
  21. Nonnull<const Witness*> witness,
  22. const TypeChecker& type_checker,
  23. std::optional<TypeStructureSortKey> sort_key) {
  24. if (const auto* constraint = dyn_cast<ConstraintType>(iface)) {
  25. CARBON_CHECK(!sort_key)
  26. << "should only be given a sort key for an impl of an interface";
  27. // The caller should have substituted `.Self` for `type` already.
  28. Add(constraint->impls_constraints(), deduced, impl_bindings, witness,
  29. type_checker);
  30. // A parameterized impl declaration doesn't contribute any equality
  31. // constraints to the scope. Instead, we'll resolve the equality
  32. // constraints by resolving a witness when needed.
  33. if (deduced.empty()) {
  34. for (const auto& equality_constraint :
  35. constraint->equality_constraints()) {
  36. equalities_.push_back(&equality_constraint);
  37. }
  38. }
  39. return;
  40. }
  41. ImplFact new_impl = {.interface = cast<InterfaceType>(iface),
  42. .deduced = deduced,
  43. .type = type,
  44. .impl_bindings = impl_bindings,
  45. .witness = witness,
  46. .sort_key = std::move(sort_key)};
  47. // Find the first impl that's more specific than this one, and place this
  48. // impl right before it. This keeps the impls with the same type structure
  49. // sorted in lexical order, which is important for `match_first` semantics.
  50. auto insert_pos =
  51. std::upper_bound(impl_facts_.begin(), impl_facts_.end(), new_impl,
  52. [](const ImplFact& a, const ImplFact& b) {
  53. return a.sort_key < b.sort_key;
  54. });
  55. impl_facts_.insert(insert_pos, std::move(new_impl));
  56. }
  57. void ImplScope::Add(llvm::ArrayRef<ImplsConstraint> impls_constraints,
  58. llvm::ArrayRef<Nonnull<const GenericBinding*>> deduced,
  59. llvm::ArrayRef<Nonnull<const ImplBinding*>> impl_bindings,
  60. Nonnull<const Witness*> witness,
  61. const TypeChecker& type_checker) {
  62. for (size_t i = 0; i != impls_constraints.size(); ++i) {
  63. ImplsConstraint impl = impls_constraints[i];
  64. Add(impl.interface, deduced, impl.type, impl_bindings,
  65. type_checker.MakeConstraintWitnessAccess(witness, i), type_checker);
  66. }
  67. }
  68. // Diagnose that `a_evaluated != b_evaluated` for the purpose of an equality
  69. // constraint.
  70. static auto DiagnoseUnequalValues(SourceLocation source_loc,
  71. Nonnull<const Value*> a_written,
  72. Nonnull<const Value*> a_evaluated,
  73. Nonnull<const Value*> b_written,
  74. Nonnull<const Value*> b_evaluated,
  75. Nonnull<const EqualityContext*> equality_ctx)
  76. -> Error {
  77. CARBON_CHECK(!ValueEqual(a_evaluated, b_evaluated, equality_ctx))
  78. << "expected unequal values";
  79. auto error = ProgramError(source_loc);
  80. error << "constraint requires that " << *a_written;
  81. if (!ValueEqual(a_written, a_evaluated, std::nullopt)) {
  82. error << " (with value " << *a_evaluated << ")";
  83. }
  84. error << " == " << *b_written;
  85. if (!ValueEqual(b_written, b_evaluated, std::nullopt)) {
  86. error << " (with value " << *b_evaluated << ")";
  87. }
  88. error << ", which is not known to be true";
  89. return std::move(error);
  90. }
  91. auto ImplScope::Resolve(Nonnull<const Value*> constraint_type,
  92. Nonnull<const Value*> impl_type,
  93. SourceLocation source_loc,
  94. const TypeChecker& type_checker,
  95. const Bindings& bindings) const
  96. -> ErrorOr<Nonnull<const Witness*>> {
  97. CARBON_ASSIGN_OR_RETURN(
  98. std::optional<Nonnull<const Witness*>> witness,
  99. TryResolve(constraint_type, impl_type, source_loc, type_checker, bindings,
  100. /*diagnose_missing_impl=*/true));
  101. CARBON_CHECK(witness) << "should have diagnosed missing impl";
  102. return *witness;
  103. }
  104. auto ImplScope::TryResolve(Nonnull<const Value*> constraint_type,
  105. Nonnull<const Value*> impl_type,
  106. SourceLocation source_loc,
  107. const TypeChecker& type_checker,
  108. const Bindings& bindings,
  109. bool diagnose_missing_impl) const
  110. -> ErrorOr<std::optional<Nonnull<const Witness*>>> {
  111. if (const auto* iface_type = dyn_cast<InterfaceType>(constraint_type)) {
  112. CARBON_ASSIGN_OR_RETURN(
  113. iface_type,
  114. type_checker.SubstituteCast<InterfaceType>(bindings, iface_type));
  115. return TryResolveInterface(iface_type, impl_type, source_loc, type_checker,
  116. diagnose_missing_impl);
  117. }
  118. if (const auto* constraint = dyn_cast<ConstraintType>(constraint_type)) {
  119. std::vector<Nonnull<const Witness*>> witnesses;
  120. for (auto impl : constraint->impls_constraints()) {
  121. // Note that later impls constraints can refer to earlier impls
  122. // constraints via impl bindings. For example, in
  123. // `C where .Self.AssocType impls D`,
  124. // ... the `.Self.AssocType impls D` constraint refers to the
  125. // `.Self impls C` constraint when naming `AssocType`. So incrementally
  126. // build up a partial constraint witness as we go.
  127. std::optional<Nonnull<const Witness*>> witness;
  128. if (constraint->self_binding()->impl_binding()) {
  129. // Note, this is a partial impl binding covering only the impl
  130. // constraints that we've already seen. Earlier impls constraints should
  131. // not be able to refer to impl bindings for later impls constraints.
  132. witness = type_checker.MakeConstraintWitness(witnesses);
  133. }
  134. Bindings local_bindings = bindings;
  135. local_bindings.Add(constraint->self_binding(), impl_type, witness);
  136. CARBON_ASSIGN_OR_RETURN(const auto* subst_interface,
  137. type_checker.SubstituteCast<InterfaceType>(
  138. local_bindings, impl.interface));
  139. CARBON_ASSIGN_OR_RETURN(
  140. Nonnull<const Value*> subst_type,
  141. type_checker.Substitute(local_bindings, impl.type));
  142. CARBON_ASSIGN_OR_RETURN(
  143. std::optional<Nonnull<const Witness*>> result,
  144. TryResolveInterface(subst_interface, subst_type, source_loc,
  145. type_checker, diagnose_missing_impl));
  146. if (!result) {
  147. return {std::nullopt};
  148. }
  149. witnesses.push_back(*result);
  150. }
  151. // Check that all intrinsic, equality, and rewrite constraints
  152. // are satisfied in this scope.
  153. llvm::ArrayRef<IntrinsicConstraint> intrinsics =
  154. constraint->intrinsic_constraints();
  155. llvm::ArrayRef<EqualityConstraint> equals =
  156. constraint->equality_constraints();
  157. llvm::ArrayRef<RewriteConstraint> rewrites =
  158. constraint->rewrite_constraints();
  159. if (!intrinsics.empty() || !equals.empty() || !rewrites.empty()) {
  160. std::optional<Nonnull<const Witness*>> witness;
  161. if (constraint->self_binding()->impl_binding()) {
  162. witness = type_checker.MakeConstraintWitness(witnesses);
  163. }
  164. Bindings local_bindings = bindings;
  165. local_bindings.Add(constraint->self_binding(), impl_type, witness);
  166. SingleStepEqualityContext equality_ctx(this);
  167. for (const auto& intrinsic : intrinsics) {
  168. CARBON_ASSIGN_OR_RETURN(
  169. Nonnull<const Value*> type,
  170. type_checker.Substitute(local_bindings, intrinsic.type));
  171. IntrinsicConstraint converted(type, intrinsic.kind, {});
  172. converted.arguments.reserve(intrinsic.arguments.size());
  173. for (Nonnull<const Value*> argument : intrinsic.arguments) {
  174. CARBON_ASSIGN_OR_RETURN(
  175. Nonnull<const Value*> subst_arg,
  176. type_checker.Substitute(local_bindings, argument));
  177. converted.arguments.push_back(subst_arg);
  178. }
  179. CARBON_ASSIGN_OR_RETURN(bool intrinsic_satisfied,
  180. type_checker.IsIntrinsicConstraintSatisfied(
  181. source_loc, converted, *this));
  182. if (!intrinsic_satisfied) {
  183. if (!diagnose_missing_impl) {
  184. return {std::nullopt};
  185. }
  186. return ProgramError(source_loc)
  187. << "constraint requires that " << converted;
  188. }
  189. }
  190. for (const auto& equal : equals) {
  191. auto it = equal.values.begin();
  192. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> first,
  193. type_checker.Substitute(local_bindings, *it++));
  194. for (; it != equal.values.end(); ++it) {
  195. CARBON_ASSIGN_OR_RETURN(Nonnull<const Value*> current,
  196. type_checker.Substitute(local_bindings, *it));
  197. if (!ValueEqual(first, current, &equality_ctx)) {
  198. if (!diagnose_missing_impl) {
  199. return {std::nullopt};
  200. }
  201. return DiagnoseUnequalValues(source_loc, equal.values.front(),
  202. first, *it, current, &equality_ctx);
  203. }
  204. }
  205. }
  206. for (const auto& rewrite : rewrites) {
  207. CARBON_ASSIGN_OR_RETURN(
  208. Nonnull<const Value*> constant,
  209. type_checker.Substitute(local_bindings, rewrite.constant));
  210. CARBON_ASSIGN_OR_RETURN(
  211. Nonnull<const Value*> value,
  212. type_checker.Substitute(local_bindings,
  213. rewrite.converted_replacement));
  214. if (!ValueEqual(constant, value, &equality_ctx)) {
  215. if (!diagnose_missing_impl) {
  216. return {std::nullopt};
  217. }
  218. return DiagnoseUnequalValues(source_loc, rewrite.constant, constant,
  219. rewrite.converted_replacement, value,
  220. &equality_ctx);
  221. }
  222. }
  223. }
  224. return {type_checker.MakeConstraintWitness(std::move(witnesses))};
  225. }
  226. CARBON_FATAL() << "expected a constraint, not " << *constraint_type;
  227. }
  228. auto ImplScope::VisitEqualValues(
  229. Nonnull<const Value*> value,
  230. llvm::function_ref<bool(Nonnull<const Value*>)> visitor) const -> bool {
  231. for (Nonnull<const EqualityConstraint*> eq : equalities_) {
  232. if (!eq->VisitEqualValues(value, visitor)) {
  233. return false;
  234. }
  235. }
  236. return !parent_scope_ || (*parent_scope_)->VisitEqualValues(value, visitor);
  237. }
  238. auto ImplScope::TryResolveInterface(Nonnull<const InterfaceType*> iface_type,
  239. Nonnull<const Value*> type,
  240. SourceLocation source_loc,
  241. const TypeChecker& type_checker,
  242. bool diagnose_missing_impl) const
  243. -> ErrorOr<std::optional<Nonnull<const Witness*>>> {
  244. CARBON_ASSIGN_OR_RETURN(
  245. std::optional<ResolveResult> result,
  246. TryResolveInterfaceRecursively(iface_type, type, source_loc, *this,
  247. type_checker));
  248. if (!result.has_value() && diagnose_missing_impl) {
  249. return ProgramError(source_loc) << "could not find implementation of "
  250. << *iface_type << " for " << *type;
  251. }
  252. return result ? std::optional(result->witness) : std::nullopt;
  253. }
  254. // Do these two witnesses refer to `impl` declarations in the same
  255. // `match_first` block?
  256. static auto InSameMatchFirst(Nonnull<const Witness*> a,
  257. Nonnull<const Witness*> b) -> bool {
  258. const auto* impl_a = dyn_cast<ImplWitness>(a);
  259. const auto* impl_b = dyn_cast<ImplWitness>(b);
  260. if (!impl_a || !impl_b) {
  261. return false;
  262. }
  263. // TODO: Once we support an impl being declared more than once, we will need
  264. // to check this more carefully.
  265. return impl_a->declaration().match_first() &&
  266. impl_a->declaration().match_first() ==
  267. impl_b->declaration().match_first();
  268. }
  269. // Determine whether this result is definitely right -- that there can be no
  270. // specialization that would give a better match.
  271. static auto IsEffectivelyFinal(ImplScope::ResolveResult result) -> bool {
  272. // TODO: Once we support 'final', check whether this is a final impl
  273. // declaration if it's parameterized.
  274. return result.impl->deduced.empty();
  275. }
  276. // Combines the results of two impl lookups. In the event of a tie, arbitrarily
  277. // prefer `a` over `b`.
  278. static auto CombineResults(Nonnull<const InterfaceType*> iface_type,
  279. Nonnull<const Value*> type,
  280. SourceLocation source_loc,
  281. std::optional<ImplScope::ResolveResult> a,
  282. std::optional<ImplScope::ResolveResult> b)
  283. -> ErrorOr<std::optional<ImplScope::ResolveResult>> {
  284. // If only one lookup succeeded, return that.
  285. if (!b) {
  286. return a;
  287. }
  288. if (!a) {
  289. return b;
  290. }
  291. // If exactly one of them is effectively final, prefer that result.
  292. bool a_is_final = IsEffectivelyFinal(*a);
  293. bool b_is_final = IsEffectivelyFinal(*b);
  294. if (a_is_final && !b_is_final) {
  295. return a;
  296. } else if (b_is_final && !a_is_final) {
  297. return b;
  298. }
  299. const auto* impl_a = dyn_cast<ImplWitness>(a->witness);
  300. const auto* impl_b = dyn_cast<ImplWitness>(b->witness);
  301. // If both are effectively final, prefer an impl declaration over a
  302. // symbolic ImplBinding, because we get more information from the impl
  303. // declaration. If they're both symbolic, arbitrarily pick a.
  304. if (a_is_final && b_is_final) {
  305. if (!impl_b) {
  306. return a;
  307. }
  308. if (!impl_a) {
  309. return b;
  310. }
  311. }
  312. CARBON_CHECK(impl_a && impl_b) << "non-final impl should not be symbolic";
  313. // At this point, we're comparing two `impl` declarations, and either they're
  314. // both final or neither of them is.
  315. // TODO: We should reject the case where both are final when checking their
  316. // declarations, but we don't do so yet, so for now we report it as an
  317. // ambiguity.
  318. //
  319. // If they refer to the same `impl` declaration, it doesn't matter which one
  320. // we pick, so we pick `a`.
  321. // TODO: Compare the identities of the `impl`s, not the declarations.
  322. if (&impl_a->declaration() == &impl_b->declaration()) {
  323. return a;
  324. }
  325. return ProgramError(source_loc)
  326. << "ambiguous implementations of " << *iface_type << " for " << *type;
  327. }
  328. auto ImplScope::TryResolveInterfaceRecursively(
  329. Nonnull<const InterfaceType*> iface_type, Nonnull<const Value*> type,
  330. SourceLocation source_loc, const ImplScope& original_scope,
  331. const TypeChecker& type_checker) const
  332. -> ErrorOr<std::optional<ResolveResult>> {
  333. CARBON_ASSIGN_OR_RETURN(
  334. std::optional<ResolveResult> result,
  335. TryResolveInterfaceHere(iface_type, type, source_loc, original_scope,
  336. type_checker));
  337. if (parent_scope_) {
  338. CARBON_ASSIGN_OR_RETURN(
  339. std::optional<ResolveResult> parent_result,
  340. (*parent_scope_)
  341. ->TryResolveInterfaceRecursively(iface_type, type, source_loc,
  342. original_scope, type_checker));
  343. CARBON_ASSIGN_OR_RETURN(result, CombineResults(iface_type, type, source_loc,
  344. result, parent_result));
  345. }
  346. return result;
  347. }
  348. auto ImplScope::TryResolveInterfaceHere(
  349. Nonnull<const InterfaceType*> iface_type, Nonnull<const Value*> impl_type,
  350. SourceLocation source_loc, const ImplScope& original_scope,
  351. const TypeChecker& type_checker) const
  352. -> ErrorOr<std::optional<ResolveResult>> {
  353. std::optional<ResolveResult> result = std::nullopt;
  354. for (const ImplFact& impl : impl_facts_) {
  355. // If we've passed the final impl with a sort key matching our best impl,
  356. // all further are worse and don't need to be checked.
  357. if (result && result->impl->sort_key < impl.sort_key) {
  358. break;
  359. }
  360. // If this impl appears later in the same match_first block as our best
  361. // result, we should not consider it.
  362. //
  363. // TODO: This should apply transitively: if we have
  364. // match_first { impl a; impl b; }
  365. // match_first { impl b; impl c; }
  366. // then we should not consider c once we match a. For now, because each
  367. // impl is only declared once, this is not a problem.
  368. if (result && InSameMatchFirst(result->impl->witness, impl.witness)) {
  369. continue;
  370. }
  371. // Try matching this impl against our query.
  372. CARBON_ASSIGN_OR_RETURN(std::optional<Nonnull<const Witness*>> witness,
  373. type_checker.MatchImpl(*iface_type, impl_type, impl,
  374. original_scope, source_loc));
  375. if (witness) {
  376. CARBON_ASSIGN_OR_RETURN(
  377. result,
  378. CombineResults(iface_type, impl_type, source_loc, result,
  379. ResolveResult{.impl = &impl, .witness = *witness}));
  380. }
  381. }
  382. return result;
  383. }
  384. // TODO: Add indentation when printing the parents.
  385. void ImplScope::Print(llvm::raw_ostream& out) const {
  386. llvm::ListSeparator sep(",\n ");
  387. out << " "
  388. << "[";
  389. for (const ImplFact& impl : impl_facts_) {
  390. out << sep << "`" << *(impl.type) << "` as `" << *(impl.interface) << "`";
  391. if (impl.sort_key) {
  392. out << " " << *impl.sort_key;
  393. }
  394. }
  395. for (Nonnull<const EqualityConstraint*> eq : equalities_) {
  396. out << sep;
  397. llvm::ListSeparator equal(" == ");
  398. for (Nonnull<const Value*> value : eq->values) {
  399. out << equal << "`" << *value << "`";
  400. }
  401. }
  402. out << "]\n";
  403. if (parent_scope_) {
  404. out << **parent_scope_;
  405. }
  406. }
  407. auto SingleStepEqualityContext::VisitEqualValues(
  408. Nonnull<const Value*> value,
  409. llvm::function_ref<bool(Nonnull<const Value*>)> visitor) const -> bool {
  410. return impl_scope_->VisitEqualValues(value, visitor);
  411. }
  412. } // namespace Carbon