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