Skip to main content

rustc_ty_utils/
consts.rs

1use rustc_errors::ErrorGuaranteed;
2use rustc_hir::def::DefKind;
3use rustc_hir::def_id::LocalDefId;
4use rustc_middle::query::Providers;
5use rustc_middle::thir::visit;
6use rustc_middle::thir::visit::Visitor;
7use rustc_middle::ty::abstract_const::CastKind;
8use rustc_middle::ty::{self, Expr, LitToConstInput, TyCtxt, TypeVisitableExt};
9use rustc_middle::{mir, thir};
10use rustc_span::Span;
11use tracing::instrument;
12
13use crate::errors::{GenericConstantTooComplex, GenericConstantTooComplexSub};
14
15/// We do not allow all binary operations in abstract consts, so filter disallowed ones.
16fn check_binop(op: mir::BinOp) -> bool {
17    use mir::BinOp::*;
18    match op {
19        Add | AddUnchecked | AddWithOverflow | Sub | SubUnchecked | SubWithOverflow | Mul
20        | MulUnchecked | MulWithOverflow | Div | Rem | BitXor | BitAnd | BitOr | Shl
21        | ShlUnchecked | Shr | ShrUnchecked | Eq | Lt | Le | Ne | Ge | Gt | Cmp => true,
22        Offset => false,
23    }
24}
25
26/// While we currently allow all unary operations, we still want to explicitly guard against
27/// future changes here.
28fn check_unop(op: mir::UnOp) -> bool {
29    use mir::UnOp::*;
30    match op {
31        Not | Neg | PtrMetadata => true,
32    }
33}
34
35fn recurse_build<'tcx>(
36    tcx: TyCtxt<'tcx>,
37    body: &thir::Thir<'tcx>,
38    node: thir::ExprId,
39    root_span: Span,
40) -> Result<ty::Const<'tcx>, ErrorGuaranteed> {
41    use thir::ExprKind;
42    let node = &body.exprs[node];
43
44    let maybe_supported_error = |a| maybe_supported_error(tcx, a, root_span);
45    let error = |a| error(tcx, a, root_span);
46
47    Ok(match &node.kind {
48        // I dont know if handling of these 3 is correct
49        &ExprKind::Scope { value, .. } => recurse_build(tcx, body, value, root_span)?,
50        &ExprKind::PlaceTypeAscription { source, .. }
51        | &ExprKind::ValueTypeAscription { source, .. } => {
52            recurse_build(tcx, body, source, root_span)?
53        }
54        &ExprKind::PlaceUnwrapUnsafeBinder { .. }
55        | &ExprKind::ValueUnwrapUnsafeBinder { .. }
56        | &ExprKind::WrapUnsafeBinder { .. } => {
57            {
    ::core::panicking::panic_fmt(format_args!("not yet implemented: {0}",
            format_args!("FIXME(unsafe_binders)")));
}todo!("FIXME(unsafe_binders)")
58        }
59        &ExprKind::Literal { lit, neg } => {
60            let sp = node.span;
61            match tcx.at(sp).lit_to_const(LitToConstInput { lit: lit.node, ty: node.ty, neg }) {
62                Some(value) => ty::Const::new_value(tcx, value.valtree, value.ty),
63                None => ty::Const::new_misc_error(tcx),
64            }
65        }
66        &ExprKind::NonHirLiteral { lit, user_ty: _ } => {
67            let val = ty::ValTree::from_scalar_int(tcx, lit);
68            ty::Const::new_value(tcx, val, node.ty)
69        }
70        &ExprKind::ZstLiteral { user_ty: _ } => ty::Const::zero_sized(tcx, node.ty),
71        &ExprKind::NamedConst { def_id, args, user_ty: _ } => {
72            let uneval = ty::UnevaluatedConst::new(def_id, args);
73            ty::Const::new_unevaluated(tcx, uneval)
74        }
75        ExprKind::ConstParam { param, .. } => ty::Const::new_param(tcx, *param),
76
77        ExprKind::Call { fun, args, .. } => {
78            let fun_ty = body.exprs[*fun].ty;
79            let fun = recurse_build(tcx, body, *fun, root_span)?;
80
81            let mut new_args = Vec::<ty::Const<'tcx>>::with_capacity(args.len());
82            for &id in args.iter() {
83                new_args.push(recurse_build(tcx, body, id, root_span)?);
84            }
85            ty::Const::new_expr(tcx, Expr::new_call(tcx, fun_ty, fun, new_args))
86        }
87        &ExprKind::Binary { op, lhs, rhs } if check_binop(op) => {
88            let lhs_ty = body.exprs[lhs].ty;
89            let lhs = recurse_build(tcx, body, lhs, root_span)?;
90            let rhs_ty = body.exprs[rhs].ty;
91            let rhs = recurse_build(tcx, body, rhs, root_span)?;
92            ty::Const::new_expr(tcx, Expr::new_binop(tcx, op, lhs_ty, rhs_ty, lhs, rhs))
93        }
94        &ExprKind::Unary { op, arg } if check_unop(op) => {
95            let arg_ty = body.exprs[arg].ty;
96            let arg = recurse_build(tcx, body, arg, root_span)?;
97            ty::Const::new_expr(tcx, Expr::new_unop(tcx, op, arg_ty, arg))
98        }
99        // This is necessary so that the following compiles:
100        //
101        // ```
102        // fn foo<const N: usize>(a: [(); N + 1]) {
103        //     bar::<{ N + 1 }>();
104        // }
105        // ```
106        ExprKind::Block { block } => {
107            if let thir::Block { stmts: box [], expr: Some(e), .. } = &body.blocks[*block] {
108                recurse_build(tcx, body, *e, root_span)?
109            } else {
110                maybe_supported_error(GenericConstantTooComplexSub::BlockNotSupported(node.span))?
111            }
112        }
113        // `ExprKind::Use` happens when a `hir::ExprKind::Cast` is a
114        // "coercion cast" i.e. using a coercion or is a no-op.
115        // This is important so that `N as usize as usize` doesn't unify with `N as usize`. (untested)
116        &ExprKind::Use { source } => {
117            let value_ty = body.exprs[source].ty;
118            let value = recurse_build(tcx, body, source, root_span)?;
119            ty::Const::new_expr(tcx, Expr::new_cast(tcx, CastKind::Use, value_ty, value, node.ty))
120        }
121        &ExprKind::Cast { source } => {
122            let value_ty = body.exprs[source].ty;
123            let value = recurse_build(tcx, body, source, root_span)?;
124            ty::Const::new_expr(tcx, Expr::new_cast(tcx, CastKind::As, value_ty, value, node.ty))
125        }
126        ExprKind::Borrow { arg, .. } => {
127            let arg_node = &body.exprs[*arg];
128
129            // Skip reborrows for now until we allow Deref/Borrow/RawBorrow
130            // expressions.
131            // FIXME(generic_const_exprs): Verify/explain why this is sound
132            if let ExprKind::Deref { arg } = arg_node.kind {
133                recurse_build(tcx, body, arg, root_span)?
134            } else {
135                maybe_supported_error(GenericConstantTooComplexSub::BorrowNotSupported(node.span))?
136            }
137        }
138        // FIXME(generic_const_exprs): We may want to support these.
139        ExprKind::RawBorrow { .. } | ExprKind::Deref { .. } => maybe_supported_error(
140            GenericConstantTooComplexSub::AddressAndDerefNotSupported(node.span),
141        )?,
142        ExprKind::Repeat { .. } | ExprKind::Array { .. } => {
143            maybe_supported_error(GenericConstantTooComplexSub::ArrayNotSupported(node.span))?
144        }
145        ExprKind::NeverToAny { .. } => {
146            maybe_supported_error(GenericConstantTooComplexSub::NeverToAnyNotSupported(node.span))?
147        }
148        ExprKind::Tuple { .. } => {
149            maybe_supported_error(GenericConstantTooComplexSub::TupleNotSupported(node.span))?
150        }
151        ExprKind::Index { .. } => {
152            maybe_supported_error(GenericConstantTooComplexSub::IndexNotSupported(node.span))?
153        }
154        ExprKind::Field { .. } => {
155            maybe_supported_error(GenericConstantTooComplexSub::FieldNotSupported(node.span))?
156        }
157        ExprKind::ConstBlock { .. } => {
158            maybe_supported_error(GenericConstantTooComplexSub::ConstBlockNotSupported(node.span))?
159        }
160        ExprKind::Adt(_) => {
161            maybe_supported_error(GenericConstantTooComplexSub::AdtNotSupported(node.span))?
162        }
163        // dont know if this is correct
164        ExprKind::PointerCoercion { .. } => {
165            error(GenericConstantTooComplexSub::PointerNotSupported(node.span))?
166        }
167        ExprKind::Yield { .. } => {
168            error(GenericConstantTooComplexSub::YieldNotSupported(node.span))?
169        }
170        ExprKind::Continue { .. }
171        | ExprKind::ConstContinue { .. }
172        | ExprKind::Break { .. }
173        | ExprKind::Loop { .. }
174        | ExprKind::LoopMatch { .. } => {
175            error(GenericConstantTooComplexSub::LoopNotSupported(node.span))?
176        }
177        ExprKind::ByUse { .. } => {
178            error(GenericConstantTooComplexSub::ByUseNotSupported(node.span))?
179        }
180        ExprKind::Unary { .. } => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
181        // we handle valid unary/binary ops above
182        ExprKind::Binary { .. } => {
183            error(GenericConstantTooComplexSub::BinaryNotSupported(node.span))?
184        }
185        ExprKind::LogicalOp { .. } => {
186            error(GenericConstantTooComplexSub::LogicalOpNotSupported(node.span))?
187        }
188        ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
189            error(GenericConstantTooComplexSub::AssignNotSupported(node.span))?
190        }
191        // FIXME(explicit_tail_calls): maybe get `become` a new error
192        ExprKind::Closure { .. } | ExprKind::Return { .. } | ExprKind::Become { .. } => {
193            error(GenericConstantTooComplexSub::ClosureAndReturnNotSupported(node.span))?
194        }
195        // let expressions imply control flow
196        ExprKind::Match { .. } | ExprKind::If { .. } | ExprKind::Let { .. } => {
197            error(GenericConstantTooComplexSub::ControlFlowNotSupported(node.span))?
198        }
199        ExprKind::InlineAsm { .. } => {
200            error(GenericConstantTooComplexSub::InlineAsmNotSupported(node.span))?
201        }
202
203        // we dont permit let stmts so `VarRef` and `UpvarRef` cant happen
204        ExprKind::VarRef { .. }
205        | ExprKind::UpvarRef { .. }
206        | ExprKind::StaticRef { .. }
207        | ExprKind::ThreadLocalRef(_) => {
208            error(GenericConstantTooComplexSub::OperationNotSupported(node.span))?
209        }
210    })
211}
212
213struct IsThirPolymorphic<'a, 'tcx> {
214    is_poly: bool,
215    thir: &'a thir::Thir<'tcx>,
216}
217
218fn error(
219    tcx: TyCtxt<'_>,
220    sub: GenericConstantTooComplexSub,
221    root_span: Span,
222) -> Result<!, ErrorGuaranteed> {
223    let reported = tcx.dcx().emit_err(GenericConstantTooComplex {
224        span: root_span,
225        maybe_supported: false,
226        sub,
227    });
228
229    Err(reported)
230}
231
232fn maybe_supported_error(
233    tcx: TyCtxt<'_>,
234    sub: GenericConstantTooComplexSub,
235    root_span: Span,
236) -> Result<!, ErrorGuaranteed> {
237    let reported = tcx.dcx().emit_err(GenericConstantTooComplex {
238        span: root_span,
239        maybe_supported: true,
240        sub,
241    });
242
243    Err(reported)
244}
245
246impl<'a, 'tcx> IsThirPolymorphic<'a, 'tcx> {
247    fn expr_is_poly(&mut self, expr: &thir::Expr<'tcx>) -> bool {
248        if expr.ty.has_non_region_param() {
249            return true;
250        }
251
252        match expr.kind {
253            thir::ExprKind::NamedConst { args, .. } | thir::ExprKind::ConstBlock { args, .. } => {
254                args.has_non_region_param()
255            }
256            thir::ExprKind::ConstParam { .. } => true,
257            thir::ExprKind::Repeat { value, count } => {
258                self.visit_expr(&self.thir()[value]);
259                count.has_non_region_param()
260            }
261            thir::ExprKind::Scope { .. }
262            | thir::ExprKind::If { .. }
263            | thir::ExprKind::Call { .. }
264            | thir::ExprKind::ByUse { .. }
265            | thir::ExprKind::Deref { .. }
266            | thir::ExprKind::Binary { .. }
267            | thir::ExprKind::LogicalOp { .. }
268            | thir::ExprKind::Unary { .. }
269            | thir::ExprKind::Cast { .. }
270            | thir::ExprKind::Use { .. }
271            | thir::ExprKind::NeverToAny { .. }
272            | thir::ExprKind::PointerCoercion { .. }
273            | thir::ExprKind::Loop { .. }
274            | thir::ExprKind::LoopMatch { .. }
275            | thir::ExprKind::Let { .. }
276            | thir::ExprKind::Match { .. }
277            | thir::ExprKind::Block { .. }
278            | thir::ExprKind::Assign { .. }
279            | thir::ExprKind::AssignOp { .. }
280            | thir::ExprKind::Field { .. }
281            | thir::ExprKind::Index { .. }
282            | thir::ExprKind::VarRef { .. }
283            | thir::ExprKind::UpvarRef { .. }
284            | thir::ExprKind::Borrow { .. }
285            | thir::ExprKind::RawBorrow { .. }
286            | thir::ExprKind::Break { .. }
287            | thir::ExprKind::Continue { .. }
288            | thir::ExprKind::ConstContinue { .. }
289            | thir::ExprKind::Return { .. }
290            | thir::ExprKind::Become { .. }
291            | thir::ExprKind::Array { .. }
292            | thir::ExprKind::Tuple { .. }
293            | thir::ExprKind::Adt(_)
294            | thir::ExprKind::PlaceTypeAscription { .. }
295            | thir::ExprKind::ValueTypeAscription { .. }
296            | thir::ExprKind::PlaceUnwrapUnsafeBinder { .. }
297            | thir::ExprKind::ValueUnwrapUnsafeBinder { .. }
298            | thir::ExprKind::WrapUnsafeBinder { .. }
299            | thir::ExprKind::Closure(_)
300            | thir::ExprKind::Literal { .. }
301            | thir::ExprKind::NonHirLiteral { .. }
302            | thir::ExprKind::ZstLiteral { .. }
303            | thir::ExprKind::StaticRef { .. }
304            | thir::ExprKind::InlineAsm(_)
305            | thir::ExprKind::ThreadLocalRef(_)
306            | thir::ExprKind::Yield { .. } => false,
307        }
308    }
309    fn pat_is_poly(&mut self, pat: &thir::Pat<'tcx>) -> bool {
310        if pat.ty.has_non_region_param() {
311            return true;
312        }
313
314        match pat.kind {
315            thir::PatKind::Constant { value } => value.has_non_region_param(),
316            thir::PatKind::Range(ref range) => {
317                let &thir::PatRange { lo, hi, .. } = range.as_ref();
318                lo.has_non_region_param() || hi.has_non_region_param()
319            }
320            _ => false,
321        }
322    }
323}
324
325impl<'a, 'tcx> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> {
326    fn thir(&self) -> &'a thir::Thir<'tcx> {
327        self.thir
328    }
329
330    #[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("visit_expr",
                                    "rustc_ty_utils::consts", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/consts.rs"),
                                    ::tracing_core::__macro_support::Option::Some(330u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::consts"),
                                    ::tracing_core::field::FieldSet::new(&["expr"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
                                                            as &dyn 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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.is_poly |= self.expr_is_poly(expr);
            if !self.is_poly { visit::walk_expr(self, expr) }
        }
    }
}#[instrument(skip(self), level = "debug")]
331    fn visit_expr(&mut self, expr: &'a thir::Expr<'tcx>) {
332        self.is_poly |= self.expr_is_poly(expr);
333        if !self.is_poly {
334            visit::walk_expr(self, expr)
335        }
336    }
337
338    #[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("visit_pat",
                                    "rustc_ty_utils::consts", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_ty_utils/src/consts.rs"),
                                    ::tracing_core::__macro_support::Option::Some(338u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_ty_utils::consts"),
                                    ::tracing_core::field::FieldSet::new(&["pat"],
                                        ::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};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat)
                                                            as &dyn 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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.is_poly |= self.pat_is_poly(pat);
            if !self.is_poly { visit::walk_pat(self, pat); }
        }
    }
}#[instrument(skip(self), level = "debug")]
339    fn visit_pat(&mut self, pat: &'a thir::Pat<'tcx>) {
340        self.is_poly |= self.pat_is_poly(pat);
341        if !self.is_poly {
342            visit::walk_pat(self, pat);
343        }
344    }
345}
346
347/// Builds an abstract const, do not use this directly, but use `AbstractConst::new` instead.
348fn thir_abstract_const<'tcx>(
349    tcx: TyCtxt<'tcx>,
350    def: LocalDefId,
351) -> Result<Option<ty::EarlyBinder<'tcx, ty::Const<'tcx>>>, ErrorGuaranteed> {
352    if !tcx.features().generic_const_exprs() {
353        return Ok(None);
354    }
355
356    match tcx.def_kind(def) {
357        // FIXME(generic_const_exprs): We currently only do this for anonymous constants,
358        // meaning that we do not look into associated constants. I(@lcnr) am not yet sure whether
359        // we want to look into them or treat them as opaque projections.
360        //
361        // Right now we do neither of that and simply always fail to unify them.
362        DefKind::AnonConst | DefKind::InlineConst => (),
363        _ => return Ok(None),
364    }
365
366    let body = tcx.thir_body(def)?;
367    let (body, body_id) = (&*body.0.borrow(), body.1);
368
369    let mut is_poly_vis = IsThirPolymorphic { is_poly: false, thir: body };
370    visit::walk_expr(&mut is_poly_vis, &body[body_id]);
371    if !is_poly_vis.is_poly {
372        return Ok(None);
373    }
374
375    let root_span = body.exprs[body_id].span;
376
377    Ok(Some(ty::EarlyBinder::bind(recurse_build(tcx, body, body_id, root_span)?)))
378}
379
380pub(crate) fn provide(providers: &mut Providers) {
381    *providers = Providers { thir_abstract_const, ..*providers };
382}