impl_scope.cpp 18 KB

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