rustc_trait_selection/traits/
coherence.rs

1//! See Rustc Dev Guide chapters on [trait-resolution] and [trait-specialization] for more info on
2//! how this works.
3//!
4//! [trait-resolution]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
5//! [trait-specialization]: https://rustc-dev-guide.rust-lang.org/traits/specialization.html
6
7use std::fmt::Debug;
8
9use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
10use rustc_errors::{Diag, EmissionGuarantee};
11use rustc_hir::def::DefKind;
12use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
13use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, TyCtxtInferExt};
14use rustc_infer::traits::PredicateObligations;
15use rustc_macros::{TypeFoldable, TypeVisitable};
16use rustc_middle::bug;
17use rustc_middle::traits::query::NoSolution;
18use rustc_middle::traits::solve::{CandidateSource, Certainty, Goal};
19use rustc_middle::traits::specialization_graph::OverlapMode;
20use rustc_middle::ty::fast_reject::DeepRejectCtxt;
21use rustc_middle::ty::{
22    self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
23};
24pub use rustc_next_trait_solver::coherence::*;
25use rustc_next_trait_solver::solve::SolverDelegateEvalExt;
26use rustc_span::{DUMMY_SP, Span, sym};
27use tracing::{debug, instrument, warn};
28
29use super::ObligationCtxt;
30use crate::error_reporting::traits::suggest_new_overflow_limit;
31use crate::infer::InferOk;
32use crate::solve::inspect::{InspectGoal, ProofTreeInferCtxtExt, ProofTreeVisitor};
33use crate::solve::{SolverDelegate, deeply_normalize_for_diagnostics, inspect};
34use crate::traits::query::evaluate_obligation::InferCtxtExt;
35use crate::traits::select::IntercrateAmbiguityCause;
36use crate::traits::{
37    FulfillmentErrorCode, NormalizeExt, Obligation, ObligationCause, PredicateObligation,
38    SelectionContext, SkipLeakCheck, util,
39};
40
41/// The "header" of an impl is everything outside the body: a Self type, a trait
42/// ref (in the case of a trait impl), and a set of predicates (from the
43/// bounds / where-clauses).
44#[derive(Clone, Debug, TypeFoldable, TypeVisitable)]
45pub struct ImplHeader<'tcx> {
46    pub impl_def_id: DefId,
47    pub impl_args: ty::GenericArgsRef<'tcx>,
48    pub self_ty: Ty<'tcx>,
49    pub trait_ref: Option<ty::TraitRef<'tcx>>,
50    pub predicates: Vec<ty::Predicate<'tcx>>,
51}
52
53pub struct OverlapResult<'tcx> {
54    pub impl_header: ImplHeader<'tcx>,
55    pub intercrate_ambiguity_causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
56
57    /// `true` if the overlap might've been permitted before the shift
58    /// to universes.
59    pub involves_placeholder: bool,
60
61    /// Used in the new solver to suggest increasing the recursion limit.
62    pub overflowing_predicates: Vec<ty::Predicate<'tcx>>,
63}
64
65pub fn add_placeholder_note<G: EmissionGuarantee>(err: &mut Diag<'_, G>) {
66    err.note(
67        "this behavior recently changed as a result of a bug fix; \
68         see rust-lang/rust#56105 for details",
69    );
70}
71
72pub(crate) fn suggest_increasing_recursion_limit<'tcx, G: EmissionGuarantee>(
73    tcx: TyCtxt<'tcx>,
74    err: &mut Diag<'_, G>,
75    overflowing_predicates: &[ty::Predicate<'tcx>],
76) {
77    for pred in overflowing_predicates {
78        err.note(format!("overflow evaluating the requirement `{}`", pred));
79    }
80
81    suggest_new_overflow_limit(tcx, err);
82}
83
84#[derive(Debug, Clone, Copy)]
85enum TrackAmbiguityCauses {
86    Yes,
87    No,
88}
89
90impl TrackAmbiguityCauses {
91    fn is_yes(self) -> bool {
92        match self {
93            TrackAmbiguityCauses::Yes => true,
94            TrackAmbiguityCauses::No => false,
95        }
96    }
97}
98
99/// If there are types that satisfy both impls, returns `Some`
100/// with a suitably-freshened `ImplHeader` with those types
101/// instantiated. Otherwise, returns `None`.
102#[instrument(skip(tcx, skip_leak_check), level = "debug")]
103pub fn overlapping_impls(
104    tcx: TyCtxt<'_>,
105    impl1_def_id: DefId,
106    impl2_def_id: DefId,
107    skip_leak_check: SkipLeakCheck,
108    overlap_mode: OverlapMode,
109) -> Option<OverlapResult<'_>> {
110    // Before doing expensive operations like entering an inference context, do
111    // a quick check via fast_reject to tell if the impl headers could possibly
112    // unify.
113    let drcx = DeepRejectCtxt::relate_infer_infer(tcx);
114    let impl1_ref = tcx.impl_trait_ref(impl1_def_id);
115    let impl2_ref = tcx.impl_trait_ref(impl2_def_id);
116    let may_overlap = match (impl1_ref, impl2_ref) {
117        (Some(a), Some(b)) => drcx.args_may_unify(a.skip_binder().args, b.skip_binder().args),
118        (None, None) => {
119            let self_ty1 = tcx.type_of(impl1_def_id).skip_binder();
120            let self_ty2 = tcx.type_of(impl2_def_id).skip_binder();
121            drcx.types_may_unify(self_ty1, self_ty2)
122        }
123        _ => bug!("unexpected impls: {impl1_def_id:?} {impl2_def_id:?}"),
124    };
125
126    if !may_overlap {
127        // Some types involved are definitely different, so the impls couldn't possibly overlap.
128        debug!("overlapping_impls: fast_reject early-exit");
129        return None;
130    }
131
132    if tcx.next_trait_solver_in_coherence() {
133        overlap(
134            tcx,
135            TrackAmbiguityCauses::Yes,
136            skip_leak_check,
137            impl1_def_id,
138            impl2_def_id,
139            overlap_mode,
140        )
141    } else {
142        let _overlap_with_bad_diagnostics = overlap(
143            tcx,
144            TrackAmbiguityCauses::No,
145            skip_leak_check,
146            impl1_def_id,
147            impl2_def_id,
148            overlap_mode,
149        )?;
150
151        // In the case where we detect an error, run the check again, but
152        // this time tracking intercrate ambiguity causes for better
153        // diagnostics. (These take time and can lead to false errors.)
154        let overlap = overlap(
155            tcx,
156            TrackAmbiguityCauses::Yes,
157            skip_leak_check,
158            impl1_def_id,
159            impl2_def_id,
160            overlap_mode,
161        )
162        .unwrap();
163        Some(overlap)
164    }
165}
166
167fn fresh_impl_header<'tcx>(infcx: &InferCtxt<'tcx>, impl_def_id: DefId) -> ImplHeader<'tcx> {
168    let tcx = infcx.tcx;
169    let impl_args = infcx.fresh_args_for_item(DUMMY_SP, impl_def_id);
170
171    ImplHeader {
172        impl_def_id,
173        impl_args,
174        self_ty: tcx.type_of(impl_def_id).instantiate(tcx, impl_args),
175        trait_ref: tcx.impl_trait_ref(impl_def_id).map(|i| i.instantiate(tcx, impl_args)),
176        predicates: tcx
177            .predicates_of(impl_def_id)
178            .instantiate(tcx, impl_args)
179            .iter()
180            .map(|(c, _)| c.as_predicate())
181            .collect(),
182    }
183}
184
185fn fresh_impl_header_normalized<'tcx>(
186    infcx: &InferCtxt<'tcx>,
187    param_env: ty::ParamEnv<'tcx>,
188    impl_def_id: DefId,
189) -> ImplHeader<'tcx> {
190    let header = fresh_impl_header(infcx, impl_def_id);
191
192    let InferOk { value: mut header, obligations } =
193        infcx.at(&ObligationCause::dummy(), param_env).normalize(header);
194
195    header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
196    header
197}
198
199/// Can both impl `a` and impl `b` be satisfied by a common type (including
200/// where-clauses)? If so, returns an `ImplHeader` that unifies the two impls.
201#[instrument(level = "debug", skip(tcx))]
202fn overlap<'tcx>(
203    tcx: TyCtxt<'tcx>,
204    track_ambiguity_causes: TrackAmbiguityCauses,
205    skip_leak_check: SkipLeakCheck,
206    impl1_def_id: DefId,
207    impl2_def_id: DefId,
208    overlap_mode: OverlapMode,
209) -> Option<OverlapResult<'tcx>> {
210    if overlap_mode.use_negative_impl() {
211        if impl_intersection_has_negative_obligation(tcx, impl1_def_id, impl2_def_id)
212            || impl_intersection_has_negative_obligation(tcx, impl2_def_id, impl1_def_id)
213        {
214            return None;
215        }
216    }
217
218    let infcx = tcx
219        .infer_ctxt()
220        .skip_leak_check(skip_leak_check.is_yes())
221        .with_next_trait_solver(tcx.next_trait_solver_in_coherence())
222        .build(TypingMode::Coherence);
223    let selcx = &mut SelectionContext::new(&infcx);
224    if track_ambiguity_causes.is_yes() {
225        selcx.enable_tracking_intercrate_ambiguity_causes();
226    }
227
228    // For the purposes of this check, we don't bring any placeholder
229    // types into scope; instead, we replace the generic types with
230    // fresh type variables, and hence we do our evaluations in an
231    // empty environment.
232    let param_env = ty::ParamEnv::empty();
233
234    let impl1_header = fresh_impl_header_normalized(selcx.infcx, param_env, impl1_def_id);
235    let impl2_header = fresh_impl_header_normalized(selcx.infcx, param_env, impl2_def_id);
236
237    // Equate the headers to find their intersection (the general type, with infer vars,
238    // that may apply both impls).
239    let mut obligations =
240        equate_impl_headers(selcx.infcx, param_env, &impl1_header, &impl2_header)?;
241    debug!("overlap: unification check succeeded");
242
243    obligations.extend(
244        [&impl1_header.predicates, &impl2_header.predicates].into_iter().flatten().map(
245            |&predicate| Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, predicate),
246        ),
247    );
248
249    let mut overflowing_predicates = Vec::new();
250    if overlap_mode.use_implicit_negative() {
251        match impl_intersection_has_impossible_obligation(selcx, &obligations) {
252            IntersectionHasImpossibleObligations::Yes => return None,
253            IntersectionHasImpossibleObligations::No { overflowing_predicates: p } => {
254                overflowing_predicates = p
255            }
256        }
257    }
258
259    // We toggle the `leak_check` by using `skip_leak_check` when constructing the
260    // inference context, so this may be a noop.
261    if infcx.leak_check(ty::UniverseIndex::ROOT, None).is_err() {
262        debug!("overlap: leak check failed");
263        return None;
264    }
265
266    let intercrate_ambiguity_causes = if !overlap_mode.use_implicit_negative() {
267        Default::default()
268    } else if infcx.next_trait_solver() {
269        compute_intercrate_ambiguity_causes(&infcx, &obligations)
270    } else {
271        selcx.take_intercrate_ambiguity_causes()
272    };
273
274    debug!("overlap: intercrate_ambiguity_causes={:#?}", intercrate_ambiguity_causes);
275    let involves_placeholder = infcx
276        .inner
277        .borrow_mut()
278        .unwrap_region_constraints()
279        .data()
280        .constraints
281        .iter()
282        .any(|c| c.0.involves_placeholders());
283
284    let mut impl_header = infcx.resolve_vars_if_possible(impl1_header);
285
286    // Deeply normalize the impl header for diagnostics, ignoring any errors if this fails.
287    if infcx.next_trait_solver() {
288        impl_header = deeply_normalize_for_diagnostics(&infcx, param_env, impl_header);
289    }
290
291    Some(OverlapResult {
292        impl_header,
293        intercrate_ambiguity_causes,
294        involves_placeholder,
295        overflowing_predicates,
296    })
297}
298
299#[instrument(level = "debug", skip(infcx), ret)]
300fn equate_impl_headers<'tcx>(
301    infcx: &InferCtxt<'tcx>,
302    param_env: ty::ParamEnv<'tcx>,
303    impl1: &ImplHeader<'tcx>,
304    impl2: &ImplHeader<'tcx>,
305) -> Option<PredicateObligations<'tcx>> {
306    let result =
307        match (impl1.trait_ref, impl2.trait_ref) {
308            (Some(impl1_ref), Some(impl2_ref)) => infcx
309                .at(&ObligationCause::dummy(), param_env)
310                .eq(DefineOpaqueTypes::Yes, impl1_ref, impl2_ref),
311            (None, None) => infcx.at(&ObligationCause::dummy(), param_env).eq(
312                DefineOpaqueTypes::Yes,
313                impl1.self_ty,
314                impl2.self_ty,
315            ),
316            _ => bug!("equate_impl_headers given mismatched impl kinds"),
317        };
318
319    result.map(|infer_ok| infer_ok.obligations).ok()
320}
321
322/// The result of [fn impl_intersection_has_impossible_obligation].
323#[derive(Debug)]
324enum IntersectionHasImpossibleObligations<'tcx> {
325    Yes,
326    No {
327        /// With `-Znext-solver=coherence`, some obligations may
328        /// fail if only the user increased the recursion limit.
329        ///
330        /// We return those obligations here and mention them in the
331        /// error message.
332        overflowing_predicates: Vec<ty::Predicate<'tcx>>,
333    },
334}
335
336/// Check if both impls can be satisfied by a common type by considering whether
337/// any of either impl's obligations is not known to hold.
338///
339/// For example, given these two impls:
340///     `impl From<MyLocalType> for Box<dyn Error>` (in my crate)
341///     `impl<E> From<E> for Box<dyn Error> where E: Error` (in libstd)
342///
343/// After replacing both impl headers with inference vars (which happens before
344/// this function is called), we get:
345///     `Box<dyn Error>: From<MyLocalType>`
346///     `Box<dyn Error>: From<?E>`
347///
348/// This gives us `?E = MyLocalType`. We then certainly know that `MyLocalType: Error`
349/// never holds in intercrate mode since a local impl does not exist, and a
350/// downstream impl cannot be added -- therefore can consider the intersection
351/// of the two impls above to be empty.
352///
353/// Importantly, this works even if there isn't a `impl !Error for MyLocalType`.
354#[instrument(level = "debug", skip(selcx), ret)]
355fn impl_intersection_has_impossible_obligation<'a, 'cx, 'tcx>(
356    selcx: &mut SelectionContext<'cx, 'tcx>,
357    obligations: &'a [PredicateObligation<'tcx>],
358) -> IntersectionHasImpossibleObligations<'tcx> {
359    let infcx = selcx.infcx;
360
361    if infcx.next_trait_solver() {
362        // A fast path optimization, try evaluating all goals with
363        // a very low recursion depth and bail if any of them don't
364        // hold.
365        if !obligations.iter().all(|o| {
366            <&SolverDelegate<'tcx>>::from(infcx)
367                .root_goal_may_hold_with_depth(8, Goal::new(infcx.tcx, o.param_env, o.predicate))
368        }) {
369            return IntersectionHasImpossibleObligations::Yes;
370        }
371
372        let ocx = ObligationCtxt::new(infcx);
373        ocx.register_obligations(obligations.iter().cloned());
374        let hard_errors = ocx.select_where_possible();
375        if !hard_errors.is_empty() {
376            assert!(
377                hard_errors.iter().all(|e| e.is_true_error()),
378                "should not have detected ambiguity during first pass"
379            );
380            return IntersectionHasImpossibleObligations::Yes;
381        }
382
383        // Make a new `ObligationCtxt` and re-prove the ambiguities with a richer
384        // `FulfillmentError`. This is so that we can detect overflowing obligations
385        // without needing to run the `BestObligation` visitor on true errors.
386        let ambiguities = ocx.into_pending_obligations();
387        let ocx = ObligationCtxt::new_with_diagnostics(infcx);
388        ocx.register_obligations(ambiguities);
389        let errors_and_ambiguities = ocx.select_all_or_error();
390        // We only care about the obligations that are *definitely* true errors.
391        // Ambiguities do not prove the disjointness of two impls.
392        let (errors, ambiguities): (Vec<_>, Vec<_>) =
393            errors_and_ambiguities.into_iter().partition(|error| error.is_true_error());
394        assert!(errors.is_empty(), "should not have ambiguities during second pass");
395
396        IntersectionHasImpossibleObligations::No {
397            overflowing_predicates: ambiguities
398                .into_iter()
399                .filter(|error| {
400                    matches!(error.code, FulfillmentErrorCode::Ambiguity { overflow: Some(true) })
401                })
402                .map(|e| infcx.resolve_vars_if_possible(e.obligation.predicate))
403                .collect(),
404        }
405    } else {
406        for obligation in obligations {
407            // We use `evaluate_root_obligation` to correctly track intercrate
408            // ambiguity clauses.
409            let evaluation_result = selcx.evaluate_root_obligation(obligation);
410
411            match evaluation_result {
412                Ok(result) => {
413                    if !result.may_apply() {
414                        return IntersectionHasImpossibleObligations::Yes;
415                    }
416                }
417                // If overflow occurs, we need to conservatively treat the goal as possibly holding,
418                // since there can be instantiations of this goal that don't overflow and result in
419                // success. While this isn't much of a problem in the old solver, since we treat overflow
420                // fatally, this still can be encountered: <https://github.com/rust-lang/rust/issues/105231>.
421                Err(_overflow) => {}
422            }
423        }
424
425        IntersectionHasImpossibleObligations::No { overflowing_predicates: Vec::new() }
426    }
427}
428
429/// Check if both impls can be satisfied by a common type by considering whether
430/// any of first impl's obligations is known not to hold *via a negative predicate*.
431///
432/// For example, given these two impls:
433///     `struct MyCustomBox<T: ?Sized>(Box<T>);`
434///     `impl From<&str> for MyCustomBox<dyn Error>` (in my crate)
435///     `impl<E> From<E> for MyCustomBox<dyn Error> where E: Error` (in my crate)
436///
437/// After replacing the second impl's header with inference vars, we get:
438///     `MyCustomBox<dyn Error>: From<&str>`
439///     `MyCustomBox<dyn Error>: From<?E>`
440///
441/// This gives us `?E = &str`. We then try to prove the first impl's predicates
442/// after negating, giving us `&str: !Error`. This is a negative impl provided by
443/// libstd, and therefore we can guarantee for certain that libstd will never add
444/// a positive impl for `&str: Error` (without it being a breaking change).
445fn impl_intersection_has_negative_obligation(
446    tcx: TyCtxt<'_>,
447    impl1_def_id: DefId,
448    impl2_def_id: DefId,
449) -> bool {
450    debug!("negative_impl(impl1_def_id={:?}, impl2_def_id={:?})", impl1_def_id, impl2_def_id);
451
452    // N.B. We need to unify impl headers *with* intercrate mode, even if proving negative predicates
453    // do not need intercrate mode enabled.
454    let ref infcx = tcx.infer_ctxt().with_next_trait_solver(true).build(TypingMode::Coherence);
455    let root_universe = infcx.universe();
456    assert_eq!(root_universe, ty::UniverseIndex::ROOT);
457
458    let impl1_header = fresh_impl_header(infcx, impl1_def_id);
459    let param_env =
460        ty::EarlyBinder::bind(tcx.param_env(impl1_def_id)).instantiate(tcx, impl1_header.impl_args);
461
462    let impl2_header = fresh_impl_header(infcx, impl2_def_id);
463
464    // Equate the headers to find their intersection (the general type, with infer vars,
465    // that may apply both impls).
466    let Some(equate_obligations) =
467        equate_impl_headers(infcx, param_env, &impl1_header, &impl2_header)
468    else {
469        return false;
470    };
471
472    // FIXME(with_negative_coherence): the infcx has constraints from equating
473    // the impl headers. We should use these constraints as assumptions, not as
474    // requirements, when proving the negated where clauses below.
475    drop(equate_obligations);
476    drop(infcx.take_registered_region_obligations());
477    drop(infcx.take_registered_region_assumptions());
478    drop(infcx.take_and_reset_region_constraints());
479
480    plug_infer_with_placeholders(
481        infcx,
482        root_universe,
483        (impl1_header.impl_args, impl2_header.impl_args),
484    );
485    let param_env = infcx.resolve_vars_if_possible(param_env);
486
487    util::elaborate(tcx, tcx.predicates_of(impl2_def_id).instantiate(tcx, impl2_header.impl_args))
488        .elaborate_sized()
489        .any(|(clause, _)| try_prove_negated_where_clause(infcx, clause, param_env))
490}
491
492fn plug_infer_with_placeholders<'tcx>(
493    infcx: &InferCtxt<'tcx>,
494    universe: ty::UniverseIndex,
495    value: impl TypeVisitable<TyCtxt<'tcx>>,
496) {
497    struct PlugInferWithPlaceholder<'a, 'tcx> {
498        infcx: &'a InferCtxt<'tcx>,
499        universe: ty::UniverseIndex,
500        var: ty::BoundVar,
501    }
502
503    impl<'tcx> PlugInferWithPlaceholder<'_, 'tcx> {
504        fn next_var(&mut self) -> ty::BoundVar {
505            let var = self.var;
506            self.var = self.var + 1;
507            var
508        }
509    }
510
511    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for PlugInferWithPlaceholder<'_, 'tcx> {
512        fn visit_ty(&mut self, ty: Ty<'tcx>) {
513            let ty = self.infcx.shallow_resolve(ty);
514            if ty.is_ty_var() {
515                let Ok(InferOk { value: (), obligations }) =
516                    self.infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
517                        // Comparing against a type variable never registers hidden types anyway
518                        DefineOpaqueTypes::Yes,
519                        ty,
520                        Ty::new_placeholder(
521                            self.infcx.tcx,
522                            ty::Placeholder {
523                                universe: self.universe,
524                                bound: ty::BoundTy {
525                                    var: self.next_var(),
526                                    kind: ty::BoundTyKind::Anon,
527                                },
528                            },
529                        ),
530                    )
531                else {
532                    bug!("we always expect to be able to plug an infer var with placeholder")
533                };
534                assert_eq!(obligations.len(), 0);
535            } else {
536                ty.super_visit_with(self);
537            }
538        }
539
540        fn visit_const(&mut self, ct: ty::Const<'tcx>) {
541            let ct = self.infcx.shallow_resolve_const(ct);
542            if ct.is_ct_infer() {
543                let Ok(InferOk { value: (), obligations }) =
544                    self.infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
545                        // The types of the constants are the same, so there is no hidden type
546                        // registration happening anyway.
547                        DefineOpaqueTypes::Yes,
548                        ct,
549                        ty::Const::new_placeholder(
550                            self.infcx.tcx,
551                            ty::Placeholder {
552                                universe: self.universe,
553                                bound: ty::BoundConst { var: self.next_var() },
554                            },
555                        ),
556                    )
557                else {
558                    bug!("we always expect to be able to plug an infer var with placeholder")
559                };
560                assert_eq!(obligations.len(), 0);
561            } else {
562                ct.super_visit_with(self);
563            }
564        }
565
566        fn visit_region(&mut self, r: ty::Region<'tcx>) {
567            if let ty::ReVar(vid) = r.kind() {
568                let r = self
569                    .infcx
570                    .inner
571                    .borrow_mut()
572                    .unwrap_region_constraints()
573                    .opportunistic_resolve_var(self.infcx.tcx, vid);
574                if r.is_var() {
575                    let Ok(InferOk { value: (), obligations }) =
576                        self.infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
577                            // Lifetimes don't contain opaque types (or any types for that matter).
578                            DefineOpaqueTypes::Yes,
579                            r,
580                            ty::Region::new_placeholder(
581                                self.infcx.tcx,
582                                ty::Placeholder {
583                                    universe: self.universe,
584                                    bound: ty::BoundRegion {
585                                        var: self.next_var(),
586                                        kind: ty::BoundRegionKind::Anon,
587                                    },
588                                },
589                            ),
590                        )
591                    else {
592                        bug!("we always expect to be able to plug an infer var with placeholder")
593                    };
594                    assert_eq!(obligations.len(), 0);
595                }
596            }
597        }
598    }
599
600    value.visit_with(&mut PlugInferWithPlaceholder { infcx, universe, var: ty::BoundVar::ZERO });
601}
602
603fn try_prove_negated_where_clause<'tcx>(
604    root_infcx: &InferCtxt<'tcx>,
605    clause: ty::Clause<'tcx>,
606    param_env: ty::ParamEnv<'tcx>,
607) -> bool {
608    let Some(negative_predicate) = clause.as_predicate().flip_polarity(root_infcx.tcx) else {
609        return false;
610    };
611
612    // N.B. We don't need to use intercrate mode here because we're trying to prove
613    // the *existence* of a negative goal, not the non-existence of a positive goal.
614    // Without this, we over-eagerly register coherence ambiguity candidates when
615    // impl candidates do exist.
616    // FIXME(#132279): `TypingMode::non_body_analysis` is a bit questionable here as it
617    // would cause us to reveal opaque types to leak their auto traits.
618    let ref infcx = root_infcx.fork_with_typing_mode(TypingMode::non_body_analysis());
619    let ocx = ObligationCtxt::new(infcx);
620    ocx.register_obligation(Obligation::new(
621        infcx.tcx,
622        ObligationCause::dummy(),
623        param_env,
624        negative_predicate,
625    ));
626    if !ocx.select_all_or_error().is_empty() {
627        return false;
628    }
629
630    // FIXME: We could use the assumed_wf_types from both impls, I think,
631    // if that wasn't implemented just for LocalDefId, and we'd need to do
632    // the normalization ourselves since this is totally fallible...
633    let errors = ocx.resolve_regions(CRATE_DEF_ID, param_env, []);
634    if !errors.is_empty() {
635        return false;
636    }
637
638    true
639}
640
641/// Compute the `intercrate_ambiguity_causes` for the new solver using
642/// "proof trees".
643///
644/// This is a bit scuffed but seems to be good enough, at least
645/// when looking at UI tests. Given that it is only used to improve
646/// diagnostics this is good enough. We can always improve it once there
647/// are test cases where it is currently not enough.
648fn compute_intercrate_ambiguity_causes<'tcx>(
649    infcx: &InferCtxt<'tcx>,
650    obligations: &[PredicateObligation<'tcx>],
651) -> FxIndexSet<IntercrateAmbiguityCause<'tcx>> {
652    let mut causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>> = Default::default();
653
654    for obligation in obligations {
655        search_ambiguity_causes(infcx, obligation.as_goal(), &mut causes);
656    }
657
658    causes
659}
660
661struct AmbiguityCausesVisitor<'a, 'tcx> {
662    cache: FxHashSet<Goal<'tcx, ty::Predicate<'tcx>>>,
663    causes: &'a mut FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
664}
665
666impl<'a, 'tcx> ProofTreeVisitor<'tcx> for AmbiguityCausesVisitor<'a, 'tcx> {
667    fn span(&self) -> Span {
668        DUMMY_SP
669    }
670
671    fn visit_goal(&mut self, goal: &InspectGoal<'_, 'tcx>) {
672        if !self.cache.insert(goal.goal()) {
673            return;
674        }
675
676        let infcx = goal.infcx();
677        for cand in goal.candidates() {
678            cand.visit_nested_in_probe(self);
679        }
680        // When searching for intercrate ambiguity causes, we only need to look
681        // at ambiguous goals, as for others the coherence unknowable candidate
682        // was irrelevant.
683        match goal.result() {
684            Ok(Certainty::Yes) | Err(NoSolution) => return,
685            Ok(Certainty::Maybe(_)) => {}
686        }
687
688        // For bound predicates we simply call `infcx.enter_forall`
689        // and then prove the resulting predicate as a nested goal.
690        let Goal { param_env, predicate } = goal.goal();
691        let trait_ref = match predicate.kind().no_bound_vars() {
692            Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(tr))) => tr.trait_ref,
693            Some(ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)))
694                if matches!(
695                    infcx.tcx.def_kind(proj.projection_term.def_id),
696                    DefKind::AssocTy | DefKind::AssocConst
697                ) =>
698            {
699                proj.projection_term.trait_ref(infcx.tcx)
700            }
701            _ => return,
702        };
703
704        if trait_ref.references_error() {
705            return;
706        }
707
708        let mut candidates = goal.candidates();
709        for cand in goal.candidates() {
710            if let inspect::ProbeKind::TraitCandidate {
711                source: CandidateSource::Impl(def_id),
712                result: Ok(_),
713            } = cand.kind()
714                && let ty::ImplPolarity::Reservation = infcx.tcx.impl_polarity(def_id)
715            {
716                let message = infcx
717                    .tcx
718                    .get_attr(def_id, sym::rustc_reservation_impl)
719                    .and_then(|a| a.value_str());
720                if let Some(message) = message {
721                    self.causes.insert(IntercrateAmbiguityCause::ReservationImpl { message });
722                }
723            }
724        }
725
726        // We also look for unknowable candidates. In case a goal is unknowable, there's
727        // always exactly 1 candidate.
728        let Some(cand) = candidates.pop() else {
729            return;
730        };
731
732        let inspect::ProbeKind::TraitCandidate {
733            source: CandidateSource::CoherenceUnknowable,
734            result: Ok(_),
735        } = cand.kind()
736        else {
737            return;
738        };
739
740        let lazily_normalize_ty = |mut ty: Ty<'tcx>| {
741            if matches!(ty.kind(), ty::Alias(..)) {
742                let ocx = ObligationCtxt::new(infcx);
743                ty = ocx
744                    .structurally_normalize_ty(&ObligationCause::dummy(), param_env, ty)
745                    .map_err(|_| ())?;
746                if !ocx.select_where_possible().is_empty() {
747                    return Err(());
748                }
749            }
750            Ok(ty)
751        };
752
753        infcx.probe(|_| {
754            let conflict = match trait_ref_is_knowable(infcx, trait_ref, lazily_normalize_ty) {
755                Err(()) => return,
756                Ok(Ok(())) => {
757                    warn!("expected an unknowable trait ref: {trait_ref:?}");
758                    return;
759                }
760                Ok(Err(conflict)) => conflict,
761            };
762
763            // It is only relevant that a goal is unknowable if it would have otherwise
764            // failed.
765            // FIXME(#132279): Forking with `TypingMode::non_body_analysis` is a bit questionable
766            // as it would allow us to reveal opaque types, potentially causing unexpected
767            // cycles.
768            let non_intercrate_infcx = infcx.fork_with_typing_mode(TypingMode::non_body_analysis());
769            if non_intercrate_infcx.predicate_may_hold(&Obligation::new(
770                infcx.tcx,
771                ObligationCause::dummy(),
772                param_env,
773                predicate,
774            )) {
775                return;
776            }
777
778            // Normalize the trait ref for diagnostics, ignoring any errors if this fails.
779            let trait_ref = deeply_normalize_for_diagnostics(infcx, param_env, trait_ref);
780            let self_ty = trait_ref.self_ty();
781            let self_ty = self_ty.has_concrete_skeleton().then(|| self_ty);
782            self.causes.insert(match conflict {
783                Conflict::Upstream => {
784                    IntercrateAmbiguityCause::UpstreamCrateUpdate { trait_ref, self_ty }
785                }
786                Conflict::Downstream => {
787                    IntercrateAmbiguityCause::DownstreamCrate { trait_ref, self_ty }
788                }
789            });
790        });
791    }
792}
793
794fn search_ambiguity_causes<'tcx>(
795    infcx: &InferCtxt<'tcx>,
796    goal: Goal<'tcx, ty::Predicate<'tcx>>,
797    causes: &mut FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
798) {
799    infcx.probe(|_| {
800        infcx.visit_proof_tree(
801            goal,
802            &mut AmbiguityCausesVisitor { cache: Default::default(), causes },
803        )
804    });
805}