rust_verify_test coverage (7c1d655)

Coverage Report

Created: 2026-07-20 10:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
rustc_mir_build/src/builder/expr/as_constant.rs
Line
Count
Source
1
//! See docs in builder/expr/mod.rs
2
3
use rustc_abi::Size;
4
use rustc_ast as ast;
5
use rustc_hir::LangItem;
6
use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, Scalar};
7
use rustc_middle::mir::*;
8
use rustc_middle::thir::*;
9
use rustc_middle::ty::{
10
    self, CanonicalUserType, CanonicalUserTypeAnnotation, LitToConstInput, Ty, TyCtxt,
11
    TypeVisitableExt as _, UserTypeAnnotationIndex,
12
};
13
use rustc_middle::{bug, mir, span_bug};
14
use tracing::{instrument, trace};
15
16
use crate::builder::{Builder, parse_float_into_constval};
17
18
impl<'a, 'tcx> Builder<'a, 'tcx> {
19
    /// Compile `expr`, yielding a compile-time constant. Assumes that
20
    /// `expr` is a valid compile-time constant!
21
1.09M
    pub(crate) fn as_constant(&mut self, expr: &Expr<'tcx>) -> ConstOperand<'tcx> {
22
1.09M
        let this = self; // See "LET_THIS_SELF".
23
1.09M
        let tcx = this.tcx;
24
1.09M
        let Expr { ty, temp_scope_id: _, span, ref kind } = *expr;
25
1.09M
        match kind {
26
0
            ExprKind::Scope { region_scope: _, hir_id: _, value } => {
27
0
                this.as_constant(&this.thir[*value])
28
            }
29
1.09M
            _ => as_constant_inner(
30
1.09M
                expr,
31
22.2k
                |user_ty| {
32
22.2k
                    Some(this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
33
22.2k
                        span,
34
22.2k
                        user_ty: user_ty.clone(),
35
22.2k
                        inferred_ty: ty,
36
22.2k
                    }))
37
22.2k
                },
38
1.09M
                tcx,
39
            ),
40
        }
41
1.09M
    }
42
}
43
44
1.09M
pub(crate) fn as_constant_inner<'tcx>(
45
1.09M
    expr: &Expr<'tcx>,
46
1.09M
    push_cuta: impl FnMut(&Box<CanonicalUserType<'tcx>>) -> Option<UserTypeAnnotationIndex>,
47
1.09M
    tcx: TyCtxt<'tcx>,
48
1.09M
) -> ConstOperand<'tcx> {
49
1.09M
    let Expr { ty, temp_scope_id: _, span, ref kind } = *expr;
50
51
1.09M
    match *kind {
52
30.9k
        ExprKind::Literal { lit, neg } => {
53
30.9k
            let const_ =
54
30.9k
                lit_to_mir_constant(tcx, LitToConstInput { lit: lit.node, ty: Some(ty), neg });
55
56
30.9k
            ConstOperand { span, user_ty: None, const_ }
57
        }
58
0
        ExprKind::NonHirLiteral { lit, ref user_ty } => {
59
0
            let user_ty = user_ty.as_ref().and_then(push_cuta);
60
61
0
            let const_ = Const::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
62
63
0
            ConstOperand { span, user_ty, const_ }
64
        }
65
1.05M
        ExprKind::ZstLiteral { ref user_ty } => {
66
1.05M
            let user_ty = user_ty.as_ref().and_then(push_cuta);
67
68
1.05M
            let const_ = Const::Val(ConstValue::ZeroSized, ty);
69
70
1.05M
            ConstOperand { span, user_ty, const_ }
71
        }
72
1.53k
        ExprKind::NamedConst { def_id, args, ref user_ty } => {
73
1.53k
            let user_ty = user_ty.as_ref().and_then(push_cuta);
74
1.53k
            if tcx.is_type_const(def_id) {
75
0
                let uneval = ty::UnevaluatedConst::new(def_id, args);
76
0
                let ct = ty::Const::new_unevaluated(tcx, uneval);
77
78
0
                let const_ = Const::Ty(ty, ct);
79
0
                return ConstOperand { span, user_ty, const_ };
80
1.53k
            }
81
82
1.53k
            let uneval = mir::UnevaluatedConst::new(def_id, args);
83
1.53k
            let const_ = Const::Unevaluated(uneval, ty);
84
85
1.53k
            ConstOperand { user_ty, span, const_ }
86
        }
87
5
        ExprKind::ConstParam { param, def_id: _ } => {
88
5
            let const_param = ty::Const::new_param(tcx, param);
89
5
            let const_ = Const::Ty(expr.ty, const_param);
90
91
5
            ConstOperand { user_ty: None, span, const_ }
92
        }
93
0
        ExprKind::ConstBlock { did: def_id, args } => {
94
0
            let uneval = mir::UnevaluatedConst::new(def_id, args);
95
0
            let const_ = Const::Unevaluated(uneval, ty);
96
97
0
            ConstOperand { user_ty: None, span, const_ }
98
        }
99
15
        ExprKind::StaticRef { alloc_id, ty, .. } => {
100
15
            let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx));
