rustc_trait_selection/traits/
mod.rs

1//! Trait Resolution. See the [rustc dev guide] for more information on how this works.
2//!
3//! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
4
5pub mod auto_trait;
6pub(crate) mod coherence;
7pub mod const_evaluatable;
8mod dyn_compatibility;
9pub mod effects;
10mod engine;
11mod fulfill;
12pub mod misc;
13pub mod normalize;
14pub mod outlives_bounds;
15pub mod project;
16pub mod query;
17#[allow(hidden_glob_reexports)]
18mod select;
19mod specialize;
20mod structural_normalize;
21#[allow(hidden_glob_reexports)]
22mod util;
23pub mod vtable;
24pub mod wf;
25
26use std::fmt::Debug;
27use std::ops::ControlFlow;
28
29use rustc_errors::ErrorGuaranteed;
30use rustc_hir::def::DefKind;
31pub use rustc_infer::traits::*;
32use rustc_middle::query::Providers;
33use rustc_middle::span_bug;
34use rustc_middle::ty::error::{ExpectedFound, TypeError};
35use rustc_middle::ty::fold::TypeFoldable;
36use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt};
37use rustc_middle::ty::{
38    self, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFolder, TypeSuperFoldable,
39    TypeSuperVisitable, TypingMode, Upcast,
40};
41use rustc_span::def_id::DefId;
42use rustc_span::{DUMMY_SP, Span};
43use tracing::{debug, instrument};
44
45pub use self::coherence::{
46    InCrate, IsFirstInputType, OrphanCheckErr, OrphanCheckMode, OverlapResult, UncoveredTyParams,
47    add_placeholder_note, orphan_check_trait_ref, overlapping_impls,
48};
49pub use self::dyn_compatibility::{
50    DynCompatibilityViolation, dyn_compatibility_violations_for_assoc_item,
51    hir_ty_lowering_dyn_compatibility_violations, is_vtable_safe_method,
52};
53pub use self::engine::{ObligationCtxt, TraitEngineExt};
54pub use self::fulfill::{FulfillmentContext, OldSolverError, PendingPredicateObligation};
55pub use self::normalize::NormalizeExt;
56pub use self::project::{normalize_inherent_projection, normalize_projection_ty};
57pub use self::select::{
58    EvaluationCache, EvaluationResult, IntercrateAmbiguityCause, OverflowError, SelectionCache,
59    SelectionContext,
60};
61pub use self::specialize::specialization_graph::{
62    FutureCompatOverlapError, FutureCompatOverlapErrorKind,
63};
64pub use self::specialize::{
65    OverlapError, specialization_graph, translate_args, translate_args_with_cause,
66};
67pub use self::structural_normalize::StructurallyNormalizeExt;
68pub use self::util::{
69    BoundVarReplacer, PlaceholderReplacer, elaborate, expand_trait_aliases, impl_item_is_final,
70    supertrait_def_ids, supertraits, transitive_bounds_that_define_assoc_item, upcast_choices,
71    with_replaced_escaping_bound_vars,
72};
73use crate::error_reporting::InferCtxtErrorExt;
74use crate::infer::outlives::env::OutlivesEnvironment;
75use crate::infer::{InferCtxt, TyCtxtInferExt};
76use crate::regions::InferCtxtRegionExt;
77use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
78
79#[derive(Debug)]
80pub struct FulfillmentError<'tcx> {
81    pub obligation: PredicateObligation<'tcx>,
82    pub code: FulfillmentErrorCode<'tcx>,
83    /// Diagnostics only: the 'root' obligation which resulted in
84    /// the failure to process `obligation`. This is the obligation
85    /// that was initially passed to `register_predicate_obligation`
86    pub root_obligation: PredicateObligation<'tcx>,
87}
88
89impl<'tcx> FulfillmentError<'tcx> {
90    pub fn new(
91        obligation: PredicateObligation<'tcx>,
92        code: FulfillmentErrorCode<'tcx>,
93        root_obligation: PredicateObligation<'tcx>,
94    ) -> FulfillmentError<'tcx> {
95        FulfillmentError { obligation, code, root_obligation }
96    }
97
98    pub fn is_true_error(&self) -> bool {
99        match self.code {
100            FulfillmentErrorCode::Select(_)
101            | FulfillmentErrorCode::Project(_)
102            | FulfillmentErrorCode::Subtype(_, _)
103            | FulfillmentErrorCode::ConstEquate(_, _) => true,
104            FulfillmentErrorCode::Cycle(_) | FulfillmentErrorCode::Ambiguity { overflow: _ } => {
105                false
106            }
107        }
108    }
109}
110
111#[derive(Clone)]
112pub enum FulfillmentErrorCode<'tcx> {
113    /// Inherently impossible to fulfill; this trait is implemented if and only
114    /// if it is already implemented.
115    Cycle(PredicateObligations<'tcx>),
116    Select(SelectionError<'tcx>),
117    Project(MismatchedProjectionTypes<'tcx>),
118    Subtype(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate
119    ConstEquate(ExpectedFound<ty::Const<'tcx>>, TypeError<'tcx>),
120    Ambiguity {
121        /// Overflow is only `Some(suggest_recursion_limit)` when using the next generation
122        /// trait solver `-Znext-solver`. With the old solver overflow is eagerly handled by
123        /// emitting a fatal error instead.
124        overflow: Option<bool>,
125    },
126}
127
128impl<'tcx> Debug for FulfillmentErrorCode<'tcx> {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        match *self {
131            FulfillmentErrorCode::Select(ref e) => write!(f, "{e:?}"),
132            FulfillmentErrorCode::Project(ref e) => write!(f, "{e:?}"),
133            FulfillmentErrorCode::Subtype(ref a, ref b) => {
134                write!(f, "CodeSubtypeError({a:?}, {b:?})")
135            }
136            FulfillmentErrorCode::ConstEquate(ref a, ref b) => {
137                write!(f, "CodeConstEquateError({a:?}, {b:?})")
138            }
139            FulfillmentErrorCode::Ambiguity { overflow: None } => write!(f, "Ambiguity"),
140            FulfillmentErrorCode::Ambiguity { overflow: Some(suggest_increasing_limit) } => {
141                write!(f, "Overflow({suggest_increasing_limit})")
142            }
143            FulfillmentErrorCode::Cycle(ref cycle) => write!(f, "Cycle({cycle:?})"),
144        }
145    }
146}
147
148/// Whether to skip the leak check, as part of a future compatibility warning step.
149///
150/// The "default" for skip-leak-check corresponds to the current
151/// behavior (do not skip the leak check) -- not the behavior we are
152/// transitioning into.
153#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
154pub enum SkipLeakCheck {
155    Yes,
156    #[default]
157    No,
158}
159
160impl SkipLeakCheck {
161    fn is_yes(self) -> bool {
162        self == SkipLeakCheck::Yes
163    }
164}
165
166/// The mode that trait queries run in.
167#[derive(Copy, Clone, PartialEq, Eq, Debug)]
168pub enum TraitQueryMode {
169    /// Standard/un-canonicalized queries get accurate
170    /// spans etc. passed in and hence can do reasonable
171    /// error reporting on their own.
172    Standard,
173    /// Canonical queries get dummy spans and hence
174    /// must generally propagate errors to
175    /// pre-canonicalization callsites.
176    Canonical,
177}
178
179/// Creates predicate obligations from the generic bounds.
180#[instrument(level = "debug", skip(cause, param_env))]
181pub fn predicates_for_generics<'tcx>(
182    cause: impl Fn(usize, Span) -> ObligationCause<'tcx>,
183    param_env: ty::ParamEnv<'tcx>,
184    generic_bounds: ty::InstantiatedPredicates<'tcx>,
185) -> impl Iterator<Item = PredicateObligation<'tcx>> {
186    generic_bounds.into_iter().enumerate().map(move |(idx, (clause, span))| Obligation {
187        cause: cause(idx, span),
188        recursion_depth: 0,
189        param_env,
190        predicate: clause.as_predicate(),
191    })
192}
193
194/// Determines whether the type `ty` is known to meet `bound` and
195/// returns true if so. Returns false if `ty` either does not meet
196/// `bound` or is not known to meet bound (note that this is
197/// conservative towards *no impl*, which is the opposite of the
198/// `evaluate` methods).
199pub fn type_known_to_meet_bound_modulo_regions<'tcx>(
200    infcx: &InferCtxt<'tcx>,
201    param_env: ty::ParamEnv<'tcx>,
202    ty: Ty<'tcx>,
203    def_id: DefId,
204) -> bool {
205    let trait_ref = ty::TraitRef::new(infcx.tcx, def_id, [ty]);
206    pred_known_to_hold_modulo_regions(infcx, param_env, trait_ref)
207}
208
209/// FIXME(@lcnr): this function doesn't seem right and shouldn't exist?
210///
211/// Ping me on zulip if you want to use this method and need help with finding
212/// an appropriate replacement.
213#[instrument(level = "debug", skip(infcx, param_env, pred), ret)]
214fn pred_known_to_hold_modulo_regions<'tcx>(
215    infcx: &InferCtxt<'tcx>,
216    param_env: ty::ParamEnv<'tcx>,
217    pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
218) -> bool {
219    let obligation = Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, pred);
220
221    let result = infcx.evaluate_obligation_no_overflow(&obligation);
222    debug!(?result);
223
224    if result.must_apply_modulo_regions() {
225        true
226    } else if result.may_apply() {
227        // Sometimes obligations are ambiguous because the recursive evaluator
228        // is not smart enough, so we fall back to fulfillment when we're not certain
229        // that an obligation holds or not. Even still, we must make sure that
230        // the we do no inference in the process of checking this obligation.
231        let goal = infcx.resolve_vars_if_possible((obligation.predicate, obligation.param_env));
232        infcx.probe(|_| {
233            let ocx = ObligationCtxt::new(infcx);
234            ocx.register_obligation(obligation);
235
236            let errors = ocx.select_all_or_error();
237            match errors.as_slice() {
238                // Only known to hold if we did no inference.
239                [] => infcx.resolve_vars_if_possible(goal) == goal,
240
241                errors => {
242                    debug!(?errors);
243                    false
244                }
245            }
246        })
247    } else {
248        false
249    }
250}
251
252#[instrument(level = "debug", skip(tcx, elaborated_env))]
253fn do_normalize_predicates<'tcx>(
254    tcx: TyCtxt<'tcx>,
255    cause: ObligationCause<'tcx>,
256    elaborated_env: ty::ParamEnv<'tcx>,
257    predicates: Vec<ty::Clause<'tcx>>,
258) -> Result<Vec<ty::Clause<'tcx>>, ErrorGuaranteed> {
259    let span = cause.span;
260
261    // FIXME. We should really... do something with these region
262    // obligations. But this call just continues the older
263    // behavior (i.e., doesn't cause any new bugs), and it would
264    // take some further refactoring to actually solve them. In
265    // particular, we would have to handle implied bounds
266    // properly, and that code is currently largely confined to
267    // regionck (though I made some efforts to extract it
268    // out). -nmatsakis
269    //
270    // @arielby: In any case, these obligations are checked
271    // by wfcheck anyway, so I'm not sure we have to check
272    // them here too, and we will remove this function when
273    // we move over to lazy normalization *anyway*.
274    let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
275    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
276    let predicates = ocx.normalize(&cause, elaborated_env, predicates);
277
278    let errors = ocx.select_all_or_error();
279    if !errors.is_empty() {
280        let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
281        return Err(reported);
282    }
283
284    debug!("do_normalize_predicates: normalized predicates = {:?}", predicates);
285
286    // We can use the `elaborated_env` here; the region code only
287    // cares about declarations like `'a: 'b`.
288    // FIXME: It's very weird that we ignore region obligations but apparently
289    // still need to use `resolve_regions` as we need the resolved regions in
290    // the normalized predicates.
291    let errors = infcx.resolve_regions(cause.body_id, elaborated_env, []);
292    if !errors.is_empty() {
293        tcx.dcx().span_delayed_bug(
294            span,
295            format!("failed region resolution while normalizing {elaborated_env:?}: {errors:?}"),
296        );
297    }
298
299    match infcx.fully_resolve(predicates) {
300        Ok(predicates) => Ok(predicates),
301        Err(fixup_err) => {
302            // If we encounter a fixup error, it means that some type
303            // variable wound up unconstrained. I actually don't know
304            // if this can happen, and I certainly don't expect it to
305            // happen often, but if it did happen it probably
306            // represents a legitimate failure due to some kind of
307            // unconstrained variable.
308            //
309            // @lcnr: Let's still ICE here for now. I want a test case
310            // for that.
311            span_bug!(
312                span,
313                "inference variables in normalized parameter environment: {}",
314                fixup_err
315            );
316        }
317    }
318}
319
320// FIXME: this is gonna need to be removed ...
321/// Normalizes the parameter environment, reporting errors if they occur.
322#[instrument(level = "debug", skip(tcx))]
323pub fn normalize_param_env_or_error<'tcx>(
324    tcx: TyCtxt<'tcx>,
325    unnormalized_env: ty::ParamEnv<'tcx>,
326    cause: ObligationCause<'tcx>,
327) -> ty::ParamEnv<'tcx> {
328    // I'm not wild about reporting errors here; I'd prefer to
329    // have the errors get reported at a defined place (e.g.,
330    // during typeck). Instead I have all parameter
331    // environments, in effect, going through this function
332    // and hence potentially reporting errors. This ensures of
333    // course that we never forget to normalize (the
334    // alternative seemed like it would involve a lot of
335    // manual invocations of this fn -- and then we'd have to
336    // deal with the errors at each of those sites).
337    //
338    // In any case, in practice, typeck constructs all the
339    // parameter environments once for every fn as it goes,
340    // and errors will get reported then; so outside of type inference we
341    // can be sure that no errors should occur.
342    let mut predicates: Vec<_> = util::elaborate(
343        tcx,
344        unnormalized_env.caller_bounds().into_iter().map(|predicate| {
345            if tcx.features().generic_const_exprs() {
346                return predicate;
347            }
348
349            struct ConstNormalizer<'tcx>(TyCtxt<'tcx>);
350
351            impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ConstNormalizer<'tcx> {
352                fn cx(&self) -> TyCtxt<'tcx> {
353                    self.0
354                }
355
356                fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
357                    // FIXME(return_type_notation): track binders in this normalizer, as
358                    // `ty::Const::normalize` can only work with properly preserved binders.
359
360                    if c.has_escaping_bound_vars() {
361                        return ty::Const::new_misc_error(self.0);
362                    }
363
364                    // While it is pretty sus to be evaluating things with an empty param env, it
365                    // should actually be okay since without `feature(generic_const_exprs)` the only
366                    // const arguments that have a non-empty param env are array repeat counts. These
367                    // do not appear in the type system though.
368                    if let ty::ConstKind::Unevaluated(uv) = c.kind()
369                        && self.0.def_kind(uv.def) == DefKind::AnonConst
370                    {
371                        let infcx = self.0.infer_ctxt().build(TypingMode::non_body_analysis());
372                        let c = evaluate_const(&infcx, c, ty::ParamEnv::empty());
373                        // We should never wind up with any `infcx` local state when normalizing anon consts
374                        // under min const generics.
375                        assert!(!c.has_infer() && !c.has_placeholders());
376                        return c;
377                    }
378
379                    c
380                }
381            }
382
383            // This whole normalization step is a hack to work around the fact that
384            // `normalize_param_env_or_error` is fundamentally broken from using an
385            // unnormalized param env with a trait solver that expects the param env
386            // to be normalized.
387            //
388            // When normalizing the param env we can end up evaluating obligations
389            // that have been normalized but can only be proven via a where clause
390            // which is still in its unnormalized form. example:
391            //
392            // Attempting to prove `T: Trait<<u8 as Identity>::Assoc>` in a param env
393            // with a `T: Trait<<u8 as Identity>::Assoc>` where clause will fail because
394            // we first normalize obligations before proving them so we end up proving
395            // `T: Trait<u8>`. Since lazy normalization is not implemented equating `u8`
396            // with `<u8 as Identity>::Assoc` fails outright so we incorrectly believe that
397            // we cannot prove `T: Trait<u8>`.
398            //
399            // The same thing is true for const generics- attempting to prove
400            // `T: Trait<ConstKind::Unevaluated(...)>` with the same thing as a where clauses
401            // will fail. After normalization we may be attempting to prove `T: Trait<4>` with
402            // the unnormalized where clause `T: Trait<ConstKind::Unevaluated(...)>`. In order
403            // for the obligation to hold `4` must be equal to `ConstKind::Unevaluated(...)`
404            // but as we do not have lazy norm implemented, equating the two consts fails outright.
405            //
406            // Ideally we would not normalize consts here at all but it is required for backwards
407            // compatibility. Eventually when lazy norm is implemented this can just be removed.
408            // We do not normalize types here as there is no backwards compatibility requirement
409            // for us to do so.
410            //
411            // FIXME(-Znext-solver): remove this hack since we have deferred projection equality
412            predicate.fold_with(&mut ConstNormalizer(tcx))
413        }),
414    )
415    .collect();
416
417    debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates);
418
419    let elaborated_env = ty::ParamEnv::new(tcx.mk_clauses(&predicates));
420    if !elaborated_env.has_aliases() {
421        return elaborated_env;
422    }
423
424    // HACK: we are trying to normalize the param-env inside *itself*. The problem is that
425    // normalization expects its param-env to be already normalized, which means we have
426    // a circularity.
427    //
428    // The way we handle this is by normalizing the param-env inside an unnormalized version
429    // of the param-env, which means that if the param-env contains unnormalized projections,
430    // we'll have some normalization failures. This is unfortunate.
431    //
432    // Lazy normalization would basically handle this by treating just the
433    // normalizing-a-trait-ref-requires-itself cycles as evaluation failures.
434    //
435    // Inferred outlives bounds can create a lot of `TypeOutlives` predicates for associated
436    // types, so to make the situation less bad, we normalize all the predicates *but*
437    // the `TypeOutlives` predicates first inside the unnormalized parameter environment, and
438    // then we normalize the `TypeOutlives` bounds inside the normalized parameter environment.
439    //
440    // This works fairly well because trait matching does not actually care about param-env
441    // TypeOutlives predicates - these are normally used by regionck.
442    let outlives_predicates: Vec<_> = predicates
443        .extract_if(.., |predicate| {
444            matches!(predicate.kind().skip_binder(), ty::ClauseKind::TypeOutlives(..))
445        })
446        .collect();
447
448    debug!(
449        "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})",
450        predicates, outlives_predicates
451    );
452    let Ok(non_outlives_predicates) =
453        do_normalize_predicates(tcx, cause.clone(), elaborated_env, predicates)
454    else {
455        // An unnormalized env is better than nothing.
456        debug!("normalize_param_env_or_error: errored resolving non-outlives predicates");
457        return elaborated_env;
458    };
459
460    debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates);
461
462    // Not sure whether it is better to include the unnormalized TypeOutlives predicates
463    // here. I believe they should not matter, because we are ignoring TypeOutlives param-env
464    // predicates here anyway. Keeping them here anyway because it seems safer.
465    let outlives_env = non_outlives_predicates.iter().chain(&outlives_predicates).cloned();
466    let outlives_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(outlives_env));
467    let Ok(outlives_predicates) =
468        do_normalize_predicates(tcx, cause, outlives_env, outlives_predicates)
469    else {
470        // An unnormalized env is better than nothing.
471        debug!("normalize_param_env_or_error: errored resolving outlives predicates");
472        return elaborated_env;
473    };
474    debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates);
475
476    let mut predicates = non_outlives_predicates;
477    predicates.extend(outlives_predicates);
478    debug!("normalize_param_env_or_error: final predicates={:?}", predicates);
479    ty::ParamEnv::new(tcx.mk_clauses(&predicates))
480}
481
482#[derive(Debug)]
483pub enum EvaluateConstErr {
484    /// The constant being evaluated was either a generic parameter or inference variable, *or*,
485    /// some unevaluated constant with either generic parameters or inference variables in its
486    /// generic arguments.
487    HasGenericsOrInfers,
488    /// The type this constant evalauted to is not valid for use in const generics. This should
489    /// always result in an error when checking the constant is correctly typed for the parameter
490    /// it is an argument to, so a bug is delayed when encountering this.
491    InvalidConstParamTy(ErrorGuaranteed),
492    /// CTFE failed to evaluate the constant in some unrecoverable way (e.g. encountered a `panic!`).
493    /// This is also used when the constant was already tainted by error.
494    EvaluationFailure(ErrorGuaranteed),
495}
496
497// FIXME(BoxyUwU): Private this once we `generic_const_exprs` isn't doing its own normalization routine
498// FIXME(generic_const_exprs): Consider accepting a `ty::UnevaluatedConst` when we are not rolling our own
499// normalization scheme
500/// Evaluates a type system constant returning a `ConstKind::Error` in cases where CTFE failed and
501/// returning the passed in constant if it was not fully concrete (i.e. depended on generic parameters
502/// or inference variables)
503///
504/// You should not call this function unless you are implementing normalization itself. Prefer to use
505/// `normalize_erasing_regions` or the `normalize` functions on `ObligationCtxt`/`FnCtxt`/`InferCtxt`.
506pub fn evaluate_const<'tcx>(
507    infcx: &InferCtxt<'tcx>,
508    ct: ty::Const<'tcx>,
509    param_env: ty::ParamEnv<'tcx>,
510) -> ty::Const<'tcx> {
511    match try_evaluate_const(infcx, ct, param_env) {
512        Ok(ct) => ct,
513        Err(EvaluateConstErr::EvaluationFailure(e) | EvaluateConstErr::InvalidConstParamTy(e)) => {
514            ty::Const::new_error(infcx.tcx, e)
515        }
516        Err(EvaluateConstErr::HasGenericsOrInfers) => ct,
517    }
518}
519
520// FIXME(BoxyUwU): Private this once we `generic_const_exprs` isn't doing its own normalization routine
521// FIXME(generic_const_exprs): Consider accepting a `ty::UnevaluatedConst` when we are not rolling our own
522// normalization scheme
523/// Evaluates a type system constant making sure to not allow constants that depend on generic parameters
524/// or inference variables to succeed in evaluating.
525///
526/// You should not call this function unless you are implementing normalization itself. Prefer to use
527/// `normalize_erasing_regions` or the `normalize` functions on `ObligationCtxt`/`FnCtxt`/`InferCtxt`.
528#[instrument(level = "debug", skip(infcx), ret)]
529pub fn try_evaluate_const<'tcx>(
530    infcx: &InferCtxt<'tcx>,
531    ct: ty::Const<'tcx>,
532    param_env: ty::ParamEnv<'tcx>,
533) -> Result<ty::Const<'tcx>, EvaluateConstErr> {
534    let tcx = infcx.tcx;
535    let ct = infcx.resolve_vars_if_possible(ct);
536    debug!(?ct);
537
538    match ct.kind() {
539        ty::ConstKind::Value(..) => Ok(ct),
540        ty::ConstKind::Error(e) => Err(EvaluateConstErr::EvaluationFailure(e)),
541        ty::ConstKind::Param(_)
542        | ty::ConstKind::Infer(_)
543        | ty::ConstKind::Bound(_, _)
544        | ty::ConstKind::Placeholder(_)
545        | ty::ConstKind::Expr(_) => Err(EvaluateConstErr::HasGenericsOrInfers),
546        ty::ConstKind::Unevaluated(uv) => {
547            // Postpone evaluation of constants that depend on generic parameters or
548            // inference variables.
549            //
550            // We use `TypingMode::PostAnalysis`  here which is not *technically* correct
551            // to be revealing opaque types here as borrowcheck has not run yet. However,
552            // CTFE itself uses `TypingMode::PostAnalysis` unconditionally even during
553            // typeck and not doing so has a lot of (undesirable) fallout (#101478, #119821).
554            // As a result we always use a revealed env when resolving the instance to evaluate.
555            //
556            // FIXME: `const_eval_resolve_for_typeck` should probably just modify the env itself
557            // instead of having this logic here
558            let (args, typing_env) = if tcx.features().generic_const_exprs()
559                && uv.has_non_region_infer()
560            {
561                // `feature(generic_const_exprs)` causes anon consts to inherit all parent generics. This can cause
562                // inference variables and generic parameters to show up in `ty::Const` even though the anon const
563                // does not actually make use of them. We handle this case specially and attempt to evaluate anyway.
564                match tcx.thir_abstract_const(uv.def) {
565                    Ok(Some(ct)) => {
566                        let ct = tcx.expand_abstract_consts(ct.instantiate(tcx, uv.args));
567                        if let Err(e) = ct.error_reported() {
568                            return Err(EvaluateConstErr::EvaluationFailure(e));
569                        } else if ct.has_non_region_infer() || ct.has_non_region_param() {
570                            // If the anon const *does* actually use generic parameters or inference variables from
571                            // the generic arguments provided for it, then we should *not* attempt to evaluate it.
572                            return Err(EvaluateConstErr::HasGenericsOrInfers);
573                        } else {
574                            let args = replace_param_and_infer_args_with_placeholder(tcx, uv.args);
575                            let typing_env = infcx
576                                .typing_env(tcx.erase_regions(param_env))
577                                .with_post_analysis_normalized(tcx);
578                            (args, typing_env)
579                        }
580                    }
581                    Err(_) | Ok(None) => {
582                        let args = GenericArgs::identity_for_item(tcx, uv.def);
583                        let typing_env = ty::TypingEnv::post_analysis(tcx, uv.def);
584                        (args, typing_env)
585                    }
586                }
587            } else if tcx.def_kind(uv.def) == DefKind::AnonConst && uv.has_non_region_infer() {
588                // FIXME: remove this when `const_evaluatable_unchecked` is a hard error.
589                //
590                // Diagnostics will sometimes replace the identity args of anon consts in
591                // array repeat expr counts with inference variables so we have to handle this
592                // even though it is not something we should ever actually encounter.
593                //
594                // Array repeat expr counts are allowed to syntactically use generic parameters
595                // but must not actually depend on them in order to evalaute successfully. This means
596                // that it is actually fine to evalaute them in their own environment rather than with
597                // the actually provided generic arguments.
598                tcx.dcx().delayed_bug(
599                    "Encountered anon const with inference variable args but no error reported",
600                );
601
602                let args = GenericArgs::identity_for_item(tcx, uv.def);
603                let typing_env = ty::TypingEnv::post_analysis(tcx, uv.def);
604                (args, typing_env)
605            } else {
606                // FIXME: This codepath is reachable under `associated_const_equality` and in the
607                // future will be reachable by `min_generic_const_args`. We should handle inference
608                // variables and generic parameters properly instead of doing nothing.
609                let typing_env = infcx
610                    .typing_env(tcx.erase_regions(param_env))
611                    .with_post_analysis_normalized(tcx);
612                (uv.args, typing_env)
613            };
614            let uv = ty::UnevaluatedConst::new(uv.def, args);
615
616            let erased_uv = tcx.erase_regions(uv);
617            use rustc_middle::mir::interpret::ErrorHandled;
618            match tcx.const_eval_resolve_for_typeck(typing_env, erased_uv, DUMMY_SP) {
619                Ok(Ok(val)) => Ok(ty::Const::new_value(
620                    tcx,
621                    val,
622                    tcx.type_of(uv.def).instantiate(tcx, uv.args),
623                )),
624                Ok(Err(_)) => {
625                    let e = tcx.dcx().delayed_bug(
626                        "Type system constant with non valtree'able type evaluated but no error emitted",
627                    );
628                    Err(EvaluateConstErr::InvalidConstParamTy(e))
629                }
630                Err(ErrorHandled::Reported(info, _)) => {
631                    Err(EvaluateConstErr::EvaluationFailure(info.into()))
632                }
633                Err(ErrorHandled::TooGeneric(_)) => Err(EvaluateConstErr::HasGenericsOrInfers),
634            }
635        }
636    }
637}
638
639/// Replaces args that reference param or infer variables with suitable
640/// placeholders. This function is meant to remove these param and infer
641/// args when they're not actually needed to evaluate a constant.
642fn replace_param_and_infer_args_with_placeholder<'tcx>(
643    tcx: TyCtxt<'tcx>,
644    args: GenericArgsRef<'tcx>,
645) -> GenericArgsRef<'tcx> {
646    struct ReplaceParamAndInferWithPlaceholder<'tcx> {
647        tcx: TyCtxt<'tcx>,
648        idx: u32,
649    }
650
651    impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReplaceParamAndInferWithPlaceholder<'tcx> {
652        fn cx(&self) -> TyCtxt<'tcx> {
653            self.tcx
654        }
655
656        fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
657            if let ty::Infer(_) = t.kind() {
658                let idx = {
659                    let idx = self.idx;
660                    self.idx += 1;
661                    idx
662                };
663                Ty::new_placeholder(
664                    self.tcx,
665                    ty::PlaceholderType {
666                        universe: ty::UniverseIndex::ROOT,
667                        bound: ty::BoundTy {
668                            var: ty::BoundVar::from_u32(idx),
669                            kind: ty::BoundTyKind::Anon,
670                        },
671                    },
672                )
673            } else {
674                t.super_fold_with(self)
675            }
676        }
677
678        fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
679            if let ty::ConstKind::Infer(_) = c.kind() {
680                ty::Const::new_placeholder(
681                    self.tcx,
682                    ty::PlaceholderConst {
683                        universe: ty::UniverseIndex::ROOT,
684                        bound: ty::BoundVar::from_u32({
685                            let idx = self.idx;
686                            self.idx += 1;
687                            idx
688                        }),
689                    },
690                )
691            } else {
692                c.super_fold_with(self)
693            }
694        }
695    }
696
697    args.fold_with(&mut ReplaceParamAndInferWithPlaceholder { tcx, idx: 0 })
698}
699
700/// Normalizes the predicates and checks whether they hold in an empty environment. If this
701/// returns true, then either normalize encountered an error or one of the predicates did not
702/// hold. Used when creating vtables to check for unsatisfiable methods. This should not be
703/// used during analysis.
704pub fn impossible_predicates<'tcx>(tcx: TyCtxt<'tcx>, predicates: Vec<ty::Clause<'tcx>>) -> bool {
705    debug!("impossible_predicates(predicates={:?})", predicates);
706    let (infcx, param_env) =
707        tcx.infer_ctxt().build_with_typing_env(ty::TypingEnv::fully_monomorphized());
708    let ocx = ObligationCtxt::new(&infcx);
709    let predicates = ocx.normalize(&ObligationCause::dummy(), param_env, predicates);
710    for predicate in predicates {
711        let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate);
712        ocx.register_obligation(obligation);
713    }
714    let errors = ocx.select_all_or_error();
715
716    if !errors.is_empty() {
717        return true;
718    }
719
720    // Leak check for any higher-ranked trait mismatches.
721    // We only need to do this in the old solver, since the new solver already
722    // leak-checks.
723    if !infcx.next_trait_solver() && infcx.leak_check(ty::UniverseIndex::ROOT, None).is_err() {
724        return true;
725    }
726
727    false
728}
729
730fn instantiate_and_check_impossible_predicates<'tcx>(
731    tcx: TyCtxt<'tcx>,
732    key: (DefId, GenericArgsRef<'tcx>),
733) -> bool {
734    debug!("instantiate_and_check_impossible_predicates(key={:?})", key);
735
736    let mut predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates;
737
738    // Specifically check trait fulfillment to avoid an error when trying to resolve
739    // associated items.
740    if let Some(trait_def_id) = tcx.trait_of_item(key.0) {
741        let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, key.1);
742        predicates.push(trait_ref.upcast(tcx));
743    }
744
745    predicates.retain(|predicate| !predicate.has_param());
746    let result = impossible_predicates(tcx, predicates);
747
748    debug!("instantiate_and_check_impossible_predicates(key={:?}) = {:?}", key, result);
749    result
750}
751
752/// Checks whether a trait's associated item is impossible to reference on a given impl.
753///
754/// This only considers predicates that reference the impl's generics, and not
755/// those that reference the method's generics.
756fn is_impossible_associated_item(
757    tcx: TyCtxt<'_>,
758    (impl_def_id, trait_item_def_id): (DefId, DefId),
759) -> bool {
760    struct ReferencesOnlyParentGenerics<'tcx> {
761        tcx: TyCtxt<'tcx>,
762        generics: &'tcx ty::Generics,
763        trait_item_def_id: DefId,
764    }
765    impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for ReferencesOnlyParentGenerics<'tcx> {
766        type Result = ControlFlow<()>;
767        fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
768            // If this is a parameter from the trait item's own generics, then bail
769            if let ty::Param(param) = *t.kind()
770                && let param_def_id = self.generics.type_param(param, self.tcx).def_id
771                && self.tcx.parent(param_def_id) == self.trait_item_def_id
772            {
773                return ControlFlow::Break(());
774            }
775            t.super_visit_with(self)
776        }
777        fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
778            if let ty::ReEarlyParam(param) = r.kind()
779                && let param_def_id = self.generics.region_param(param, self.tcx).def_id
780                && self.tcx.parent(param_def_id) == self.trait_item_def_id
781            {
782                return ControlFlow::Break(());
783            }
784            ControlFlow::Continue(())
785        }
786        fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
787            if let ty::ConstKind::Param(param) = ct.kind()
788                && let param_def_id = self.generics.const_param(param, self.tcx).def_id
789                && self.tcx.parent(param_def_id) == self.trait_item_def_id
790            {
791                return ControlFlow::Break(());
792            }
793            ct.super_visit_with(self)
794        }
795    }
796
797    let generics = tcx.generics_of(trait_item_def_id);
798    let predicates = tcx.predicates_of(trait_item_def_id);
799
800    // Be conservative in cases where we have `W<T: ?Sized>` and a method like `Self: Sized`,
801    // since that method *may* have some substitutions where the predicates hold.
802    //
803    // This replicates the logic we use in coherence.
804    let infcx = tcx
805        .infer_ctxt()
806        .ignoring_regions()
807        .with_next_trait_solver(true)
808        .build(TypingMode::Coherence);
809    let param_env = ty::ParamEnv::empty();
810    let fresh_args = infcx.fresh_args_for_item(tcx.def_span(impl_def_id), impl_def_id);
811
812    let impl_trait_ref = tcx
813        .impl_trait_ref(impl_def_id)
814        .expect("expected impl to correspond to trait")
815        .instantiate(tcx, fresh_args);
816
817    let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id };
818    let predicates_for_trait = predicates.predicates.iter().filter_map(|(pred, span)| {
819        pred.visit_with(&mut visitor).is_continue().then(|| {
820            Obligation::new(
821                tcx,
822                ObligationCause::dummy_with_span(*span),
823                param_env,
824                ty::EarlyBinder::bind(*pred).instantiate(tcx, impl_trait_ref.args),
825            )
826        })
827    });
828
829    let ocx = ObligationCtxt::new(&infcx);
830    ocx.register_obligations(predicates_for_trait);
831    !ocx.select_where_possible().is_empty()
832}
833
834pub fn provide(providers: &mut Providers) {
835    dyn_compatibility::provide(providers);
836    vtable::provide(providers);
837    *providers = Providers {
838        specialization_graph_of: specialize::specialization_graph_provider,
839        specializes: specialize::specializes,
840        specialization_enabled_in: specialize::specialization_enabled_in,
841        instantiate_and_check_impossible_predicates,
842        is_impossible_associated_item,
843        ..*providers
844    };
845}