impl_scope.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. iface_type =
  112. cast<InterfaceType>(type_checker.Substitute(bindings, iface_type));
  113. return TryResolveInterface(iface_type, impl_type, source_loc, type_checker,
  114. diagnose_missing_impl);
  115. }
  116. if (const auto* constraint = dyn_cast<ConstraintType>(constraint_type)) {
  117. std::vector<Nonnull<const Witness*>> witnesses;
  118. for (auto impl : constraint->impl_constraints()) {
  119. // Note that later impl constraints can refer to earlier impl constraints
  120. // via impl bindings. For example, in
  121. // `C where .Self.AssocType is D`,
  122. // ... the `.Self.AssocType is D` constraint refers to the `.Self is C`
  123. // constraint when naming `AssocType`. So incrementally build up a
  124. // partial constraint witness as we go.
  125. std::optional<Nonnull<const Witness*>> witness;
  126. if (constraint->self_binding()->impl_binding()) {
  127. // Note, this is a partial impl binding covering only the impl
  128. // constraints that we've already seen. Earlier impl constraints should
  129. // not be able to refer to impl bindings for later impl constraints.
  130. witness = type_checker.MakeConstraintWitness(witnesses);
  131. }
  132. Bindings local_bindings = bindings;
  133. local_bindings.Add(constraint->self_binding(), impl_type, witness);
  134. CARBON_ASSIGN_OR_RETURN(
  135. std::optional<Nonnull<const Witness*>> result,
  136. TryResolveInterface(
  137. cast<InterfaceType>(
  138. type_checker.Substitute(local_bindings, impl.interface)),
  139. type_checker.Substitute(local_bindings, impl.type), source_loc,
  140. type_checker, diagnose_missing_impl));
  141. if (!result) {
  142. return {std::nullopt};
  143. }
  144. witnesses.push_back(*result);
  145. }
  146. // Check that all intrinsic, equality, and rewrite constraints
  147. // are satisfied in this scope.
  148. llvm::ArrayRef<IntrinsicConstraint> intrinsics =
  149. constraint->intrinsic_constraints();
  150. llvm::ArrayRef<EqualityConstraint> equals =
  151. constraint->equality_constraints();
  152. llvm::ArrayRef<RewriteConstraint> rewrites =
  153. constraint->rewrite_constraints();
  154. if (!intrinsics.empty() || !equals.empty() || !rewrites.empty()) {
  155. std::optional<Nonnull<const Witness*>> witness;
  156. if (constraint->self_binding()->impl_binding()) {
  157. witness = type_checker.MakeConstraintWitness(witnesses);
  158. }
  159. Bindings local_bindings = bindings;
  160. local_bindings.Add(constraint->self_binding(), impl_type, witness);
  161. SingleStepEqualityContext equality_ctx(this);
  162. for (const auto& intrinsic : intrinsics) {
  163. IntrinsicConstraint converted = {
  164. .type = type_checker.Substitute(local_bindings, intrinsic.type),
  165. .kind = intrinsic.kind,
  166. .arguments = {}};
  167. converted.arguments.reserve(intrinsic.arguments.size());
  168. for (Nonnull<const Value*> argument : intrinsic.arguments) {
  169. converted.arguments.push_back(
  170. type_checker.Substitute(local_bindings, argument));
  171. }
  172. if (!type_checker.IsIntrinsicConstraintSatisfied(converted, *this)) {
  173. if (!diagnose_missing_impl) {
  174. return {std::nullopt};
  175. }
  176. return ProgramError(source_loc)
  177. << "constraint requires that " << converted;
  178. }
  179. }
  180. for (const auto& equal : equals) {
  181. auto it = equal.values.begin();
  182. Nonnull<const Value*> first =
  183. type_checker.Substitute(local_bindings, *it++);
  184. for (; it != equal.values.end(); ++it) {
  185. Nonnull<const Value*> current =
  186. type_checker.Substitute(local_bindings, *it);
  187. if (!ValueEqual(first, current, &equality_ctx)) {
  188. if (!diagnose_missing_impl) {
  189. return {std::nullopt};
  190. }
  191. return DiagnoseUnequalValues(source_loc, equal.values.front(),
  192. first, *it, current, &equality_ctx);
  193. }
  194. }
  195. }
  196. for (const auto& rewrite : rewrites) {
  197. Nonnull<const Value*> constant =
  198. type_checker.Substitute(local_bindings, rewrite.constant);
  199. Nonnull<const Value*> value = type_checker.Substitute(
  200. local_bindings, rewrite.converted_replacement);
  201. if (!ValueEqual(constant, value, &equality_ctx)) {
  202. if (!diagnose_missing_impl) {
  203. return {std::nullopt};
  204. }
  205. return DiagnoseUnequalValues(source_loc, rewrite.constant, constant,
  206. rewrite.converted_replacement, value,
  207. &equality_ctx);
  208. }
  209. }
  210. }
  211. return {type_checker.MakeConstraintWitness(std::move(witnesses))};
  212. }
  213. CARBON_FATAL() << "expected a constraint, not " << *constraint_type;
  214. }
  215. auto ImplScope::VisitEqualValues(
  216. Nonnull<const Value*> value,
  217. llvm::function_ref<bool(Nonnull<const Value*>)> visitor) const -> bool {
  218. for (Nonnull<const EqualityConstraint*> eq : equalities_) {
  219. if (!eq->VisitEqualValues(value, visitor)) {
  220. return false;
  221. }
  222. }
  223. if (parent_scope_ && !(*parent_scope_)->VisitEqualValues(value, visitor)) {
  224. return false;
  225. }
  226. return true;
  227. }
  228. auto ImplScope::TryResolveInterface(Nonnull<const InterfaceType*> iface_type,
  229. Nonnull<const Value*> type,
  230. SourceLocation source_loc,
  231. const TypeChecker& type_checker,
  232. bool diagnose_missing_impl) const
  233. -> ErrorOr<std::optional<Nonnull<const Witness*>>> {
  234. CARBON_ASSIGN_OR_RETURN(
  235. std::optional<ResolveResult> result,
  236. TryResolveInterfaceRecursively(iface_type, type, source_loc, *this,
  237. type_checker));
  238. if (!result.has_value() && diagnose_missing_impl) {
  239. return ProgramError(source_loc) << "could not find implementation of "
  240. << *iface_type << " for " << *type;
  241. }
  242. return result ? std::optional(result->witness) : std::nullopt;
  243. }
  244. // Do these two witnesses refer to `impl` declarations in the same
  245. // `match_first` block?
  246. static auto InSameMatchFirst(Nonnull<const Witness*> a,
  247. Nonnull<const Witness*> b) -> bool {
  248. const auto* impl_a = dyn_cast<ImplWitness>(a);
  249. const auto* impl_b = dyn_cast<ImplWitness>(b);
  250. if (!impl_b || !impl_b) {
  251. return false;
  252. }
  253. // TODO: Once we support an impl being declared more than once, we will need
  254. // to check this more carefully.
  255. return impl_a->declaration().match_first() &&
  256. impl_a->declaration().match_first() ==
  257. impl_b->declaration().match_first();
  258. }
  259. // Determine whether this result is definitely right -- that there can be no
  260. // specialization that would give a better match.
  261. static auto IsEffectivelyFinal(ImplScope::ResolveResult result) -> bool {
  262. // TODO: Once we support 'final', check whether this is a final impl
  263. // declaration if it's parameterized.
  264. return result.impl->deduced.empty();
  265. }
  266. // Combines the results of two impl lookups. In the event of a tie, arbitrarily
  267. // prefer `a` over `b`.
  268. static auto CombineResults(Nonnull<const InterfaceType*> iface_type,
  269. Nonnull<const Value*> type,
  270. SourceLocation source_loc,
  271. std::optional<ImplScope::ResolveResult> a,
  272. std::optional<ImplScope::ResolveResult> b)
  273. -> ErrorOr<std::optional<ImplScope::ResolveResult>> {
  274. // If only one lookup succeeded, return that.
  275. if (!b) {
  276. return a;
  277. }
  278. if (!a) {
  279. return b;
  280. }
  281. // If exactly one of them is effectively final, prefer that result.
  282. bool a_is_final = IsEffectivelyFinal(*a);
  283. bool b_is_final = IsEffectivelyFinal(*b);
  284. if (a_is_final && !b_is_final) {
  285. return a;
  286. } else if (b_is_final && !a_is_final) {
  287. return b;
  288. }
  289. const auto* impl_a = dyn_cast<ImplWitness>(a->witness);
  290. const auto* impl_b = dyn_cast<ImplWitness>(b->witness);
  291. // If both are effectively final, prefer an impl declaration over a
  292. // symbolic ImplBinding, because we get more information from the impl
  293. // declaration. If they're both symbolic, arbitrarily pick a.
  294. if (a_is_final && b_is_final) {
  295. if (!impl_b) {
  296. return a;
  297. }
  298. if (!impl_a) {
  299. return b;
  300. }
  301. }
  302. CARBON_CHECK(impl_a && impl_b) << "non-final impl should not be symbolic";
  303. // At this point, we're comparing two `impl` declarations, and either they're
  304. // both final or neither of them is.
  305. // TODO: We should reject the case where both are final when checking their
  306. // declarations, but we don't do so yet, so for now we report it as an
  307. // ambiguity.
  308. //
  309. // If they refer to the same `impl` declaration, it doesn't matter which one
  310. // we pick, so we pick `a`.
  311. // TODO: Compare the identities of the `impl`s, not the declarations.
  312. if (&impl_a->declaration() == &impl_b->declaration()) {
  313. return a;
  314. }
  315. return ProgramError(source_loc)
  316. << "ambiguous implementations of " << *iface_type << " for " << *type;
  317. }
  318. auto ImplScope::TryResolveInterfaceRecursively(
  319. Nonnull<const InterfaceType*> iface_type, Nonnull<const Value*> type,
  320. SourceLocation source_loc, const ImplScope& original_scope,
  321. const TypeChecker& type_checker) const
  322. -> ErrorOr<std::optional<ResolveResult>> {
  323. CARBON_ASSIGN_OR_RETURN(
  324. std::optional<ResolveResult> result,
  325. TryResolveInterfaceHere(iface_type, type, source_loc, original_scope,
  326. type_checker));
  327. if (parent_scope_) {
  328. CARBON_ASSIGN_OR_RETURN(
  329. std::optional<ResolveResult> parent_result,
  330. (*parent_scope_)
  331. ->TryResolveInterfaceRecursively(iface_type, type, source_loc,
  332. original_scope, type_checker));
  333. CARBON_ASSIGN_OR_RETURN(result, CombineResults(iface_type, type, source_loc,
  334. result, parent_result));
  335. }
  336. return result;
  337. }
  338. auto ImplScope::TryResolveInterfaceHere(
  339. Nonnull<const InterfaceType*> iface_type, Nonnull<const Value*> impl_type,
  340. SourceLocation source_loc, const ImplScope& original_scope,
  341. const TypeChecker& type_checker) const
  342. -> ErrorOr<std::optional<ResolveResult>> {
  343. std::optional<ResolveResult> result = std::nullopt;
  344. for (const Impl& impl : impls_) {
  345. // If we've passed the final impl with a sort key matching our best impl,
  346. // all further impls are worse and don't need to be checked.
  347. if (result && result->impl->sort_key < impl.sort_key) {
  348. break;
  349. }
  350. // If this impl appears later in the same match_first block as our best
  351. // result, we should not consider it.
  352. //
  353. // TODO: This should apply transitively: if we have
  354. // match_first { impl a; impl b; }
  355. // match_first { impl b; impl c; }
  356. // then we should not consider c once we match a. For now, because each
  357. // impl is only declared once, this is not a problem.
  358. if (result && InSameMatchFirst(result->impl->witness, impl.witness)) {
  359. continue;
  360. }
  361. // Try matching this impl against our query.
  362. CARBON_ASSIGN_OR_RETURN(std::optional<Nonnull<const Witness*>> witness,
  363. type_checker.MatchImpl(*iface_type, impl_type, impl,
  364. original_scope, source_loc));
  365. if (witness) {
  366. CARBON_ASSIGN_OR_RETURN(
  367. result,
  368. CombineResults(iface_type, impl_type, source_loc, result,
  369. ResolveResult{.impl = &impl, .witness = *witness}));
  370. }
  371. }
  372. return result;
  373. }
  374. // TODO: Add indentation when printing the parents.
  375. void ImplScope::Print(llvm::raw_ostream& out) const {
  376. out << "impls: ";
  377. llvm::ListSeparator sep;
  378. for (const Impl& impl : impls_) {
  379. out << sep << *(impl.type) << " as " << *(impl.interface);
  380. if (impl.sort_key) {
  381. out << " " << *impl.sort_key;
  382. }
  383. }
  384. for (Nonnull<const EqualityConstraint*> eq : equalities_) {
  385. out << sep;
  386. llvm::ListSeparator equal(" == ");
  387. for (Nonnull<const Value*> value : eq->values) {
  388. out << equal << *value;
  389. }
  390. }
  391. out << "\n";
  392. if (parent_scope_) {
  393. out << **parent_scope_;
  394. }
  395. }
  396. auto SingleStepEqualityContext::VisitEqualValues(
  397. Nonnull<const Value*> value,
  398. llvm::function_ref<bool(Nonnull<const Value*>)> visitor) const -> bool {
  399. return impl_scope_->VisitEqualValues(value, visitor);
  400. }
  401. } // namespace Carbon