101
15
            let const_ = Const::Val(const_val, ty);
102
103
15
            ConstOperand { span, user_ty: None, const_ }
104
        }
105
0
        _ => span_bug!(span, "expression is not a valid constant {:?}", kind),
106
    }
107
1.09M
}
_RINvNtNtNtCsdd3slutIhk3_15rustc_mir_build7builder4expr11as_constant17as_constant_innerNCNvMB2_NtB6_7Builder11as_constant0EB8_
Line
Count
Source
44
1.09M
pub(crate) fn as_constant_inner<'tcx>(
45
1.09M
    expr: &Expr<'tcx>,
46
1.09M
    push_cuta: impl FnMut(&Box<CanonicalUserType<'tcx>>) -> Option<UserTypeAnnotationIndex>,
47
1.09M
    tcx: TyCtxt<'tcx>,
48
1.09M
) -> ConstOperand<'tcx> {
49
1.09M
    let Expr { ty, temp_scope_id: _, span, ref kind } = *expr;
50
51
1.09M
    match *kind {
52
30.9k
        ExprKind::Literal { lit, neg } => {
53
30.9k
            let const_ =
54
30.9k
                lit_to_mir_constant(tcx, LitToConstInput { lit: lit.node, ty: Some(ty), neg });
55
56
30.9k
            ConstOperand { span, user_ty: None, const_ }
57
        }
58
0
        ExprKind::NonHirLiteral { lit, ref user_ty } => {
59
0
            let user_ty = user_ty.as_ref().and_then(push_cuta);
60
61
0
            let const_ = Const::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
62
63
0
            ConstOperand { span, user_ty, const_ }
64
        }
65
1.05M
        ExprKind::ZstLiteral { ref user_ty } => {
66
1.05M
            let user_ty = user_ty.as_ref().and_then(push_cuta);
67
68
1.05M
            let const_ = Const::Val(ConstValue::ZeroSized, ty);
69
70
1.05M
            ConstOperand { span, user_ty, const_ }
71
        }
72
1.53k
        ExprKind::NamedConst { def_id, args, ref user_ty } => {
73
1.53k
            let user_ty = user_ty.as_ref().and_then(push_cuta);
74
1.53k
            if tcx.is_type_const(def_id) {
75
0
                let uneval = ty::UnevaluatedConst::new(def_id, args);
76
0
                let ct = ty::Const::new_unevaluated(tcx, uneval);
77
78
0
                let const_ = Const::Ty(ty, ct);
79
0
                return ConstOperand { span, user_ty, const_ };
80
1.53k
            }
81
82
1.53k
            let uneval = mir::UnevaluatedConst::new(def_id, args);
83
1.53k
            let const_ = Const::Unevaluated(uneval, ty);
84
85
1.53k
            ConstOperand { user_ty, span, const_ }
86
        }
87
5
        ExprKind::ConstParam { param, def_id: _ } => {
88
5
            let const_param = ty::Const::new_param(tcx, param);
89
5
            let const_ = Const::Ty(expr.ty, const_param);
90
91
5
            ConstOperand { user_ty: None, span, const_ }
92
        }
93
0
        ExprKind::ConstBlock { did: def_id, args } => {
94
0
            let uneval = mir::UnevaluatedConst::new(def_id, args);
95
0
            let const_ = Const::Unevaluated(uneval, ty);
96
97
0
            ConstOperand { user_ty: None, span, const_ }
98
        }
99
15
        ExprKind::StaticRef { alloc_id, ty, .. } => {
100
15
            let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx));
101
15
            let const_ = Const::Val(const_val, ty);
102
103
15
            ConstOperand { span, user_ty: None, const_ }
104
        }
105
0
        _ => span_bug!(span, "expression is not a valid constant {:?}", kind),
