Skip to main content

rustc_mir_build/builder/expr/
as_constant.rs

1//! See docs in builder/expr/mod.rs
2
3use rustc_abi::Size;
4use rustc_ast as ast;
5use rustc_hir::attrs::lang_items::LangItem;
6use rustc_hir::def::DefKind;
7use rustc_middle::mir;
8use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, Scalar};
9use rustc_middle::mir::*;
10use rustc_middle::thir::*;
11use rustc_middle::ty::{
12    self, CanonicalUserType, CanonicalUserTypeAnnotation, LitToConstInput, Ty, TyCtxt,
13    TypeVisitableExt as _, UserTypeAnnotationIndex,
14};
15use rustc_span::{bug, span_bug};
16use tracing::{instrument, trace};
17
18use crate::builder::{Builder, parse_float_into_constval};
19
20impl<'a, 'tcx> Builder<'a, 'tcx> {
21    /// Compile `expr`, yielding a compile-time constant. Assumes that
22    /// `expr` is a valid compile-time constant!
23    pub(crate) fn as_constant(&mut self, expr: &Expr<'tcx>) -> ConstOperand<'tcx> {
24        let this = self; // See "LET_THIS_SELF".
25        let tcx = this.tcx;
26        let Expr { ty, temp_scope_id: _, span, ref kind } = *expr;
27        match kind {
28            ExprKind::Scope { region_scope: _, hir_id: _, value } => {
29                this.as_constant(&this.thir[*value])
30            }
31            _ => as_constant_inner(
32                expr,
33                |user_ty| {
34                    Some(this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
35                        span,
36                        user_ty: user_ty.clone(),
37                        inferred_ty: ty,
38                    }))
39                },
40                tcx,
41            ),
42        }
43    }
44}
45
46pub(crate) fn as_constant_inner<'tcx>(
47    expr: &Expr<'tcx>,
48    push_cuta: impl FnMut(&Box<CanonicalUserType<'tcx>>) -> Option<UserTypeAnnotationIndex>,
49    tcx: TyCtxt<'tcx>,
50) -> ConstOperand<'tcx> {
51    let Expr { ty, temp_scope_id: _, span, ref kind } = *expr;
52
53    match *kind {
54        ExprKind::Literal { lit, neg } => {
55            let const_ =
56                lit_to_mir_constant(tcx, LitToConstInput { lit: lit.node, ty: Some(ty), neg });
57
58            ConstOperand { span, user_ty: None, const_ }
59        }
60        ExprKind::NonHirLiteral { lit, ref user_ty } => {
61            let user_ty = user_ty.as_ref().and_then(push_cuta);
62
63            let const_ = Const::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
64
65            ConstOperand { span, user_ty, const_ }
66        }
67        ExprKind::ZstLiteral { ref user_ty } => {
68            let user_ty = user_ty.as_ref().and_then(push_cuta);
69
70            let const_ = Const::Val(ConstValue::ZeroSized, ty);
71
72            ConstOperand { span, user_ty, const_ }
73        }
74        ExprKind::NamedConst { def_id, args, ref user_ty } => {
75            let user_ty = user_ty.as_ref().and_then(push_cuta);
76            // Under generic_const_args, `def_id` might be a regular const declared in a trait, but
77            // is `impl`d as a directly represented const. We do not know whether it is here, so we
78            // must use type system normalization for all consts under generic_const_args.
79            // FIXME(generic_const_args): there's a lot to consider here! `Const::Ty` uses valtrees
80            // and `Const::Unevaluated` does not, we should revisit this before stabilization.
81            if tcx.features().generic_const_args()
82                || #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(def_id) {
    DefKind::Const | DefKind::AssocConst => true,
    _ => false,
}matches!(tcx.def_kind(def_id), DefKind::Const | DefKind::AssocConst)
83                    && tcx.is_direct_const(def_id)
84            {
85                let uneval = ty::AliasConst::new(
86                    tcx,
87                    ty::AliasConstKind::new_from_def_id(
88                        tcx,
89                        def_id,
90                        ty::AliasConstInherentArgsKind::Impl,
91                    ),
92                    args,
93                );
94                let ct = ty::Const::new_alias(tcx, ty::IsRigid::No, uneval);
95
96                let const_ = Const::Ty(ty, ct);
97                return ConstOperand { span, user_ty, const_ };
98            }
99
100            let uneval = mir::UnevaluatedConst::new(def_id, args);
101            let const_ = Const::Unevaluated(uneval, ty);
102
103            ConstOperand { user_ty, span, const_ }
104        }
105        ExprKind::ConstParam { param, def_id: _ } => {
106            let const_param = ty::Const::new_param(tcx, param);
107            let const_ = Const::Ty(expr.ty, const_param);
108
109            ConstOperand { user_ty: None, span, const_ }
110        }
111        ExprKind::ConstBlock { did: def_id, args } => {
112            let uneval = mir::UnevaluatedConst::new(def_id, args);
113            let const_ = Const::Unevaluated(uneval, ty);
114
115            ConstOperand { user_ty: None, span, const_ }
116        }
117        ExprKind::StaticRef { alloc_id, ty, .. } => {
118            let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx));
119            let const_ = Const::Val(const_val, ty);
120
121            ConstOperand { span, user_ty: None, const_ }
122        }
123        _ => bug_impl(Some(span),
    format_args!("expression is not a valid constant {0:?}", kind),
    Location::caller())span_bug!(span, "expression is not a valid constant {:?}", kind),
