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