106
    }
107
1.09M
}
Unexecuted instantiation: _RINvNtNtNtCsdd3slutIhk3_15rustc_mir_build7builder4expr11as_constant17as_constant_innerNCNvMNtNtNtB6_6custom5parse11instructionNtB1v_9ParseCtxt13parse_operand0EB8_
Unexecuted instantiation: _RINvNtNtNtCsdd3slutIhk3_15rustc_mir_build7builder4expr11as_constant17as_constant_innerNCNvMNtNtNtB6_6custom5parse11instructionNtB1v_9ParseCtxt21parse_integer_literal0EB8_
108
109
#[instrument(skip(tcx, lit_input))]
110
30.9k
fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx>) -> Const<'tcx> {
111
30.9k
    let LitToConstInput { lit, ty, neg } = lit_input;
112
113
30.9k
    let ty = ty.expect("type of literal must be known at this point");
114
115
30.9k
    if let Err(guar) = ty.error_reported() {
116
0
        return Const::Ty(Ty::new_error(tcx, guar), ty::Const::new_error(tcx, guar));
117
30.9k
    }
118
119
30.9k
    let lit_ty = match *ty.kind() {
120
0
        ty::Pat(base, _) => base,
121
30.9k
        _ => ty,
122
    };
123
124
30.9k
    let trunc = |n| {
125
13.2k
        let width = lit_ty.primitive_size(tcx);
126
13.2k
        trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
127
13.2k
        let result = width.truncate(n);
128
13.2k
        trace!("trunc result: {}", result);
129
13.2k
        ConstValue::Scalar(Scalar::from_uint(result, width))
130
13.2k
    };
131
132
30.9k
    let value = match (lit, lit_ty.kind()) {
133
16.2k
        (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
134
16.2k
            let s = s.as_str().as_bytes();
135
16.2k
            let len = s.len();
136
16.2k
            let allocation = tcx.allocate_bytes_dedup(s, CTFE_ALLOC_SALT);
137
16.2k
            ConstValue::Slice { alloc_id: allocation, meta: len.try_into().unwrap() }
138
        }
139
0
        (ast::LitKind::ByteStr(byte_sym, _), ty::Ref(_, inner_ty, _))
140
0
            if matches!(inner_ty.kind(), ty::Slice(_)) =>
141
        {
142
0
            let data = byte_sym.as_byte_str();
143
0
            let len = data.len();
144
0
            let allocation = tcx.allocate_bytes_dedup(data, CTFE_ALLOC_SALT);
145
0
            ConstValue::Slice { alloc_id: allocation, meta: len.try_into().unwrap() }
146
        }
147
0
        (ast::LitKind::ByteStr(byte_sym, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
148
0
            let id = tcx.allocate_bytes_dedup(byte_sym.as_byte_str(), CTFE_ALLOC_SALT);
149
0
            ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
150
        }
151
0
        (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)) =>
152
        {
153
0
            let data = byte_sym.as_byte_str();
154
0
            let len = data.len();
155
0
            let allocation = tcx.allocate_bytes_dedup(data, CTFE_ALLOC_SALT);
156
0
            ConstValue::Slice { alloc_id: allocation, meta: len.try_into().unwrap() }
157
        }
158
0
        (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
159
0
            ConstValue::Scalar(Scalar::from_uint(n, Size::from_bytes(1)))
160
        }
161
9.85k
        (ast::LitKind::Int(n, _), ty::Uint(_)) if !neg => trunc(n.get()),
162
3.43k
        (ast::LitKind::Int(n, _), ty::Int(_)) => {
163
            // Unsigned "negation" has the same bitwise effect as signed negation,
164
            // which gets the result we want without additional casts.
165
3.43k
            trunc(if neg { u128::wrapping_neg(n.get()) } else { n.get() })
166
        }
167
8
        (ast::LitKind::Float(n, _), ty::Float(fty)) => {
168
8
            parse_float_into_constval(n, *fty, neg).unwrap()
169
        }
170
1.32k
        (ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(b)),
171
28
        (ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(c)),
172
0
        (ast::LitKind::Err(guar), _) => {
173
0
            return Const::Ty(Ty::new_error(tcx, guar), ty::Const::new_error(tcx, guar));
174
        }
175
0
        _ => bug!("invalid lit/ty combination in `lit_to_mir_constant`: {lit:?}: {ty:?}"),
176
    };
177
178
30.9k
    Const::Val(value, ty)
179
30.9k
}