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