impl_scope.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 intrinsic, equality, and rewrite constraints
  120. // are satisfied in this scope.
  121. llvm::ArrayRef<IntrinsicConstraint> intrinsics =
  122. constraint->intrinsic_constraints();
  123. llvm::ArrayRef<EqualityConstraint> equals =
  124. constraint->equality_constraints();
  125. llvm::ArrayRef<RewriteConstraint> rewrites =
  126. constraint->rewrite_constraints();
  127. if (!intrinsics.empty() || !equals.empty() || !rewrites.empty()) {
  128. std::optional<Nonnull<const Witness*>> witness;
  129. if (constraint->self_binding()->impl_binding()) {
  130. witness = type_checker.MakeConstraintWitness(witnesses);
  131. }
  132. Bindings local_bindings = bindings;
  133. local_bindings.Add(constraint->self_binding(), impl_type, witness);
  134. SingleStepEqualityContext equality_ctx(this);
  135. for (const auto& intrinsic : intrinsics) {
  136. IntrinsicConstraint converted = {
  137. .type = type_checker.Substitute(local_bindings, intrinsic.type),
  138. .kind = intrinsic.kind,
  139. .arguments = {}};
  140. converted.arguments.reserve(intrinsic.arguments.size());
  141. for (Nonnull<const Value*> argument : intrinsic.arguments) {
  142. converted.arguments.push_back(
  143. type_checker.Substitute(local_bindings, argument));
  144. }
  145. if (!type_checker.IsIntrinsicConstraintSatisfied(converted, *this)) {
  146. return ProgramError(source_loc)
  147. << "constraint requires that " << converted;
  148. }
  149. }
  150. for (const auto& equal : equals) {
  151. auto it = equal.values.begin();
  152. Nonnull<const Value*> first =
  153. type_checker.Substitute(local_bindings, *it++);
  154. for (; it != equal.values.end(); ++it) {
  155. Nonnull<const Value*> current =
  156. type_checker.Substitute(local_bindings, *it);
  157. CARBON_RETURN_IF_ERROR(
  158. CheckEqualOrDiagnose(source_loc, equal.values.front(), first, *it,
  159. current, &equality_ctx));
  160. }
  161. }
  162. for (const auto& rewrite : rewrites) {
  163. Nonnull<const Value*> constant =
  164. type_checker.Substitute(local_bindings, rewrite.constant);
  165. Nonnull<const Value*> value = type_checker.Substitute(
  166. local_bindings, rewrite.converted_replacement);
  167. CARBON_RETURN_IF_ERROR(CheckEqualOrDiagnose(
  168. source_loc, rewrite.constant, constant,
  169. rewrite.converted_replacement, value, &equality_ctx));
  170. }
  171. }
  172. return type_checker.MakeConstraintWitness(std::move(witnesses));
  173. }
  174. CARBON_FATAL() << "expected a constraint, not " << *constraint_type;
  175. }
  176. auto ImplScope::VisitEqualValues(
  177. Nonnull<const Value*> value,
  178. llvm::function_ref<bool(Nonnull<const Value*>)> visitor) const -> bool {
  179. for (Nonnull<const EqualityConstraint*> eq : equalities_) {
  180. if (!eq->VisitEqualValues(value, visitor)) {
  181. return false;
  182. }
  183. }
  184. for (Nonnull<const ImplScope*> parent : parent_scopes_) {
  185. if (!parent->VisitEqualValues(value, visitor)) {
  186. return false;
  187. }
  188. }
  189. return true;
  190. }
  191. auto ImplScope::ResolveInterface(Nonnull<const InterfaceType*> iface_type,
  192. Nonnull<const Value*> type,
  193. SourceLocation source_loc,
  194. const TypeChecker& type_checker) const
  195. -> ErrorOr<Nonnull<const Witness*>> {
  196. CARBON_ASSIGN_OR_RETURN(
  197. std::optional<Nonnull<const Witness*>> result,
  198. TryResolve(iface_type, type, source_loc, *this, type_checker));
  199. if (!result.has_value()) {
  200. return ProgramError(source_loc) << "could not find implementation of "
  201. << *iface_type << " for " << *type;
  202. }
  203. return *result;
  204. }
  205. // Combines the results of two impl lookups. In the event of a tie, arbitrarily
  206. // prefer `a` over `b`.
  207. static auto CombineResults(Nonnull<const InterfaceType*> iface_type,
  208. Nonnull<const Value*> type,
  209. SourceLocation source_loc,
  210. std::optional<Nonnull<const Witness*>> a,
  211. std::optional<Nonnull<const Witness*>> b)
  212. -> ErrorOr<std::optional<Nonnull<const Witness*>>> {
  213. // If only one lookup succeeded, return that.
  214. if (!b) {
  215. return a;
  216. }
  217. if (!a) {
  218. return b;
  219. }
  220. // If either of them was a symbolic result, then they'll end up being
  221. // equivalent. In that case, pick `a`.
  222. const auto* impl_a = dyn_cast<ImplWitness>(*a);
  223. const auto* impl_b = dyn_cast<ImplWitness>(*b);
  224. if (!impl_b) {
  225. return a;
  226. }
  227. if (!impl_a) {
  228. return b;
  229. }
  230. // If they refer to the same `impl` declaration, it doesn't matter which one
  231. // we pick, so we pick `a`.
  232. // TODO: Compare the identities of the `impl`s, not the declarations.
  233. if (&impl_a->declaration() == &impl_b->declaration()) {
  234. return a;
  235. }
  236. // TODO: Order the `impl`s based on type structure.
  237. // If the declarations appear in the same `match_first` block, whichever
  238. // appears first wins.
  239. // TODO: Once we support an impl being declared more than once, we will need
  240. // to check this more carefully.
  241. if (impl_a->declaration().match_first() &&
  242. impl_a->declaration().match_first() ==
  243. impl_b->declaration().match_first()) {
  244. for (const auto* impl : (*impl_a->declaration().match_first())->impls()) {
  245. if (impl == &impl_a->declaration()) {
  246. return a;
  247. }
  248. if (impl == &impl_b->declaration()) {
  249. return b;
  250. }
  251. }
  252. }
  253. return ProgramError(source_loc)
  254. << "ambiguous implementations of " << *iface_type << " for " << *type;
  255. }
  256. auto ImplScope::TryResolve(Nonnull<const InterfaceType*> iface_type,
  257. Nonnull<const Value*> type,
  258. SourceLocation source_loc,
  259. const ImplScope& original_scope,
  260. const TypeChecker& type_checker) const
  261. -> ErrorOr<std::optional<Nonnull<const Witness*>>> {
  262. CARBON_ASSIGN_OR_RETURN(
  263. std::optional<Nonnull<const Witness*>> result,
  264. ResolveHere(iface_type, type, source_loc, original_scope, type_checker));
  265. for (Nonnull<const ImplScope*> parent : parent_scopes_) {
  266. CARBON_ASSIGN_OR_RETURN(
  267. std::optional<Nonnull<const Witness*>> parent_result,
  268. parent->TryResolve(iface_type, type, source_loc, original_scope,
  269. type_checker));
  270. CARBON_ASSIGN_OR_RETURN(result, CombineResults(iface_type, type, source_loc,
  271. result, parent_result));
  272. }
  273. return result;
  274. }
  275. auto ImplScope::ResolveHere(Nonnull<const InterfaceType*> iface_type,
  276. Nonnull<const Value*> impl_type,
  277. SourceLocation source_loc,
  278. const ImplScope& original_scope,
  279. const TypeChecker& type_checker) const
  280. -> ErrorOr<std::optional<Nonnull<const Witness*>>> {
  281. std::optional<Nonnull<const Witness*>> result = std::nullopt;
  282. for (const Impl& impl : impls_) {
  283. std::optional<Nonnull<const Witness*>> m = type_checker.MatchImpl(
  284. *iface_type, impl_type, impl, original_scope, source_loc);
  285. CARBON_ASSIGN_OR_RETURN(
  286. result, CombineResults(iface_type, impl_type, source_loc, result, m));
  287. }
  288. return result;
  289. }
  290. // TODO: Add indentation when printing the parents.
  291. void ImplScope::Print(llvm::raw_ostream& out) const {
  292. out << "impls: ";
  293. llvm::ListSeparator sep;
  294. for (const Impl& impl : impls_) {
  295. out << sep << *(impl.type) << " as " << *(impl.interface);
  296. }
  297. for (Nonnull<const EqualityConstraint*> eq : equalities_) {
  298. out << sep;
  299. llvm::ListSeparator equal(" == ");
  300. for (Nonnull<const Value*> value : eq->values) {
  301. out << equal << *value;
  302. }
  303. }
  304. out << "\n";
  305. for (const Nonnull<const ImplScope*>& parent : parent_scopes_) {
  306. out << *parent;
  307. }
  308. }
  309. auto SingleStepEqualityContext::VisitEqualValues(
  310. Nonnull<const Value*> value,
  311. llvm::function_ref<bool(Nonnull<const Value*>)> visitor) const -> bool {
  312. return impl_scope_->VisitEqualValues(value, visitor);
  313. }
  314. } // namespace Carbon