impl_scope.cpp 18 KB

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