impl_scope.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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/interpreter/type_checker.h"
  6. #include "explorer/interpreter/value.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. if (const auto* constraint = dyn_cast<ConstraintType>(iface)) {
  24. // The caller should have substituted `.Self` for `type` already.
  25. Add(constraint->impl_constraints(), deduced, impl_bindings, witness,
  26. type_checker);
  27. // A parameterized impl declaration doesn't contribute any equality
  28. // constraints to the scope. Instead, we'll resolve the equality
  29. // constraints by resolving a witness when needed.
  30. if (deduced.empty()) {
  31. for (const auto& equality_constraint :
  32. constraint->equality_constraints()) {
  33. equalities_.push_back(&equality_constraint);
  34. }
  35. }
  36. return;
  37. }
  38. impls_.push_back({.interface = cast<InterfaceType>(iface),
  39. .deduced = deduced,
  40. .type = type,
  41. .impl_bindings = impl_bindings,
  42. .witness = witness});
  43. }
  44. void ImplScope::Add(llvm::ArrayRef<ImplConstraint> impls,
  45. llvm::ArrayRef<Nonnull<const GenericBinding*>> deduced,
  46. llvm::ArrayRef<Nonnull<const ImplBinding*>> impl_bindings,
  47. Nonnull<const Witness*> witness,
  48. const TypeChecker& type_checker) {
  49. for (size_t i = 0; i != impls.size(); ++i) {
  50. ImplConstraint impl = impls[i];
  51. Add(impl.interface, deduced, impl.type, impl_bindings,
  52. type_checker.MakeConstraintWitnessAccess(witness, i), type_checker);
  53. }
  54. }
  55. void ImplScope::AddParent(Nonnull<const ImplScope*> parent) {
  56. parent_scopes_.push_back(parent);
  57. }
  58. // Checks that `a_evaluated == b_evaluated` for the purpose of an equality
  59. // constraint. Produces an error if not.
  60. static auto CheckEqualOrDiagnose(SourceLocation source_loc,
  61. Nonnull<const Value*> a_written,
  62. Nonnull<const Value*> a_evaluated,
  63. Nonnull<const Value*> b_written,
  64. Nonnull<const Value*> b_evaluated,
  65. Nonnull<const EqualityContext*> equality_ctx)
  66. -> ErrorOr<Success> {
  67. if (ValueEqual(a_evaluated, b_evaluated, equality_ctx)) {
  68. return Success();
  69. }
  70. auto error = ProgramError(source_loc);
  71. error << "constraint requires that " << *a_written;
  72. if (!ValueEqual(a_written, a_evaluated, std::nullopt)) {
  73. error << " (with value " << *a_evaluated << ")";
  74. }
  75. error << " == " << *b_written;
  76. if (!ValueEqual(b_written, b_evaluated, std::nullopt)) {
  77. error << " (with value " << *b_evaluated << ")";
  78. }
  79. error << ", which is not known to be true";
  80. return std::move(error);
  81. }
  82. auto ImplScope::Resolve(Nonnull<const Value*> constraint_type,
  83. Nonnull<const Value*> impl_type,
  84. SourceLocation source_loc,
  85. const TypeChecker& type_checker,
  86. const Bindings& bindings) const
  87. -> ErrorOr<Nonnull<const Witness*>> {
  88. if (const auto* iface_type = dyn_cast<InterfaceType>(constraint_type)) {
  89. iface_type =
  90. cast<InterfaceType>(type_checker.Substitute(bindings, iface_type));
  91. return ResolveInterface(iface_type, impl_type, source_loc, type_checker);
  92. }
  93. if (const auto* constraint = dyn_cast<ConstraintType>(constraint_type)) {
  94. std::vector<Nonnull<const Witness*>> witnesses;
  95. for (auto impl : constraint->impl_constraints()) {
  96. // Note that later impl constraints can refer to earlier impl constraints
  97. // via impl bindings. For example, in
  98. // `C where .Self.AssocType is D`,
  99. // ... the `.Self.AssocType is D` constraint refers to the `.Self is C`
  100. // constraint when naming `AssocType`. So incrementally build up a
  101. // partial constraint witness as we go.
  102. std::optional<Nonnull<const Witness*>> witness;
  103. if (constraint->self_binding()->impl_binding()) {
  104. // Note, this is a partial impl binding covering only the impl
  105. // constraints that we've already seen. Earlier impl constraints should
  106. // not be able to refer to impl bindings for later impl constraints.
  107. witness = type_checker.MakeConstraintWitness(witnesses);
  108. }
  109. Bindings local_bindings = bindings;
  110. local_bindings.Add(constraint->self_binding(), impl_type, witness);
  111. CARBON_ASSIGN_OR_RETURN(
  112. Nonnull<const Witness*> result,
  113. ResolveInterface(cast<InterfaceType>(type_checker.Substitute(
  114. local_bindings, impl.interface)),
  115. type_checker.Substitute(local_bindings, impl.type),
  116. source_loc, type_checker));
  117. witnesses.push_back(result);
  118. }
  119. // Check that all equality and rewrite constraints are satisfied in this
  120. // scope.
  121. llvm::ArrayRef<EqualityConstraint> equals =
  122. constraint->equality_constraints();
  123. llvm::ArrayRef<RewriteConstraint> rewrites =
  124. constraint->rewrite_constraints();
  125. if (!equals.empty() || !rewrites.empty()) {
  126. std::optional<Nonnull<const Witness*>> witness;
  127. if (constraint->self_binding()->impl_binding()) {
  128. witness = type_checker.MakeConstraintWitness(witnesses);
  129. }
  130. Bindings local_bindings = bindings;
  131. local_bindings.Add(constraint->self_binding(), impl_type, witness);
  132. SingleStepEqualityContext equality_ctx(this);
  133. for (const auto& equal : equals) {
  134. auto it = equal.values.begin();
  135. Nonnull<const Value*> first =
  136. type_checker.Substitute(local_bindings, *it++);
  137. for (; it != equal.values.end(); ++it) {
  138. Nonnull<const Value*> current =
  139. type_checker.Substitute(local_bindings, *it);
  140. CARBON_RETURN_IF_ERROR(
  141. CheckEqualOrDiagnose(source_loc, equal.values.front(), first, *it,
  142. current, &equality_ctx));
  143. }
  144. }
  145. for (auto& rewrite : rewrites) {
  146. Nonnull<const Value*> constant =
  147. type_checker.Substitute(local_bindings, rewrite.constant);
  148. Nonnull<const Value*> value = type_checker.Substitute(
  149. local_bindings, rewrite.converted_replacement);
  150. CARBON_RETURN_IF_ERROR(CheckEqualOrDiagnose(
  151. source_loc, rewrite.constant, constant,
  152. rewrite.converted_replacement, value, &equality_ctx));
  153. }
  154. }
  155. return type_checker.MakeConstraintWitness(std::move(witnesses));
  156. }
  157. CARBON_FATAL() << "expected a constraint, not " << *constraint_type;
  158. }
  159. auto ImplScope::VisitEqualValues(
  160. Nonnull<const Value*> value,
  161. llvm::function_ref<bool(Nonnull<const Value*>)> visitor) const -> bool {
  162. for (Nonnull<const EqualityConstraint*> eq : equalities_) {
  163. if (!eq->VisitEqualValues(value, visitor)) {
  164. return false;
  165. }
  166. }
  167. for (Nonnull<const ImplScope*> parent : parent_scopes_) {
  168. if (!parent->VisitEqualValues(value, visitor)) {
  169. return false;
  170. }
  171. }
  172. return true;
  173. }
  174. auto ImplScope::ResolveInterface(Nonnull<const InterfaceType*> iface_type,
  175. Nonnull<const Value*> type,
  176. SourceLocation source_loc,
  177. const TypeChecker& type_checker) const
  178. -> ErrorOr<Nonnull<const Witness*>> {
  179. CARBON_ASSIGN_OR_RETURN(
  180. std::optional<Nonnull<const Witness*>> result,
  181. TryResolve(iface_type, type, source_loc, *this, type_checker));
  182. if (!result.has_value()) {
  183. return ProgramError(source_loc) << "could not find implementation of "
  184. << *iface_type << " for " << *type;
  185. }
  186. return *result;
  187. }
  188. // Combines the results of two impl lookups. In the event of a tie, arbitrarily
  189. // prefer `a` over `b`.
  190. static auto CombineResults(Nonnull<const InterfaceType*> iface_type,
  191. Nonnull<const Value*> type,
  192. SourceLocation source_loc,
  193. std::optional<Nonnull<const Witness*>> a,
  194. std::optional<Nonnull<const Witness*>> b)
  195. -> ErrorOr<std::optional<Nonnull<const Witness*>>> {
  196. // If only one lookup succeeded, return that.
  197. if (!b) {
  198. return a;
  199. }
  200. if (!a) {
  201. return b;
  202. }
  203. // If either of them was a symbolic result, then they'll end up being
  204. // equivalent. In that case, pick `a`.
  205. const auto* impl_a = dyn_cast<ImplWitness>(*a);
  206. const auto* impl_b = dyn_cast<ImplWitness>(*b);
  207. if (!impl_b) {
  208. return a;
  209. }
  210. if (!impl_a) {
  211. return b;
  212. }
  213. // If they refer to the same `impl` declaration, it doesn't matter which one
  214. // we pick, so we pick `a`.
  215. // TODO: Compare the identities of the `impl`s, not the declarations.
  216. if (&impl_a->declaration() == &impl_b->declaration()) {
  217. return a;
  218. }
  219. // TODO: Order the `impl`s based on type structure.
  220. return ProgramError(source_loc)
  221. << "ambiguous implementations of " << *iface_type << " for " << *type;
  222. }
  223. auto ImplScope::TryResolve(Nonnull<const InterfaceType*> iface_type,
  224. Nonnull<const Value*> type,
  225. SourceLocation source_loc,
  226. const ImplScope& original_scope,
  227. const TypeChecker& type_checker) const
  228. -> ErrorOr<std::optional<Nonnull<const Witness*>>> {
  229. CARBON_ASSIGN_OR_RETURN(
  230. std::optional<Nonnull<const Witness*>> result,
  231. ResolveHere(iface_type, type, source_loc, original_scope, type_checker));
  232. for (Nonnull<const ImplScope*> parent : parent_scopes_) {
  233. CARBON_ASSIGN_OR_RETURN(
  234. std::optional<Nonnull<const Witness*>> parent_result,
  235. parent->TryResolve(iface_type, type, source_loc, original_scope,
  236. type_checker));
  237. CARBON_ASSIGN_OR_RETURN(result, CombineResults(iface_type, type, source_loc,
  238. result, parent_result));
  239. }
  240. return result;
  241. }
  242. auto ImplScope::ResolveHere(Nonnull<const InterfaceType*> iface_type,
  243. Nonnull<const Value*> impl_type,
  244. SourceLocation source_loc,
  245. const ImplScope& original_scope,
  246. const TypeChecker& type_checker) const
  247. -> ErrorOr<std::optional<Nonnull<const Witness*>>> {
  248. std::optional<Nonnull<const Witness*>> result = std::nullopt;
  249. for (const Impl& impl : impls_) {
  250. std::optional<Nonnull<const Witness*>> m = type_checker.MatchImpl(
  251. *iface_type, impl_type, impl, original_scope, source_loc);
  252. CARBON_ASSIGN_OR_RETURN(
  253. result, CombineResults(iface_type, impl_type, source_loc, result, m));
  254. }
  255. return result;
  256. }
  257. // TODO: Add indentation when printing the parents.
  258. void ImplScope::Print(llvm::raw_ostream& out) const {
  259. out << "impls: ";
  260. llvm::ListSeparator sep;
  261. for (const Impl& impl : impls_) {
  262. out << sep << *(impl.type) << " as " << *(impl.interface);
  263. }
  264. for (Nonnull<const EqualityConstraint*> eq : equalities_) {
  265. out << sep;
  266. llvm::ListSeparator equal(" == ");
  267. for (Nonnull<const Value*> value : eq->values) {
  268. out << equal << *value;
  269. }
  270. }
  271. out << "\n";
  272. for (const Nonnull<const ImplScope*>& parent : parent_scopes_) {
  273. out << *parent;
  274. }
  275. }
  276. auto SingleStepEqualityContext::VisitEqualValues(
  277. Nonnull<const Value*> value,
  278. llvm::function_ref<bool(Nonnull<const Value*>)> visitor) const -> bool {
  279. return impl_scope_->VisitEqualValues(value, visitor);
  280. }
  281. } // namespace Carbon