124    }
125}
126
127{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
                ::tracing::Level::INFO <=
                    ::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("lit_to_mir_constant",
                                    "rustc_mir_build::builder::expr::as_constant",
                                    ::tracing::Level::INFO,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/as_constant.rs"),
                                    ::tracing_core::__macro_support::Option::Some(127u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_constant"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::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,
                        &{ meta.fields().value_set_all(&[]) })
                } 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: Const<'tcx> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let LitToConstInput { lit, ty, neg } = lit_input;
            let ty = ty.expect("type of literal must be known at this point");
            if let Err(guar) = ty.error_reported() {
                return Const::Ty(Ty::new_error(tcx, guar),
                        ty::Const::new_error(tcx, guar));
            }
            let lit_ty =
                match *ty.kind() { ty::Pat(base, _) => base, _ => ty, };
            let trunc =
                |n|
                    {
                        let width = lit_ty.primitive_size(tcx);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/as_constant.rs:144",
                                                "rustc_mir_build::builder::expr::as_constant",
                                                ::tracing::Level::TRACE,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/as_constant.rs"),
                                                ::tracing_core::__macro_support::Option::Some(144u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_constant"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::TRACE <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::TRACE <=
                                            ::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(&format_args!("trunc {0} with size {1} and shift {2}",
                                                                            n, width.bits(), 128 - width.bits()) as
                                                                    &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        let result = width.truncate(n);
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/as_constant.rs:146",
                                                "rustc_mir_build::builder::expr::as_constant",
                                                ::tracing::Level::TRACE,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_mir_build/src/builder/expr/as_constant.rs"),
                                                ::tracing_core::__macro_support::Option::Some(146u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_constant"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::TRACE <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::TRACE <=
                                            ::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(&format_args!("trunc result: {0}",
                                                                            result) as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        ConstValue::Scalar(Scalar::from_uint(result, width))
                    };
            let value =
                match (lit, lit_ty.kind()) {
                    (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if
                        inner_ty.is_str() => {
                        let s = s.as_str().as_bytes();
                        let len = s.len();
                        let allocation =
                            tcx.allocate_bytes_dedup(s, CTFE_ALLOC_SALT);
                        ConstValue::Slice {
                            alloc_id: allocation,
                            meta: len.try_into().unwrap(),
                        }
                    }
                    (ast::LitKind::ByteStr(byte_sym, _),
                        ty::Ref(_, inner_ty, _)) if
                        #[allow(non_exhaustive_omitted_patterns)] match inner_ty.kind()
                            {
                            ty::Slice(_) => true,
                            _ => false,
                        } => {
                        let data = byte_sym.as_byte_str();
                        let len = data.len();
                        let allocation =
                            tcx.allocate_bytes_dedup(data, CTFE_ALLOC_SALT);
                        ConstValue::Slice {
                            alloc_id: allocation,
                            meta: len.try_into().unwrap(),
                        }
                    }
                    (ast::LitKind::ByteStr(byte_sym, _),
                        ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
                        let id =
                            tcx.allocate_bytes_dedup(byte_sym.as_byte_str(),
                                CTFE_ALLOC_SALT);
                        ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
                    }
                    (ast::LitKind::CStr(byte_sym, _), ty::Ref(_, inner_ty, _))
                        if
                        #[allow(non_exhaustive_omitted_patterns)] match inner_ty.kind()
                            {
                            ty::Adt(def, _) if
                                tcx.is_lang_item(def.did(), LangItem::CStr) => true,
                            _ => false,
                        } => {
                        let data = byte_sym.as_byte_str();
                        let len = data.len();
                        let allocation =
                            tcx.allocate_bytes_dedup(data, CTFE_ALLOC_SALT);
                        ConstValue::Slice {
                            alloc_id: allocation,
                            meta: len.try_into().unwrap(),
                        }
                    }
                    (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
                        ConstValue::Scalar(Scalar::from_uint(n,
                                Size::from_bytes(1)))
                    }
                    (ast::LitKind::Int(n, _), ty::Uint(_)) if !neg =>
                        trunc(n.get()),
                    (ast::LitKind::Int(n, _), ty::Int(_)) => {
                        trunc(if neg {
                                u128::wrapping_neg(n.get())
                            } else { n.get() })
                    }
                    (ast::LitKind::Float(n, _), ty::Float(fty)) => {
                        parse_float_into_constval(n, *fty, neg).unwrap()
                    }
                    (ast::LitKind::Bool(b), ty::Bool) =>
                        ConstValue::Scalar(Scalar::from_bool(b)),
                    (ast::LitKind::Char(c), ty::Char) =>
                        ConstValue::Scalar(Scalar::from_char(c)),
                    (ast::LitKind::Err(guar), _) => {
                        return Const::Ty(Ty::new_error(tcx, guar),
                                ty::Const::new_error(tcx, guar));
                    }
                    _ =>
                        bug_impl(None,
                            format_args!("invalid lit/ty combination in `lit_to_mir_constant`: {0:?}: {1:?}",
                                lit, ty), Location::caller()),
                };
            Const::Val(value, ty)
        }
    }
}#[instrument(skip(tcx, lit_input))]
128fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx>) -> Const<'tcx> {
129    let LitToConstInput { lit, ty, neg } = lit_input;
130
131    let ty = ty.expect("type of literal must be known at this point");
132
133    if let Err(guar) = ty.error_reported() {
134        return Const::Ty(Ty::new_error(tcx, guar), ty::Const::new_error(tcx, guar));
135    }
136
137    let lit_ty = match *ty.kind() {
138        ty::Pat(base, _) => base,
139        _ => ty,
140    };
141
142    let trunc = |n| {
143        let width = lit_ty.primitive_size(tcx);
144        trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
145        let result = width.truncate(n);
146        trace!("trunc result: {}", result);
147        ConstValue::Scalar(Scalar::from_uint(result, width))
148    };
149
150    let value = match (lit, lit_ty.kind()) {
151        (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
152            let s = s.as_str().as_bytes();
153            let len = s.len();
154            let allocation = tcx.allocate_bytes_dedup(s, CTFE_ALLOC_SALT);
155            ConstValue::Slice { alloc_id: allocation, meta: len.try_into().unwrap() }
156        }
157        (ast::LitKind::ByteStr(byte_sym, _), ty::Ref(_, inner_ty, _))
158            if matches!(inner_ty.kind(), ty::Slice(_)) =>
159        {
160            let data = byte_sym.as_byte_str();
161            let len = data.len();
162            let allocation = tcx.allocate_bytes_dedup(data, CTFE_ALLOC_SALT);
163            ConstValue::Slice { alloc_id: allocation, meta: len.try_into().unwrap() }
164        }
165        (ast::LitKind::ByteStr(byte_sym, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
166            let id = tcx.allocate_bytes_dedup(byte_sym.as_byte_str(), CTFE_ALLOC_SALT);
167            ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
168        }
169        (ast::LitKind::CStr(byte_sym, _), ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::CStr)) =>
170        {
171            let data = byte_sym.as_byte_str();
172            let len = data.len();
173            let allocation = tcx.allocate_bytes_dedup(data, CTFE_ALLOC_SALT);
174            ConstValue::Slice { alloc_id: allocation, meta: len.try_into().unwrap() }
175        }
176        (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
177            ConstValue::Scalar(Scalar::from_uint(n, Size::from_bytes(1)))
178        }
179        (ast::LitKind::Int(n, _), ty::Uint(_)) if !neg => trunc(n.get()),
180        (ast::LitKind::Int(n, _), ty::Int(_)) => {
181            // Unsigned "negation" has the same bitwise effect as signed negation,
182            // which gets the result we want without additional casts.
183            trunc(if neg { u128::wrapping_neg(n.get()) } else { n.get() })
184        }
185        (ast::LitKind::Float(n, _), ty::Float(fty)) => {
186            parse_float_into_constval(n, *fty, neg).unwrap()
187        }
188        (ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(b)),
189        (ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(c)),
190        (ast::LitKind::Err(guar), _) => {
191            return Const::Ty(Ty::new_error(tcx, guar), ty::Const::new_error(tcx, guar));
192        }
193        _ => bug!("invalid lit/ty combination in `lit_to_mir_constant`: {lit:?}: {ty:?}"),
194    };
195
196    Const::Val(value, ty)
197}