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