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