rustc_const_eval/const_eval/
mod.rs

1// Not in interpret to make sure we do not use private implementation details
2
3use rustc_abi::VariantIdx;
4use rustc_middle::query::Key;
5use rustc_middle::ty::layout::LayoutOf;
6use rustc_middle::ty::{self, Ty, TyCtxt};
7use rustc_middle::{bug, mir};
8use tracing::instrument;
9
10use crate::interpret::InterpCx;
11
12mod dummy_machine;
13mod error;
14mod eval_queries;
15mod fn_queries;
16mod machine;
17mod valtrees;
18
19pub use self::dummy_machine::*;
20pub use self::error::*;
21pub use self::eval_queries::*;
22pub use self::fn_queries::*;
23pub use self::machine::*;
24pub(crate) use self::valtrees::{eval_to_valtree, valtree_to_const_value};
25
26// We forbid type-level constants that contain more than `VALTREE_MAX_NODES` nodes.
27const VALTREE_MAX_NODES: usize = 100000;
28
29pub(crate) enum ValTreeCreationError<'tcx> {
30    NodesOverflow,
31    /// Values of this type, or this particular value, are not supported as valtrees.
32    NonSupportedType(Ty<'tcx>),
33}
34pub(crate) type ValTreeCreationResult<'tcx> = Result<ty::ValTree<'tcx>, ValTreeCreationError<'tcx>>;
35
36#[instrument(skip(tcx), level = "debug")]
37pub(crate) fn try_destructure_mir_constant_for_user_output<'tcx>(
38    tcx: TyCtxt<'tcx>,
39    val: mir::ConstValue<'tcx>,
40    ty: Ty<'tcx>,
41) -> Option<mir::DestructuredConstant<'tcx>> {
42    let typing_env = ty::TypingEnv::fully_monomorphized();
43    // FIXME: use a proper span here?
44    let (ecx, op) = mk_eval_cx_for_const_val(tcx.at(rustc_span::DUMMY_SP), typing_env, val, ty)?;
45
46    // We go to `usize` as we cannot allocate anything bigger anyway.
47    let (field_count, variant, down) = match ty.kind() {
48        ty::Array(_, len) => (len.try_to_target_usize(tcx)? as usize, None, op),
49        ty::Adt(def, _) if def.variants().is_empty() => {
50            return None;
51        }
52        ty::Adt(def, _) => {
53            let variant = ecx.read_discriminant(&op).discard_err()?;
54            let down = ecx.project_downcast(&op, variant).discard_err()?;
55            (def.variants()[variant].fields.len(), Some(variant), down)
56        }
57        ty::Tuple(args) => (args.len(), None, op),
58        _ => bug!("cannot destructure mir constant {:?}", val),
59    };
60
61    let fields_iter = (0..field_count)
62        .map(|i| {
63            let field_op = ecx.project_field(&down, i).discard_err()?;
64            let val = op_to_const(&ecx, &field_op, /* for diagnostics */ true);
65            Some((val, field_op.layout.ty))
66        })
67        .collect::<Option<Vec<_>>>()?;
68    let fields = tcx.arena.alloc_from_iter(fields_iter);
69
70    Some(mir::DestructuredConstant { variant, fields })
71}
72
73/// Computes the tag (if any) for a given type and variant.
74#[instrument(skip(tcx), level = "debug")]
75pub fn tag_for_variant_provider<'tcx>(
76    tcx: TyCtxt<'tcx>,
77    (ty, variant_index): (Ty<'tcx>, VariantIdx),
78) -> Option<ty::ScalarInt> {
79    assert!(ty.is_enum());
80
81    // FIXME: This uses an empty `TypingEnv` even though
82    // it may be used by a generic CTFE.
83    let ecx = InterpCx::new(
84        tcx,
85        ty.default_span(tcx),
86        ty::TypingEnv::fully_monomorphized(),
87        crate::const_eval::DummyMachine,
88    );
89
90    let layout = ecx.layout_of(ty).unwrap();
91    ecx.tag_for_variant(layout, variant_index).unwrap().map(|(tag, _tag_field)| tag)
92}