Skip to main content

rustc_middle/mir/interpret/
queries.rs

1use rustc_hir::def::DefKind;
2use rustc_hir::def_id::DefId;
3use rustc_lint_defs::builtin::CONST_EVALUATABLE_UNCHECKED;
4use rustc_span::{DUMMY_SP, Span, bug};
5use tracing::{debug, instrument};
6
7use super::{
8    ErrorHandled, EvalToAllocationRawResult, EvalToConstValueResult, GlobalId, ReportedErrorInfo,
9};
10use crate::mir::interpret::ValTreeCreationError;
11use crate::ty::{self, ConstToValTreeResult, GenericArgs, TyCtxt, TypeVisitableExt};
12use crate::{diagnostics, mir};
13
14impl<'tcx> TyCtxt<'tcx> {
15    /// Evaluates a constant without providing any generic parameters. This is useful to evaluate consts
16    /// that can't take any generic arguments like const items or enum discriminants. If a
17    /// generic parameter is used within the constant `ErrorHandled::TooGeneric` will be returned.
18    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("const_eval_poly",
                                    "rustc_middle::mir::interpret::queries",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_middle/src/mir/interpret/queries.rs"),
                                    ::tracing_core::__macro_support::Option::Some(18u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret::queries"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: EvalToConstValueResult<'tcx> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let args = GenericArgs::identity_for_item(self, def_id);
            let instance = ty::Instance::new_raw(def_id, args);
            let cid = GlobalId { instance, promoted: None };
            let typing_env = ty::TypingEnv::post_analysis(self, def_id);
            self.const_eval_global_id(typing_env, cid, DUMMY_SP)
        }
    }
}#[instrument(skip(self), level = "debug")]
19    pub fn const_eval_poly(self, def_id: DefId) -> EvalToConstValueResult<'tcx> {
20        // In some situations def_id will have generic parameters within scope, but they aren't allowed
21        // to be used. So we can't use `Instance::mono`, instead we feed unresolved generic parameters
22        // into `const_eval` which will return `ErrorHandled::TooGeneric` if any of them are
23        // encountered.
24        let args = GenericArgs::identity_for_item(self, def_id);
25        let instance = ty::Instance::new_raw(def_id, args);
26        let cid = GlobalId { instance, promoted: None };
27        let typing_env = ty::TypingEnv::post_analysis(self, def_id);
28        self.const_eval_global_id(typing_env, cid, DUMMY_SP)
29    }
30
31    /// Evaluates a constant without providing any generic parameters. This is useful to evaluate consts
32    /// that can't take any generic arguments like const items or enum discriminants. If a
33    /// generic parameter is used within the constant `ErrorHandled::TooGeneric` will be returned.
34    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("const_eval_poly_to_alloc",
                                    "rustc_middle::mir::interpret::queries",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_middle/src/mir/interpret/queries.rs"),
                                    ::tracing_core::__macro_support::Option::Some(34u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret::queries"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: EvalToAllocationRawResult<'tcx> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let args = GenericArgs::identity_for_item(self, def_id);
            let instance = ty::Instance::new_raw(def_id, args);
            let cid = GlobalId { instance, promoted: None };
            let typing_env = ty::TypingEnv::post_analysis(self, def_id);
            let inputs =
                self.erase_and_anonymize_regions(typing_env.as_query_input(cid));
            self.eval_to_allocation_raw(inputs)
        }
    }
}#[instrument(skip(self), level = "debug")]
35    pub fn const_eval_poly_to_alloc(self, def_id: DefId) -> EvalToAllocationRawResult<'tcx> {
36        // In some situations def_id will have generic parameters within scope, but they aren't allowed
37        // to be used. So we can't use `Instance::mono`, instead we feed unresolved generic parameters
38        // into `const_eval` which will return `ErrorHandled::TooGeneric` if any of them are
39        // encountered.
40        let args = GenericArgs::identity_for_item(self, def_id);
41        let instance = ty::Instance::new_raw(def_id, args);
42        let cid = GlobalId { instance, promoted: None };
43        let typing_env = ty::TypingEnv::post_analysis(self, def_id);
44        let inputs = self.erase_and_anonymize_regions(typing_env.as_query_input(cid));
45        self.eval_to_allocation_raw(inputs)
46    }
47
48    /// Resolves and evaluates a constant.
49    ///
50    /// The constant can be located on a trait like `<A as B>::C`, in which case the given
51    /// generic parameters and environment are used to resolve the constant. Alternatively if the
52    /// constant has generic parameters in scope the generic parameters are used to evaluate the value of
53    /// the constant. For example in `fn foo<T>() { let _ = [0; bar::<T>()]; }` the repeat count
54    /// constant `bar::<T>()` requires a instantiation for `T`, if the instantiation for `T` is still
55    /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is
56    /// returned.
57    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("const_eval_resolve",
                                    "rustc_middle::mir::interpret::queries",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_middle/src/mir/interpret/queries.rs"),
                                    ::tracing_core::__macro_support::Option::Some(57u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret::queries"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("typing_env")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("typing_env");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ct")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ct");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&typing_env)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ct)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: EvalToConstValueResult<'tcx> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if ct.args.has_non_region_infer() {
                ::rustc_span::macros::bug_impl(None,
                    format_args!("did not expect inference variables here"),
                    Location::caller());
            }
            match ty::Instance::try_resolve(self, typing_env, ct.def, ct.args)
                {
                Ok(Some(instance)) => {
                    let cid = GlobalId { instance, promoted: ct.promoted };
                    self.const_eval_global_id(typing_env, cid, span)
                }
                Ok(None) => Err(ErrorHandled::TooGeneric(DUMMY_SP)),
                Err(err) => {
                    Err(ErrorHandled::Reported(ReportedErrorInfo::non_const_eval_error(err),
                            DUMMY_SP))
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
58    pub fn const_eval_resolve(
59        self,
60        typing_env: ty::TypingEnv<'tcx>,
61        ct: mir::UnevaluatedConst<'tcx>,
62        span: Span,
63    ) -> EvalToConstValueResult<'tcx> {
64        // Cannot resolve `Unevaluated` constants that contain inference
65        // variables. We reject those here since `resolve`
66        // would fail otherwise.
67        //
68        // When trying to evaluate constants containing inference variables,
69        // use `Infcx::const_eval_resolve` instead.
70        if ct.args.has_non_region_infer() {
71            bug!("did not expect inference variables here");
72        }
73
74        // FIXME: maybe have a separate version for resolving mir::UnevaluatedConst?
75        match ty::Instance::try_resolve(self, typing_env, ct.def, ct.args) {
76            Ok(Some(instance)) => {
77                let cid = GlobalId { instance, promoted: ct.promoted };
78                self.const_eval_global_id(typing_env, cid, span)
79            }
80            // For errors during resolution, we deliberately do not point at the usage site of the constant,
81            // since for these errors the place the constant is used shouldn't matter.
82            Ok(None) => Err(ErrorHandled::TooGeneric(DUMMY_SP)),
83            Err(err) => {
84                Err(ErrorHandled::Reported(ReportedErrorInfo::non_const_eval_error(err), DUMMY_SP))
85            }
86        }
87    }
88
89    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("const_eval_resolve_for_typeck",
                                    "rustc_middle::mir::interpret::queries",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_middle/src/mir/interpret/queries.rs"),
                                    ::tracing_core::__macro_support::Option::Some(89u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret::queries"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("typing_env")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("typing_env");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ct")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ct");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&typing_env)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ct)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ConstToValTreeResult<'tcx> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if ct.args.has_non_region_infer() {
                ::rustc_span::macros::bug_impl(None,
                    format_args!("did not expect inference variables here"),
                    Location::caller());
            }
            let def_id =
                match ct.kind {
                    ty::AliasConstKind::InherentSelf { .. } => {
                        ::rustc_span::macros::bug_impl(None,
                            format_args!("got AliasConstKind::InherentSelf in const_eval_resolve_for_typeck"),
                            Location::caller())
                    }
                    ty::AliasConstKind::Projection { def_id } |
                        ty::AliasConstKind::InherentImpl { def_id } |
                        ty::AliasConstKind::Free { def_id } |
                        ty::AliasConstKind::Anon { def_id } => def_id,
                };
            let ty::PseudoCanonicalInput { typing_env, value: args } =
                typing_env.with_post_analysis_normalized_invalidating_rigid_aliases(self,
                    ct.args);
            let cid =
                match ty::Instance::try_resolve(self, typing_env, def_id,
                        args) {
                    Ok(Some(instance)) => GlobalId { instance, promoted: None },
                    Ok(None) => return Err(ErrorHandled::TooGeneric(DUMMY_SP)),
                    Err(err) => {
                        return Err(ErrorHandled::Reported(ReportedErrorInfo::non_const_eval_error(err),
                                    DUMMY_SP));
                    }
                };
            self.const_eval_global_id_for_typeck(typing_env, cid,
                    span).inspect(|_|
                    {
                        let def_id = cid.instance.def_id();
                        if !self.features().generic_const_exprs() &&
                                            args.has_non_region_param() &&
                                        self.def_kind(def_id) == DefKind::AnonConst &&
                                    !self.is_trivial_const(def_id) &&
                                let Some(local_def_id) = def_id.as_local() {
                            let mir_body = self.mir_for_ctfe(def_id);
                            if mir_body.is_polymorphic {
                                self.emit_node_span_lint(CONST_EVALUATABLE_UNCHECKED,
                                    self.local_def_id_to_hir_id(local_def_id),
                                    self.def_span(def_id),
                                    rustc_errors::DiagDecorator(|lint|
                                            {
                                                lint.primary_message("cannot use constants which depend on generic parameters in types");
                                            }))
                            }
                        }
                    })
        }
    }
}#[instrument(level = "debug", skip(self))]
90    pub fn const_eval_resolve_for_typeck(
91        self,
92        typing_env: ty::TypingEnv<'tcx>,
93        ct: ty::AliasConst<'tcx>,
94        span: Span,
95    ) -> ConstToValTreeResult<'tcx> {
96        // Cannot resolve `Unevaluated` constants that contain inference
97        // variables. We reject those here since `resolve`
98        // would fail otherwise.
99        //
100        // When trying to evaluate constants containing inference variables,
101        // use `Infcx::const_eval_resolve` instead.
102        if ct.args.has_non_region_infer() {
103            bug!("did not expect inference variables here");
104        }
105
106        let def_id = match ct.kind {
107            ty::AliasConstKind::InherentSelf { .. } => {
108                bug!("got AliasConstKind::InherentSelf in const_eval_resolve_for_typeck")
109            }
110            ty::AliasConstKind::Projection { def_id }
111            | ty::AliasConstKind::InherentImpl { def_id }
112            | ty::AliasConstKind::Free { def_id }
113            | ty::AliasConstKind::Anon { def_id } => def_id,
114        };
115
116        // We need to use post analysis mode for instance resolving to succeed.
117        // Otherwise we often bail due to impl candidate not being final.
118        // Revealing opaques here should be fine as we proved the trait ref
119        // with rigid opaques in typeck.
120        let ty::PseudoCanonicalInput { typing_env, value: args } =
121            typing_env.with_post_analysis_normalized_invalidating_rigid_aliases(self, ct.args);
122
123        let cid = match ty::Instance::try_resolve(self, typing_env, def_id, args) {
124            Ok(Some(instance)) => GlobalId { instance, promoted: None },
125            // For errors during resolution, we deliberately do not point at the usage site of the constant,
126            // since for these errors the place the constant is used shouldn't matter.
127            Ok(None) => return Err(ErrorHandled::TooGeneric(DUMMY_SP)),
128            Err(err) => {
129                return Err(ErrorHandled::Reported(
130                    ReportedErrorInfo::non_const_eval_error(err),
131                    DUMMY_SP,
132                ));
133            }
134        };
135
136        self.const_eval_global_id_for_typeck(typing_env, cid, span).inspect(|_| {
137            // We are emitting the lint here instead of in `is_const_evaluatable`
138            // as we normalize obligations before checking them, and normalization
139            // uses this function to evaluate this constant.
140            //
141            // @lcnr believes that successfully evaluating even though there are
142            // used generic parameters is a bug of evaluation, so checking for it
143            // here does feel somewhat sensible.
144            let def_id = cid.instance.def_id();
145            if !self.features().generic_const_exprs()
146                && args.has_non_region_param()
147                // We only FCW for anon consts as repeat expr counts with anon consts are the only place
148                // that we have a back compat hack for. We don't need to check this is a const argument
149                // as only anon consts as const args should get evaluated "for the type system".
150                //
151                // If we don't *only* FCW anon consts we can wind up incorrectly FCW'ing uses of assoc
152                // consts in pattern positions. #140447
153                && self.def_kind(def_id) == DefKind::AnonConst
154                && !self.is_trivial_const(def_id)
155                && let Some(local_def_id) = def_id.as_local()
156            {
157                let mir_body = self.mir_for_ctfe(def_id);
158                if mir_body.is_polymorphic {
159                    self.emit_node_span_lint(
160                        CONST_EVALUATABLE_UNCHECKED,
161                        self.local_def_id_to_hir_id(local_def_id),
162                        self.def_span(def_id),
163                        rustc_errors::DiagDecorator(|lint| {
164                            lint.primary_message(
165                                "cannot use constants which depend on generic parameters in types",
166                            );
167                        }),
168                    )
169                }
170            }
171        })
172    }
173
174    pub fn const_eval_instance(
175        self,
176        typing_env: ty::TypingEnv<'tcx>,
177        instance: ty::Instance<'tcx>,
178        span: Span,
179    ) -> EvalToConstValueResult<'tcx> {
180        self.const_eval_global_id(typing_env, GlobalId { instance, promoted: None }, span)
181    }
182
183    /// Evaluate a constant to a `ConstValue`.
184    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("const_eval_global_id",
                                    "rustc_middle::mir::interpret::queries",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_middle/src/mir/interpret/queries.rs"),
                                    ::tracing_core::__macro_support::Option::Some(184u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret::queries"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("typing_env")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("typing_env");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("cid")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("cid");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&typing_env)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cid)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: EvalToConstValueResult<'tcx> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let inputs =
                self.erase_and_anonymize_regions(typing_env.with_post_analysis_normalized_invalidating_rigid_aliases(self,
                        cid));
            if !span.is_dummy() {
                self.at(span).eval_to_const_value_raw(inputs).map_err(|e|
                        e.with_span(span))
            } else { self.eval_to_const_value_raw(inputs) }
        }
    }
}#[instrument(skip(self), level = "debug")]
185    pub fn const_eval_global_id(
186        self,
187        typing_env: ty::TypingEnv<'tcx>,
188        cid: GlobalId<'tcx>,
189        span: Span,
190    ) -> EvalToConstValueResult<'tcx> {
191        // Const-eval shouldn't depend on lifetimes at all, so we can erase them, which should
192        // improve caching of queries.
193        let inputs = self.erase_and_anonymize_regions(
194            typing_env.with_post_analysis_normalized_invalidating_rigid_aliases(self, cid),
195        );
196        if !span.is_dummy() {
197            // The query doesn't know where it is being invoked, so we need to fix the span.
198            self.at(span).eval_to_const_value_raw(inputs).map_err(|e| e.with_span(span))
199        } else {
200            self.eval_to_const_value_raw(inputs)
201        }
202    }
203
204    /// Evaluate a constant to a type-level constant.
205    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("const_eval_global_id_for_typeck",
                                    "rustc_middle::mir::interpret::queries",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_middle/src/mir/interpret/queries.rs"),
                                    ::tracing_core::__macro_support::Option::Some(205u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret::queries"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("typing_env")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("typing_env");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("cid")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("cid");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&typing_env)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cid)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: ConstToValTreeResult<'tcx> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            let inputs =
                self.erase_and_anonymize_regions(typing_env.with_post_analysis_normalized_invalidating_rigid_aliases(self,
                        cid));
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_middle/src/mir/interpret/queries.rs:217",
                                    "rustc_middle::mir::interpret::queries",
                                    ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/16d1ffac17ad8b739e32483ac2e65fe7e1804977/compiler/rustc_middle/src/mir/interpret/queries.rs"),
                                    ::tracing_core::__macro_support::Option::Some(217u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::interpret::queries"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("inputs")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("inputs");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&inputs)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let res =
                if !span.is_dummy() {
                    self.at(span).eval_to_valtree(inputs).map_err(|e|
                            e.with_span(span))
                } else { self.eval_to_valtree(inputs) };
            match res {
                Ok(valtree) => Ok(Ok(valtree)),
                Err(err) => {
                    match err {
                        ValTreeCreationError::NonSupportedType(ty) => Ok(Err(ty)),
                        ValTreeCreationError::NodesOverflow => {
                            let handled =
                                self.dcx().emit_err(diagnostics::MaxNumNodesInValtree {
                                        span,
                                        global_const_id: cid.display(self),
                                    });
                            Err(ReportedErrorInfo::allowed_in_infallible(handled).into())
                        }
                        ValTreeCreationError::InvalidConst => {
                            let handled =
                                self.dcx().emit_err(diagnostics::InvalidConstInValtree {
                                        span,
                                        global_const_id: cid.display(self),
                                    });
                            Err(ReportedErrorInfo::allowed_in_infallible(handled).into())
                        }
                        ValTreeCreationError::CyclicConst => {
                            let handled =
                                self.dcx().emit_err(diagnostics::CyclicConstInValtree {
                                        span,
                                        global_const_id: cid.display(self),
                                    });
                            Err(ReportedErrorInfo::allowed_in_infallible(handled).into())
                        }
                        ValTreeCreationError::ErrorHandled(handled) => Err(handled),
                    }
                }
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
206    pub fn const_eval_global_id_for_typeck(
207        self,
208        typing_env: ty::TypingEnv<'tcx>,
209        cid: GlobalId<'tcx>,
210        span: Span,
211    ) -> ConstToValTreeResult<'tcx> {
212        // Const-eval shouldn't depend on lifetimes at all, so we can erase them, which should
213        // improve caching of queries.
214        let inputs = self.erase_and_anonymize_regions(
215            typing_env.with_post_analysis_normalized_invalidating_rigid_aliases(self, cid),
216        );
217        debug!(?inputs);
218        let res = if !span.is_dummy() {
219            // The query doesn't know where it is being invoked, so we need to fix the span.
220            self.at(span).eval_to_valtree(inputs).map_err(|e| e.with_span(span))
221        } else {
222            self.eval_to_valtree(inputs)
223        };
224        match res {
225            Ok(valtree) => Ok(Ok(valtree)),
226            Err(err) => {
227                match err {
228                    // Let the caller decide how to handle this.
229                    ValTreeCreationError::NonSupportedType(ty) => Ok(Err(ty)),
230                    // Report the others.
231                    ValTreeCreationError::NodesOverflow => {
232                        let handled = self.dcx().emit_err(diagnostics::MaxNumNodesInValtree {
233                            span,
234                            global_const_id: cid.display(self),
235                        });
236                        Err(ReportedErrorInfo::allowed_in_infallible(handled).into())
237                    }
238                    ValTreeCreationError::InvalidConst => {
239                        let handled = self.dcx().emit_err(diagnostics::InvalidConstInValtree {
240                            span,
241                            global_const_id: cid.display(self),
242                        });
243                        Err(ReportedErrorInfo::allowed_in_infallible(handled).into())
244                    }
245                    ValTreeCreationError::CyclicConst => {
246                        let handled = self.dcx().emit_err(diagnostics::CyclicConstInValtree {
247                            span,
248                            global_const_id: cid.display(self),
249                        });
250                        Err(ReportedErrorInfo::allowed_in_infallible(handled).into())
251                    }
252                    ValTreeCreationError::ErrorHandled(handled) => Err(handled),
253                }
254            }
255        }
256    }
257}