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