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