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