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::{FieldIdx, VariantIdx};
4use rustc_middle::query::Key;
5use rustc_middle::ty::{self, Ty, TyCtxt};
6use rustc_middle::{bug, mir};
7use tracing::instrument;
8
9use crate::interpret::InterpCx;
10
11mod dummy_machine;
12mod error;
13mod eval_queries;
14mod fn_queries;
15mod machine;
16mod valtrees;
17
18pub use self::dummy_machine::*;
19pub use self::error::*;
20pub use self::eval_queries::*;
21pub use self::fn_queries::*;
22pub use self::machine::*;
23pub(crate) use self::valtrees::{eval_to_valtree, valtree_to_const_value};
24
25// We forbid type-level constants that contain more than `VALTREE_MAX_NODES` nodes.
26const VALTREE_MAX_NODES: usize = 100000;
27
28#[instrument(skip(tcx), level = "debug")]
29pub(crate) fn try_destructure_mir_constant_for_user_output<'tcx>(
30    tcx: TyCtxt<'tcx>,
31    val: mir::ConstValue<'tcx>,
32    ty: Ty<'tcx>,
33) -> Option<mir::DestructuredConstant<'tcx>> {
34    let typing_env = ty::TypingEnv::fully_monomorphized();
35    // FIXME: use a proper span here?
36    let (ecx, op) = mk_eval_cx_for_const_val(tcx.at(rustc_span::DUMMY_SP), typing_env, val, ty)?;
37
38    // We go to `usize` as we cannot allocate anything bigger anyway.
39    let (field_count, variant, down) = match ty.kind() {
40        ty::Array(_, len) => (len.try_to_target_usize(tcx)? as usize, None, op),
41        ty::Adt(def, _) if def.variants().is_empty() => {
42            return None;
43        }
44        ty::Adt(def, _) => {
45            let variant = ecx.read_discriminant(&op).discard_err()?;
46            let down = ecx.project_downcast(&op, variant).discard_err()?;
47            (def.variants()[variant].fields.len(), Some(variant), down)
48        }
49        ty::Tuple(args) => (args.len(), None, op),
50        _ => bug!("cannot destructure mir constant {:?}", val),
51    };
52
53    let fields_iter = (0..field_count)
54        .map(|i| {
55            let field_op = ecx.project_field(&down, FieldIdx::from_usize(i)).discard_err()?;
56            let val = op_to_const(&ecx, &field_op, /* for diagnostics */ true);
57            Some((val, field_op.layout.ty))
58        })
59        .collect::<Option<Vec<_>>>()?;
60    let fields = tcx.arena.alloc_from_iter(fields_iter);
61
62    Some(mir::DestructuredConstant { variant, fields })
63}
64
65/// Computes the tag (if any) for a given type and variant.
66#[instrument(skip(tcx), level = "debug")]
67pub fn tag_for_variant_provider<'tcx>(
68    tcx: TyCtxt<'tcx>,
69    key: ty::PseudoCanonicalInput<'tcx, (Ty<'tcx>, VariantIdx)>,
70) -> Option<ty::ScalarInt> {
71    let (ty, variant_index) = key.value;
72    assert!(ty.is_enum());
73
74    let ecx =
75        InterpCx::new(tcx, ty.default_span(tcx), key.typing_env, crate::const_eval::DummyMachine);
76
77    let layout = ecx.layout_of(ty).unwrap();
78    ecx.tag_for_variant(layout, variant_index).unwrap().map(|(tag, _tag_field)| tag)
79}