Skip to main content

rustc_const_eval/interpret/
util.rs

1use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId};
2use rustc_infer::infer::TyCtxtInferExt;
3use rustc_infer::traits::{Obligation, ObligationCause};
4use rustc_middle::mir::interpret::{AllocInit, Allocation, GlobalAlloc, InterpResult, Pointer};
5use rustc_middle::ty::layout::TyAndLayout;
6use rustc_middle::ty::{PolyExistentialPredicate, Ty, TyCtxt, TypeVisitable, TypeVisitableExt};
7use rustc_middle::{mir, span_bug, ty};
8use rustc_trait_selection::traits::ObligationCtxt;
9use tracing::debug;
10
11use super::{InterpCx, MPlaceTy, MemoryKind, interp_ok, throw_inval};
12use crate::const_eval::{CompileTimeInterpCx, CompileTimeMachine, InterpretationResult};
13use crate::interpret::Machine;
14
15/// Checks if a type implements predicates.
16/// Calls `ensure_monomorphic_enough` on `ty` and `trait_ty` for you.
17pub(crate) fn type_implements_dyn_trait<'tcx, M: Machine<'tcx>>(
18    ecx: &mut InterpCx<'tcx, M>,
19    ty: Ty<'tcx>,
20    trait_ty: Ty<'tcx>,
21) -> InterpResult<'tcx, (bool, &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>)> {
22    ensure_monomorphic_enough(ty)?;
23    ensure_monomorphic_enough(trait_ty)?;
24
25    let ty::Dynamic(preds, _) = trait_ty.kind() else {
26        ::rustc_middle::util::bug::span_bug_fmt(ecx.find_closest_untracked_caller_location(),
    format_args!("Invalid type provided to type_implements_predicates. U must be dyn Trait, got {0}.",
        trait_ty));span_bug!(
27            ecx.find_closest_untracked_caller_location(),
28            "Invalid type provided to type_implements_predicates. U must be dyn Trait, got {trait_ty}."
29        );
30    };
31
32    let (infcx, param_env) = ecx.tcx.infer_ctxt().build_with_typing_env(ty::TypingEnv::new(
33        ecx.typing_env.param_env,
34        ty::TypingMode::Reflection,
35    ));
36
37    let ocx = ObligationCtxt::new(&infcx);
38    ocx.register_obligations(preds.iter().map(|pred: PolyExistentialPredicate<'_>| {
39        let pred = pred.with_self_ty(ecx.tcx.tcx, ty);
40        // Lifetimes can only be 'static because of the bound on T
41        let pred = rustc_middle::ty::fold_regions(ecx.tcx.tcx, pred, |r, _| {
42            if r == ecx.tcx.tcx.lifetimes.re_erased { ecx.tcx.tcx.lifetimes.re_static } else { r }
43        });
44        Obligation::new(ecx.tcx.tcx, ObligationCause::dummy(), param_env, pred)
45    }));
46    let type_impls_trait = ocx.evaluate_obligations_error_on_ambiguity().is_empty();
47    // Since `assumed_wf_tys=[]` the choice of LocalDefId is irrelevant, so using the "default"
48    let regions_are_valid = ocx.resolve_regions(CRATE_DEF_ID, param_env, []).is_empty();
49
50    interp_ok((regions_are_valid && type_impls_trait, preds))
51}
52
53/// Checks whether a type contains generic parameters which must be instantiated.
54///
55/// In case it does, returns a `TooGeneric` const eval error.
56pub(crate) fn ensure_monomorphic_enough<'tcx, T>(ty: T) -> InterpResult<'tcx>
57where
58    T: TypeVisitable<TyCtxt<'tcx>>,
59{
60    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_const_eval/src/interpret/util.rs:60",
                        "rustc_const_eval::interpret::util",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_const_eval/src/interpret/util.rs"),
                        ::tracing_core::__macro_support::Option::Some(60u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_const_eval::interpret::util"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("ensure_monomorphic_enough: ty={0:?}",
                                                    ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("ensure_monomorphic_enough: ty={:?}", ty);
61    if ty.has_param() {
62        do yeet ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::TooGeneric);throw_inval!(TooGeneric);
63    }
64    interp_ok(())
65}
66
67impl<'tcx> InterpretationResult<'tcx> for mir::interpret::ConstAllocation<'tcx> {
68    fn make_result(
69        mplace: MPlaceTy<'tcx>,
70        ecx: &mut InterpCx<'tcx, CompileTimeMachine<'tcx>>,
71    ) -> Self {
72        let alloc_id = mplace.ptr().provenance.unwrap().alloc_id();
73        let alloc = ecx.memory.alloc_map.swap_remove(&alloc_id).unwrap().1;
74        ecx.tcx.mk_const_alloc(alloc)
75    }
76}
77
78pub(crate) fn create_static_alloc<'tcx>(
79    ecx: &mut CompileTimeInterpCx<'tcx>,
80    static_def_id: LocalDefId,
81    layout: TyAndLayout<'tcx>,
82) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
83    // Inherit size and align from the `GlobalAlloc::Static` so we can avoid duplicating
84    // the alignment attribute logic.
85    let (size, align) =
86        GlobalAlloc::Static(static_def_id.into()).size_and_align(*ecx.tcx, ecx.typing_env);
87    {
    match (&size, &layout.size) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(size, layout.size);
88    if !(align >= layout.align.abi) {
    ::core::panicking::panic("assertion failed: align >= layout.align.abi")
};assert!(align >= layout.align.abi);
89
90    let alloc = Allocation::try_new(size, align, AllocInit::Uninit, ())?;
91    let alloc_id = ecx.tcx.reserve_and_set_static_alloc(static_def_id.into());
92    {
    match (&ecx.machine.static_root_ids, &None) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(ecx.machine.static_root_ids, None);
93    ecx.machine.static_root_ids = Some((alloc_id, static_def_id));
94    if !ecx.memory.alloc_map.insert(alloc_id,
                (MemoryKind::Stack, alloc)).is_none() {
    ::core::panicking::panic("assertion failed: ecx.memory.alloc_map.insert(alloc_id, (MemoryKind::Stack, alloc)).is_none()")
};assert!(ecx.memory.alloc_map.insert(alloc_id, (MemoryKind::Stack, alloc)).is_none());
95    interp_ok(ecx.ptr_to_mplace(Pointer::from(alloc_id).into(), layout))
96}
97
98/// A marker trait returned by [crate::interpret::Machine::enter_trace_span], identifying either a
99/// real [tracing::span::EnteredSpan] in case tracing is enabled, or the dummy type `()` when
100/// tracing is disabled. Also see [crate::enter_trace_span!] below.
101pub trait EnteredTraceSpan {
102    /// Allows executing an alternative function when tracing is disabled. Useful for example if you
103    /// want to open a trace span when tracing is enabled, and alternatively just log a line when
104    /// tracing is disabled.
105    fn or_if_tracing_disabled(self, f: impl FnOnce()) -> Self;
106}
107impl EnteredTraceSpan for () {
108    fn or_if_tracing_disabled(self, f: impl FnOnce()) -> Self {
109        f(); // tracing is disabled, execute the function
110        self
111    }
112}
113impl EnteredTraceSpan for tracing::span::EnteredSpan {
114    fn or_if_tracing_disabled(self, _f: impl FnOnce()) -> Self {
115        self // tracing is enabled, don't execute anything
116    }
117}
118
119/// Shorthand for calling [crate::interpret::Machine::enter_trace_span] on a [tracing::info_span!].
120/// This is supposed to be compiled out when [crate::interpret::Machine::enter_trace_span] has the
121/// default implementation (i.e. when it does not actually enter the span but instead returns `()`).
122/// This macro takes a type implementing the [crate::interpret::Machine] trait as its first argument
123/// and otherwise accepts the same syntax as [tracing::span!] (see some tips below).
124/// Note: the result of this macro **must be used** because the span is exited when it's dropped.
125///
126/// ### Syntax accepted by this macro
127///
128/// The full documentation for the [tracing::span!] syntax can be found at [tracing] under "Using the
129/// Macros". A few possibly confusing syntaxes are listed here:
130/// ```rust
131/// # use rustc_const_eval::enter_trace_span;
132/// # type M = rustc_const_eval::const_eval::CompileTimeMachine<'static>;
133/// # let my_display_var = String::new();
134/// # let my_debug_var = String::new();
135/// // logs a span named "hello" with a field named "arg" of value 42 (works only because
136/// // 42 implements the tracing::Value trait, otherwise use one of the options below)
137/// let _trace = enter_trace_span!(M, "hello", arg = 42);
138/// // logs a field called "my_display_var" using the Display implementation
139/// let _trace = enter_trace_span!(M, "hello", %my_display_var);
140/// // logs a field called "my_debug_var" using the Debug implementation
141/// let _trace = enter_trace_span!(M, "hello", ?my_debug_var);
142///  ```
143///
144/// ### `NAME::SUBNAME` syntax
145///
146/// In addition to the syntax accepted by [tracing::span!], this macro optionally allows passing
147/// the span name (i.e. the first macro argument) in the form `NAME::SUBNAME` (without quotes) to
148/// indicate that the span has name "NAME" (usually the name of the component) and has an additional
149/// more specific name "SUBNAME" (usually the function name). The latter is passed to the [tracing]
150/// infrastructure as a span field with the name "NAME". This allows not being distracted by
151/// subnames when looking at the trace in <https://ui.perfetto.dev>, but when deeper introspection
152/// is needed within a component, it's still possible to view the subnames directly in the UI by
153/// selecting a span, clicking on the "NAME" argument on the right, and clicking on "Visualize
154/// argument values".
155/// ```rust
156/// # use rustc_const_eval::enter_trace_span;
157/// # type M = rustc_const_eval::const_eval::CompileTimeMachine<'static>;
158/// // for example, the first will expand to the second
159/// let _trace = enter_trace_span!(M, borrow_tracker::on_stack_pop, /* ... */);
160/// let _trace = enter_trace_span!(M, "borrow_tracker", borrow_tracker = "on_stack_pop", /* ... */);
161/// ```
162///
163/// ### `tracing_separate_thread` parameter
164///
165/// This macro was introduced to obtain better traces of Miri without impacting release performance.
166/// Miri saves traces using the `tracing_chrome` `tracing::Layer` so that they can be visualized
167/// in <https://ui.perfetto.dev>. To instruct `tracing_chrome` to put some spans on a separate trace
168/// thread/line than other spans when viewed in <https://ui.perfetto.dev>, you can pass
169/// `tracing_separate_thread = tracing::field::Empty` to the tracing macros. This is useful to
170/// separate out spans which just indicate the current step or program frame being processed by the
171/// interpreter. You should use a value of [tracing::field::Empty] so that other tracing layers
172/// (e.g. the logger) will ignore the `tracing_separate_thread` field. For example:
173/// ```rust
174/// # use rustc_const_eval::enter_trace_span;
175/// # type M = rustc_const_eval::const_eval::CompileTimeMachine<'static>;
176/// let _trace = enter_trace_span!(M, step::eval_statement, tracing_separate_thread = tracing::field::Empty);
177/// ```
178///
179/// ### Executing something else when tracing is disabled
180///
181/// [crate::interpret::Machine::enter_trace_span] returns [EnteredTraceSpan], on which you can call
182/// [EnteredTraceSpan::or_if_tracing_disabled], to e.g. log a line as an alternative to the tracing
183/// span for when tracing is disabled. For example:
184/// ```rust
185/// # use rustc_const_eval::enter_trace_span;
186/// # use rustc_const_eval::interpret::EnteredTraceSpan;
187/// # type M = rustc_const_eval::const_eval::CompileTimeMachine<'static>;
188/// let _trace = enter_trace_span!(M, step::eval_statement)
189///     .or_if_tracing_disabled(|| tracing::info!("eval_statement"));
190/// ```
191#[macro_export]
192macro_rules! enter_trace_span {
193    ($machine:ty, $name:ident :: $subname:ident $($tt:tt)*) => {
194        $crate::enter_trace_span!($machine, stringify!($name), $name = %stringify!($subname) $($tt)*)
195    };
196
197    ($machine:ty, $($tt:tt)*) => {
198        <$machine as $crate::interpret::Machine>::enter_trace_span(|| tracing::info_span!($($tt)*))
199    };
200}