impl_scope.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. // Diagnose that `a_evaluated != b_evaluated` for the purpose of an equality
  59. // constraint.
  60. static auto DiagnoseUnequalValues(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. -> Error {
  67. CARBON_CHECK(!ValueEqual(a_evaluated, b_evaluated, equality_ctx))
  68. << "expected unequal values";
  69. auto error = ProgramError(source_loc);
  70. error << "constraint requires that " << *a_written;
  71. if (!ValueEqual(a_written, a_evaluated, std::nullopt)) {
  72. error << " (with value " << *a_evaluated << ")";
  73. }
  74. error << " == " << *b_written;
  75. if (!ValueEqual(b_written, b_evaluated, std::nullopt)) {
  76. error << " (with value " << *b_evaluated << ")";
  77. }
  78. error << ", which is not known to be true";
  79. return std::move(error);
  80. }
  81. auto ImplScope::Resolve(Nonnull<const Value*> constraint_type,
  82. Nonnull<const Value*> impl_type,
  83. SourceLocation source_loc,
  84. const TypeChecker& type_checker,
  85. const Bindings& bindings) const
  86. -> ErrorOr<Nonnull<const Witness*>> {
  87. CARBON_ASSIGN_OR_RETURN(
  88. std::optional<Nonnull<const Witness*>> witness,
  89. TryResolve(constraint_type, impl_type, source_loc, type_checker, bindings,
  90. /*diagnose_missing_impl=*/true));
  91. CARBON_CHECK(witness) << "should have diagnosed missing impl";
  92. return *witness;
  93. }
  94. auto ImplScope::TryResolve(Nonnull<const Value*> constraint_type,
  95. Nonnull<const Value*> impl_type,
  96. SourceLocation source_loc,
  97. const TypeChecker& type_checker,
  98. const Bindings& bindings,
  99. bool diagnose_missing_impl) const
  100. -> ErrorOr<std::optional<Nonnull<const Witness*>>> {
  101. if (const auto* iface_type = dyn_cast<InterfaceType>(constraint_type)) {
  102. iface_type =
  103. cast<InterfaceType>(type_checker.Substitute(bindings, iface_type));
  104. return TryResolveInterface(iface_type, impl_type, source_loc, type_checker,
  105. diagnose_missing_impl);
  106. }
  107. if (const auto* constraint = dyn_cast<ConstraintType>(constraint_type)) {
  108. std::vector<Nonnull<const Witness*>> witnesses;
  109. for (auto impl : constraint->impl_constraints()) {
  110. // Note that later impl constraints can refer to earlier impl constraints
  111. // via impl bindings. For example, in
  112. // `C where .Self.AssocType is D`,
  113. // ... the `.Self.AssocType is D` constraint refers to the `.Self is C`
  114. // constraint when naming `AssocType`. So incrementally build up a
  115. // partial constraint witness as we go.
  116. std::optional<Nonnull<const Witness*>> witness;
  117. if (constraint->self_binding()->impl_binding()) {
  118. // Note, this is a partial impl binding covering only the impl
  119. // constraints that we've already seen. Earlier impl constraints should
  120. // not be able to refer to impl bindings for later impl constraints.
  121. witness = type_checker.MakeConstraintWitness(witnesses);
  122. }
  123. Bindings local_bindings = bindings;
  124. local_bindings.Add(constraint->self_binding(), impl_type, witness);
  125. CARBON_ASSIGN_OR_RETURN(
  126. std::optional<Nonnull<const Witness*>> result,
  127. TryResolveInterface(
  128. cast<InterfaceType>(
  129. type_checker.Substitute(local_bindings, impl.interface)),
  130. type_checker.Substitute(local_bindings, impl.type), source_loc,
  131. type_checker, diagnose_missing_impl));
  132. if (!result) {
  133. return {std::nullopt};
  134. }
  135. witnesses.push_back(*result);
  136. }
  137. // Check that all intrinsic, equality, and rewrite constraints
  138. // are satisfied in this scope.
  139. llvm::ArrayRef<IntrinsicConstraint> intrinsics =
  140. constraint->intrinsic_constraints();
  141. llvm::ArrayRef<EqualityConstraint> equals =
  142. constraint->equality_constraints();
  143. llvm::ArrayRef<RewriteConstraint> rewrites =
  144. constraint->rewrite_constraints();
  145. if (!intrinsics.empty() || !equals.empty() || !rewrites.empty()) {
  146. std::optional<Nonnull<const Witness*>> witness;
  147. if (constraint->self_binding()->impl_binding()) {
  148. witness = type_checker.MakeConstraintWitness(witnesses);
  149. }
  150. Bindings local_bindings = bindings;
  151. local_bindings.Add(constraint->self_binding(), impl_type, witness);
  152. SingleStepEqualityContext equality_ctx(this);
  153. for (const auto& intrinsic : intrinsics) {
  154. IntrinsicConstraint converted = {
  155. .type = type_checker.Substitute(local_bindings, intrinsic.type),
  156. .kind = intrinsic.kind,
  157. .arguments = {}};
  158. converted.arguments.reserve(intrinsic.arguments.size());
  159. for (Nonnull<const Value*> argument : intrinsic.arguments) {
  160. converted.arguments.push_back(
  161. type_checker.Substitute(local_bindings, argument));
  162. }
  163. if (!type_checker.IsIntrinsicConstraintSatisfied(converted, *this)) {
  164. if (!diagnose_missing_impl) {
  165. return {std::nullopt};
  166. }
  167. return ProgramError(source_loc)
  168. << "constraint requires that " << converted;
  169. }
  170. }
  171. for (const auto& equal : equals) {
  172. auto it = equal.values.begin();
  173. Nonnull<const Value*> first =
  174. type_checker.Substitute(local_bindings, *it++);
  175. for (; it != equal.values.end(); ++it) {
  176. Nonnull<const Value*> current =
  177. type_checker.Substitute(local_bindings, *it);
  178. if (!ValueEqual(first, current, &equality_ctx)) {
  179. if (!diagnose_missing_impl) {
  180. return {std::nullopt};
  181. }
  182. return DiagnoseUnequalValues(source_loc, equal.values.front(),
  183. first, *it, current, &equality_ctx);
  184. }
  185. }
  186. }
  187. for (const auto& rewrite : rewrites) {
  188. Nonnull<const Value*> constant =
  189. type_checker.Substitute(local_bindings, rewrite.constant);
  190. Nonnull<const Value*> value = type_checker.Substitute(
  191. local_bindings, rewrite.converted_replacement);
  192. if (!ValueEqual(constant, value, &equality_ctx)) {
  193. if (!diagnose_missing_impl) {
  194. return {std::nullopt};
  195. }
  196. return DiagnoseUnequalValues(source_loc, rewrite.constant, constant,
  197. rewrite.converted_replacement, value,
  198. &equality_ctx);
  199. }
  200. }
  201. }
  202. return {type_checker.MakeConstraintWitness(std::move(witnesses))};
  203. }
  204. CARBON_FATAL() << "expected a constraint, not " << *constraint_type;
  205. }
  206. auto ImplScope::VisitEqualValues(
  207. Nonnull<const Value*> value,
  208. llvm::function_ref<bool(Nonnull<const Value*>)> visitor) const -> bool {
  209. for (Nonnull<const EqualityConstraint*> eq : equalities_) {
  210. if (!eq->VisitEqualValues(value, visitor)) {
  211. return false;
  212. }
  213. }
  214. for (Nonnull<const ImplScope*> parent : parent_scopes_) {
  215. if (!parent->VisitEqualValues(value, visitor)) {
  216. return false;
  217. }
  218. }
  219. return true;
  220. }
  221. auto ImplScope::TryResolveInterface(Nonnull<const InterfaceType*> iface_type,
  222. Nonnull<const Value*> type,
  223. SourceLocation source_loc,
  224. const TypeChecker& type_checker,
  225. bool diagnose_missing_impl) const
  226. -> ErrorOr<std::optional<Nonnull<const Witness*>>> {
  227. CARBON_ASSIGN_OR_RETURN(
  228. std::optional<Nonnull<const Witness*>> result,
  229. TryResolveInterfaceRecursively(iface_type, type, source_loc, *this,
  230. type_checker));
  231. if (!result.has_value() && diagnose_missing_impl) {
  232. return ProgramError(source_loc) << "could not find implementation of "
  233. << *iface_type << " for " << *type;
  234. }
  235. return result;
  236. }
  237. // Combines the results of two impl lookups. In the event of a tie, arbitrarily
  238. // prefer `a` over `b`.
  239. static auto CombineResults(Nonnull<const InterfaceType*> iface_type,
  240. Nonnull<const Value*> type,
  241. SourceLocation source_loc,
  242. std::optional<Nonnull<const Witness*>> a,
  243. std::optional<Nonnull<const Witness*>> b)
  244. -> ErrorOr<std::optional<Nonnull<const Witness*>>> {
  245. // If only one lookup succeeded, return that.
  246. if (!b) {
  247. return a;
  248. }
  249. if (!a) {
  250. return b;
  251. }
  252. // If either of them was a symbolic result, then they'll end up being
  253. // equivalent. In that case, pick `a`.
  254. const auto* impl_a = dyn_cast<ImplWitness>(*a);
  255. const auto* impl_b = dyn_cast<ImplWitness>(*b);
  256. if (!impl_b) {
  257. return a;
  258. }
  259. if (!impl_a) {
  260. return b;
  261. }
  262. // If they refer to the same `impl` declaration, it doesn't matter which one
  263. // we pick, so we pick `a`.
  264. // TODO: Compare the identities of the `impl`s, not the declarations.
  265. if (&impl_a->declaration() == &impl_b->declaration()) {
  266. return a;
  267. }
  268. // TODO: Order the `impl`s based on type structure.
  269. // If the declarations appear in the same `match_first` block, whichever
  270. // appears first wins.
  271. // TODO: Once we support an impl being declared more than once, we will need
  272. // to check this more carefully.
  273. if (impl_a->declaration().match_first() &&
  274. impl_a->declaration().match_first() ==
  275. impl_b->declaration().match_first()) {
  276. for (const auto* impl : (*impl_a->declaration().match_first())->impls()) {
  277. if (impl == &impl_a->declaration()) {
  278. return a;
  279. }
  280. if (impl == &impl_b->declaration()) {
  281. return b;
  282. }
  283. }
  284. }
  285. return ProgramError(source_loc)
  286. << "ambiguous implementations of " << *iface_type << " for " << *type;
  287. }
  288. auto ImplScope::TryResolveInterfaceRecursively(
  289. Nonnull<const InterfaceType*> iface_type, Nonnull<const Value*> type,
  290. SourceLocation source_loc, const ImplScope& original_scope,
  291. const TypeChecker& type_checker) const
  292. -> ErrorOr<std::optional<Nonnull<const Witness*>>> {
  293. CARBON_ASSIGN_OR_RETURN(
  294. std::optional<Nonnull<const Witness*>> result,
  295. TryResolveInterfaceHere(iface_type, type, source_loc, original_scope,
  296. type_checker));
  297. for (Nonnull<const ImplScope*> parent : parent_scopes_) {
  298. CARBON_ASSIGN_OR_RETURN(
  299. std::optional<Nonnull<const Witness*>> parent_result,
  300. parent->TryResolveInterfaceRecursively(iface_type, type, source_loc,
  301. original_scope, type_checker));
  302. CARBON_ASSIGN_OR_RETURN(result, CombineResults(iface_type, type, source_loc,
  303. result, parent_result));
  304. }
  305. return result;
  306. }
  307. auto ImplScope::TryResolveInterfaceHere(
  308. Nonnull<const InterfaceType*> iface_type, Nonnull<const Value*> impl_type,
  309. SourceLocation source_loc, const ImplScope& original_scope,
  310. const TypeChecker& type_checker) const
  311. -> ErrorOr<std::optional<Nonnull<const Witness*>>> {
  312. std::optional<Nonnull<const Witness*>> result = std::nullopt;
  313. for (const Impl& impl : impls_) {
  314. CARBON_ASSIGN_OR_RETURN(std::optional<Nonnull<const Witness*>> m,
  315. type_checker.MatchImpl(*iface_type, impl_type, impl,
  316. original_scope, source_loc));
  317. CARBON_ASSIGN_OR_RETURN(
  318. result, CombineResults(iface_type, impl_type, source_loc, result, m));
  319. }
  320. return result;
  321. }
  322. // TODO: Add indentation when printing the parents.
  323. void ImplScope::Print(llvm::raw_ostream& out) const {
  324. out << "impls: ";
  325. llvm::ListSeparator sep;
  326. for (const Impl& impl : impls_) {
  327. out << sep << *(impl.type) << " as " << *(impl.interface);
  328. }
  329. for (Nonnull<const EqualityConstraint*> eq : equalities_) {
  330. out << sep;
  331. llvm::ListSeparator equal(" == ");
  332. for (Nonnull<const Value*> value : eq->values) {
  333. out << equal << *value;
  334. }
  335. }
  336. out << "\n";
  337. for (const Nonnull<const ImplScope*>& parent : parent_scopes_) {
  338. out << *parent;
  339. }
  340. }
  341. auto SingleStepEqualityContext::VisitEqualValues(
  342. Nonnull<const Value*> value,
  343. llvm::function_ref<bool(Nonnull<const Value*>)> visitor) const -> bool {
  344. return impl_scope_->VisitEqualValues(value, visitor);
  345. }
  346. } // namespace Carbon