Skip to main content

hir_ty/mir/
eval.rs

1//! This module provides a MIR interpreter, which is used in const eval.
2
3use std::{borrow::Cow, cell::RefCell, iter, mem, ops::Range};
4
5use base_db::{Crate, target::TargetLoadError};
6use either::Either;
7use hir_def::{
8    AdtId, DefWithBodyId, EnumVariantId, FunctionId, HasModule, ItemContainerId, Lookup, StaticId,
9    VariantId,
10    expr_store::{Body, ExpressionStore, HygieneId},
11    item_tree::FieldsShape,
12    lang_item::LangItems,
13    layout::{TagEncoding, Variants},
14    resolver::{HasResolver, ValueNs},
15    signatures::{EnumSignature, StaticFlags, StaticSignature, StructFlags, StructSignature},
16};
17use hir_expand::{InFile, mod_path::path};
18use la_arena::ArenaMap;
19use macros::GenericTypeVisitable;
20use rustc_abi::{Size, TargetDataLayout};
21use rustc_apfloat::{
22    Float,
23    ieee::{Half as f16, Quad as f128},
24};
25use rustc_ast_ir::Mutability;
26use rustc_hash::{FxHashMap, FxHashSet};
27use rustc_type_ir::{
28    AliasTyKind,
29    inherent::{GenericArgs as _, IntoKind, Region as _, SliceLike, Ty as _},
30};
31use salsa::SalsaValue;
32use span::FileId;
33use stdx::never;
34use syntax::{SyntaxNodePtr, TextRange};
35use triomphe::Arc;
36
37use crate::{
38    CallableDefId, ComplexMemoryMap, InferBodyId, InferenceResult, MemoryMap, ParamEnvAndCrate,
39    consteval::{self, ConstEvalError, try_const_usize},
40    db::{GeneralConstId, HirDatabase, InternedClosureId},
41    infer::PointerCast,
42    layout::{Layout, LayoutError, RustcEnumVariantIdx},
43    method_resolution::{is_dyn_method, lookup_impl_const},
44    next_solver::{
45        AliasTy, Allocation, AllocationData, Const, ConstKind, DbInterner, ErrorGuaranteed,
46        GenericArgs, Region, StoredTy, Ty, TyKind, TypingMode, UnevaluatedConst, ValTree,
47        infer::{DbInternerInferExt, InferCtxt, traits::ObligationCause},
48        obligation_ctxt::ObligationCtxt,
49    },
50    traits::FnTrait,
51    utils::detect_variant_from_bytes,
52};
53
54use super::{
55    AggregateKind, BasicBlockId, BinOp, CastKind, LocalId, MirBody, MirLowerError, MirSpan,
56    Operand, OperandKind, Place, PlaceElem, PlaceTy, ProjectionElem, Rvalue, StatementKind,
57    StoredPlace, TerminatorKind, UnOp, return_slot,
58};
59
60mod shim;
61
62macro_rules! from_bytes {
63    ($ty:tt, $value:expr) => {
64        ($ty::from_le_bytes(match ($value).try_into() {
65            Ok(it) => it,
66            Err(_) => return Err(MirEvalError::InternalError(stringify!(mismatched size in constructing $ty).into())),
67        }))
68    };
69    ($apfloat:tt, $bits:tt, $value:expr) => {
70        // FIXME(#17451): Switch to builtin `f16` and `f128` once they are stable.
71        $apfloat::from_bits($bits::from_le_bytes(match ($value).try_into() {
72            Ok(it) => it,
73            Err(_) => return Err(MirEvalError::InternalError(stringify!(mismatched size in constructing $apfloat).into())),
74        }).into())
75    };
76}
77use from_bytes;
78
79macro_rules! not_supported {
80    ($it: expr) => {
81        return Err($crate::mir::eval::MirEvalError::NotSupported(format!($it)))
82    };
83}
84use not_supported;
85
86#[derive(Debug, Default, Clone, PartialEq, Eq, GenericTypeVisitable)]
87pub struct VTableMap<'db> {
88    ty_to_id: FxHashMap<Ty<'db>, usize>,
89    id_to_ty: Vec<Ty<'db>>,
90}
91
92impl<'db> VTableMap<'db> {
93    const OFFSET: usize = 1000; // We should add some offset to ids to make 0 (null) an invalid id.
94
95    fn id(&mut self, ty: Ty<'db>) -> usize {
96        if let Some(it) = self.ty_to_id.get(&ty) {
97            return *it;
98        }
99        let id = self.id_to_ty.len() + VTableMap::OFFSET;
100        self.id_to_ty.push(ty);
101        self.ty_to_id.insert(ty, id);
102        id
103    }
104
105    pub(crate) fn ty(&self, id: usize) -> Result<'db, Ty<'db>> {
106        id.checked_sub(VTableMap::OFFSET)
107            .and_then(|id| self.id_to_ty.get(id).copied())
108            .ok_or(MirEvalError::InvalidVTableId(id))
109    }
110
111    fn ty_of_bytes(&self, bytes: &[u8]) -> Result<'db, Ty<'db>> {
112        let id = from_bytes!(usize, bytes);
113        self.ty(id)
114    }
115
116    pub fn shrink_to_fit(&mut self) {
117        self.id_to_ty.shrink_to_fit();
118        self.ty_to_id.shrink_to_fit();
119    }
120
121    fn is_empty(&self) -> bool {
122        self.id_to_ty.is_empty() && self.ty_to_id.is_empty()
123    }
124}
125
126#[derive(Debug, Default, Clone, PartialEq, Eq)]
127struct TlsData {
128    keys: Vec<u128>,
129}
130
131impl TlsData {
132    fn create_key(&mut self) -> usize {
133        self.keys.push(0);
134        self.keys.len() - 1
135    }
136
137    fn get_key(&mut self, key: usize) -> Result<'static, u128> {
138        let r = self.keys.get(key).ok_or_else(|| {
139            MirEvalError::UndefinedBehavior(format!("Getting invalid tls key {key}"))
140        })?;
141        Ok(*r)
142    }
143
144    fn set_key(&mut self, key: usize, value: u128) -> Result<'static, ()> {
145        let r = self.keys.get_mut(key).ok_or_else(|| {
146            MirEvalError::UndefinedBehavior(format!("Setting invalid tls key {key}"))
147        })?;
148        *r = value;
149        Ok(())
150    }
151}
152
153struct StackFrame<'a, 'db> {
154    locals: Locals<'a, 'db>,
155    destination: Option<BasicBlockId>,
156    prev_stack_ptr: usize,
157    span: (MirSpan, InferBodyId<'db>),
158}
159
160#[derive(Clone)]
161enum MirOrDynIndex<'db> {
162    Mir(&'db MirBody<'db>),
163    Dyn(usize),
164}
165
166pub struct Evaluator<'a, 'db> {
167    db: &'db dyn HirDatabase,
168    param_env: ParamEnvAndCrate<'db>,
169    target_data_layout: &'db TargetDataLayout,
170    stack: Vec<u8>,
171    heap: Vec<u8>,
172    code_stack: Vec<StackFrame<'a, 'db>>,
173    /// Stores the global location of the statics. We const evaluate every static first time we need it
174    /// and see it's missing, then we add it to this to reuse.
175    static_locations: FxHashMap<StaticId, Address>,
176    /// We don't really have function pointers, i.e. pointers to some assembly instructions that we can run. Instead, we
177    /// store the type as an interned id in place of function and vtable pointers, and we recover back the type at the
178    /// time of use.
179    vtable_map: VTableMap<'db>,
180    thread_local_storage: TlsData,
181    random_state: oorandom::Rand64,
182    stdout: Vec<u8>,
183    stderr: Vec<u8>,
184    layout_cache: RefCell<FxHashMap<Ty<'db>, Arc<Layout>>>,
185    projected_ty_cache: RefCell<FxHashMap<(PlaceTy<'db>, PlaceElem), PlaceTy<'db>>>,
186    not_special_fn_cache: RefCell<FxHashSet<FunctionId>>,
187    mir_or_dyn_index_cache: RefCell<FxHashMap<(FunctionId, GenericArgs<'db>), MirOrDynIndex<'db>>>,
188    /// Constantly dropping and creating `Locals` is very costly. We store
189    /// old locals that we normally want to drop here, to reuse their allocations
190    /// later.
191    unused_locals_store: RefCell<FxHashMap<InferBodyId<'db>, Vec<Locals<'a, 'db>>>>,
192    cached_ptr_size: usize,
193    cached_fn_trait_func: Option<FunctionId>,
194    cached_fn_mut_trait_func: Option<FunctionId>,
195    cached_fn_once_trait_func: Option<FunctionId>,
196    crate_id: Crate,
197    // FIXME: This is a workaround, see the comment on `interpret_mir`
198    assert_placeholder_ty_is_unused: bool,
199    /// A general limit on execution, to prevent non terminating programs from breaking r-a main process
200    execution_limit: usize,
201    /// An additional limit on stack depth, to prevent stack overflow
202    stack_depth_limit: usize,
203    /// Maximum count of bytes that heap and stack can grow
204    memory_limit: usize,
205    infcx: InferCtxt<'db>,
206}
207
208#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
209enum Address {
210    Stack(usize),
211    Heap(usize),
212    Invalid(usize),
213}
214
215use Address::*;
216
217#[derive(Debug, Clone, Copy)]
218struct Interval {
219    addr: Address,
220    size: usize,
221}
222
223#[derive(Debug, Clone)]
224struct IntervalAndTy<'db> {
225    interval: Interval,
226    ty: Ty<'db>,
227}
228
229impl Interval {
230    fn new(addr: Address, size: usize) -> Self {
231        Self { addr, size }
232    }
233
234    fn get<'b, 'a, 'db>(&self, memory: &'b Evaluator<'a, 'db>) -> Result<'db, &'b [u8]> {
235        memory.read_memory(self.addr, self.size)
236    }
237
238    fn write_from_bytes<'a, 'db>(
239        &self,
240        memory: &mut Evaluator<'a, 'db>,
241        bytes: &[u8],
242    ) -> Result<'db, ()> {
243        memory.write_memory(self.addr, bytes)
244    }
245
246    fn write_from_interval<'a, 'db>(
247        &self,
248        memory: &mut Evaluator<'a, 'db>,
249        interval: Interval,
250    ) -> Result<'db, ()> {
251        memory.copy_from_interval(self.addr, interval)
252    }
253
254    fn slice(self, range: Range<usize>) -> Interval {
255        Interval { addr: self.addr.offset(range.start), size: range.len() }
256    }
257}
258
259impl<'db> IntervalAndTy<'db> {
260    fn get<'b, 'a>(&self, memory: &'b Evaluator<'a, 'db>) -> Result<'db, &'b [u8]> {
261        memory.read_memory(self.interval.addr, self.interval.size)
262    }
263
264    fn new<'a>(
265        addr: Address,
266        ty: Ty<'db>,
267        evaluator: &Evaluator<'a, 'db>,
268        locals: &Locals<'a, 'db>,
269    ) -> Result<'db, IntervalAndTy<'db>> {
270        let size = evaluator.size_of_sized(ty, locals, "type of interval")?;
271        Ok(IntervalAndTy { interval: Interval { addr, size }, ty })
272    }
273}
274
275enum IntervalOrOwned {
276    Owned(Vec<u8>),
277    Borrowed(Interval),
278}
279
280impl From<Interval> for IntervalOrOwned {
281    fn from(it: Interval) -> IntervalOrOwned {
282        IntervalOrOwned::Borrowed(it)
283    }
284}
285
286impl IntervalOrOwned {
287    fn get<'b, 'a, 'db>(&'b self, memory: &'b Evaluator<'a, 'db>) -> Result<'db, &'b [u8]> {
288        Ok(match self {
289            IntervalOrOwned::Owned(o) => o,
290            IntervalOrOwned::Borrowed(b) => b.get(memory)?,
291        })
292    }
293}
294
295#[cfg(target_pointer_width = "64")]
296const STACK_OFFSET: usize = 1 << 60;
297#[cfg(target_pointer_width = "64")]
298const HEAP_OFFSET: usize = 1 << 59;
299
300#[cfg(target_pointer_width = "32")]
301const STACK_OFFSET: usize = 1 << 30;
302#[cfg(target_pointer_width = "32")]
303const HEAP_OFFSET: usize = 1 << 29;
304
305impl Address {
306    fn from_bytes<'db>(it: &[u8]) -> Result<'db, Self> {
307        Ok(Address::from_usize(from_bytes!(usize, it)))
308    }
309
310    fn from_usize(it: usize) -> Self {
311        if it > STACK_OFFSET {
312            Stack(it - STACK_OFFSET)
313        } else if it > HEAP_OFFSET {
314            Heap(it - HEAP_OFFSET)
315        } else {
316            Invalid(it)
317        }
318    }
319
320    fn to_bytes(&self) -> [u8; size_of::<usize>()] {
321        usize::to_le_bytes(self.to_usize())
322    }
323
324    fn to_usize(&self) -> usize {
325        match self {
326            Stack(it) => *it + STACK_OFFSET,
327            Heap(it) => *it + HEAP_OFFSET,
328            Invalid(it) => *it,
329        }
330    }
331
332    fn map(&self, f: impl FnOnce(usize) -> usize) -> Address {
333        match self {
334            Stack(it) => Stack(f(*it)),
335            Heap(it) => Heap(f(*it)),
336            Invalid(it) => Invalid(f(*it)),
337        }
338    }
339
340    fn offset(&self, offset: usize) -> Address {
341        self.map(|it| it + offset)
342    }
343}
344
345#[derive(Clone, PartialEq, Eq, SalsaValue)]
346pub enum MirEvalError<'db> {
347    ConstEvalError(String, Box<ConstEvalError<'db>>),
348    LayoutError(LayoutError, StoredTy),
349    TargetDataLayoutNotAvailable(TargetLoadError),
350    /// Means that code had undefined behavior. We don't try to actively detect UB, but if it was detected
351    /// then use this type of error.
352    UndefinedBehavior(String),
353    Panic(String),
354    // FIXME: This should be folded into ConstEvalError?
355    MirLowerError(FunctionId, MirLowerError<'db>),
356    MirLowerErrorForClosure(InternedClosureId<'db>, MirLowerError<'db>),
357    TypeIsUnsized(StoredTy, &'static str),
358    NotSupported(String),
359    InvalidConst,
360    InFunction(
361        Box<MirEvalError<'db>>,
362        Vec<(Either<FunctionId, InternedClosureId<'db>>, MirSpan, InferBodyId<'db>)>,
363    ),
364    ExecutionLimitExceeded,
365    StackOverflow,
366    /// FIXME: Fold this into InternalError
367    InvalidVTableId(usize),
368    /// ?
369    CoerceUnsizedError(StoredTy),
370    /// These should not occur, usually indicates a bug in mir lowering.
371    InternalError(Box<str>),
372}
373
374impl std::fmt::Debug for MirEvalError<'_> {
375    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
376        match self {
377            Self::ConstEvalError(arg0, arg1) => {
378                f.debug_tuple("ConstEvalError").field(arg0).field(arg1).finish()
379            }
380            Self::LayoutError(arg0, arg1) => {
381                f.debug_tuple("LayoutError").field(arg0).field(arg1).finish()
382            }
383            Self::UndefinedBehavior(arg0) => {
384                f.debug_tuple("UndefinedBehavior").field(arg0).finish()
385            }
386            Self::Panic(msg) => write!(f, "Panic with message:\n{msg:?}"),
387            Self::TargetDataLayoutNotAvailable(arg0) => {
388                f.debug_tuple("TargetDataLayoutNotAvailable").field(arg0).finish()
389            }
390            Self::TypeIsUnsized(ty, it) => write!(f, "{ty:?} is unsized. {it} should be sized."),
391            Self::ExecutionLimitExceeded => write!(f, "execution limit exceeded"),
392            Self::StackOverflow => write!(f, "stack overflow"),
393            Self::MirLowerError(arg0, arg1) => {
394                f.debug_tuple("MirLowerError").field(arg0).field(arg1).finish()
395            }
396            Self::MirLowerErrorForClosure(arg0, arg1) => {
397                f.debug_tuple("MirLowerError").field(arg0).field(arg1).finish()
398            }
399            Self::CoerceUnsizedError(arg0) => {
400                f.debug_tuple("CoerceUnsizedError").field(arg0).finish()
401            }
402            Self::InternalError(arg0) => f.debug_tuple("InternalError").field(arg0).finish(),
403            Self::InvalidVTableId(arg0) => f.debug_tuple("InvalidVTableId").field(arg0).finish(),
404            Self::NotSupported(arg0) => f.debug_tuple("NotSupported").field(arg0).finish(),
405            Self::InvalidConst => f.write_str("InvalidConst"),
406            Self::InFunction(e, stack) => {
407                f.debug_struct("WithStack").field("error", e).field("stack", &stack).finish()
408            }
409        }
410    }
411}
412
413type Result<'db, T> = std::result::Result<T, MirEvalError<'db>>;
414
415#[derive(Debug, Default)]
416struct DropFlags<'db> {
417    need_drop: FxHashSet<Place<'db>>,
418}
419
420impl<'db> DropFlags<'db> {
421    fn add_place(&mut self, p: Place<'db>) {
422        if p.iterate_over_parents().any(|it| self.need_drop.contains(&it)) {
423            return;
424        }
425        self.need_drop.retain(|it| !p.is_parent(*it));
426        self.need_drop.insert(p);
427    }
428
429    fn remove_place(&mut self, p: Place<'db>) -> bool {
430        // FIXME: replace parents with parts
431        if let Some(parent) = p.iterate_over_parents().find(|it| self.need_drop.contains(it)) {
432            self.need_drop.remove(&parent);
433            return true;
434        }
435        self.need_drop.remove(&p)
436    }
437
438    fn clear(&mut self) {
439        self.need_drop.clear();
440    }
441}
442
443#[derive(Debug)]
444struct Locals<'a, 'db> {
445    ptr: ArenaMap<LocalId, Interval>,
446    body: &'db MirBody<'db>,
447    drop_flags: DropFlags<'a>,
448}
449
450pub struct MirOutput {
451    stdout: Vec<u8>,
452    stderr: Vec<u8>,
453}
454
455impl MirOutput {
456    pub fn stdout(&self) -> Cow<'_, str> {
457        String::from_utf8_lossy(&self.stdout)
458    }
459    pub fn stderr(&self) -> Cow<'_, str> {
460        String::from_utf8_lossy(&self.stderr)
461    }
462}
463
464pub fn interpret_mir<'db>(
465    db: &'db dyn HirDatabase,
466    body: &'db MirBody<'db>,
467    // FIXME: This is workaround. Ideally, const generics should have a separate body (issue #7434), but now
468    // they share their body with their parent, so in MIR lowering we have locals of the parent body, which
469    // might have placeholders. With this argument, we (wrongly) assume that every placeholder type has
470    // a zero size, hoping that they are all outside of our current body. Even without a fix for #7434, we can
471    // (and probably should) do better here, for example by excluding bindings outside of the target expression.
472    assert_placeholder_ty_is_unused: bool,
473    trait_env: Option<ParamEnvAndCrate<'db>>,
474) -> Result<'db, (Result<'db, Allocation<'db>>, MirOutput)> {
475    let ty = body.locals[return_slot()].ty.as_ref();
476    let mut evaluator = Evaluator::new(db, body.owner, assert_placeholder_ty_is_unused, trait_env)?;
477    let it: Result<'db, Allocation<'db>> = (|| {
478        if evaluator.ptr_size() != size_of::<usize>() {
479            not_supported!("targets with different pointer size from host");
480        }
481        let interval = evaluator.interpret_mir(body, None.into_iter())?;
482        let bytes = interval.get(&evaluator)?;
483        let mut memory_map = evaluator.create_memory_map(
484            bytes,
485            ty,
486            &Locals { ptr: ArenaMap::new(), body, drop_flags: DropFlags::default() },
487        )?;
488        let bytes = Box::from(bytes);
489        let memory_map = if memory_map.memory.is_empty() && evaluator.vtable_map.is_empty() {
490            MemoryMap::Empty
491        } else {
492            memory_map.vtable = mem::take(&mut evaluator.vtable_map);
493            memory_map.vtable.shrink_to_fit();
494            MemoryMap::Complex(Box::new(memory_map))
495        };
496        Ok(Allocation::new(AllocationData { ty, memory: bytes, memory_map }))
497    })();
498    Ok((it, MirOutput { stdout: evaluator.stdout, stderr: evaluator.stderr }))
499}
500
501#[cfg(test)]
502const EXECUTION_LIMIT: usize = 100_000;
503#[cfg(not(test))]
504const EXECUTION_LIMIT: usize = 10_000_000;
505
506impl<'a, 'db> Evaluator<'a, 'db> {
507    pub fn new(
508        db: &'db dyn HirDatabase,
509        owner: InferBodyId<'db>,
510        assert_placeholder_ty_is_unused: bool,
511        trait_env: Option<ParamEnvAndCrate<'db>>,
512    ) -> Result<'db, Evaluator<'a, 'db>> {
513        let module = owner.module(db);
514        let crate_id = module.krate(db);
515        let target_data_layout = match db.target_data_layout(crate_id) {
516            Ok(target_data_layout) => target_data_layout,
517            Err(e) => return Err(MirEvalError::TargetDataLayoutNotAvailable(e)),
518        };
519        let cached_ptr_size = target_data_layout.pointer_size().bytes_usize();
520        let interner = DbInterner::new_with(db, crate_id);
521        let infcx = interner.infer_ctxt().build(TypingMode::PostAnalysis);
522        let lang_items = interner.lang_items();
523        Ok(Evaluator {
524            target_data_layout,
525            stack: vec![0],
526            heap: vec![0],
527            code_stack: vec![],
528            vtable_map: VTableMap::default(),
529            thread_local_storage: TlsData::default(),
530            static_locations: Default::default(),
531            db,
532            random_state: oorandom::Rand64::new(0),
533            param_env: trait_env.unwrap_or_else(|| ParamEnvAndCrate {
534                param_env: db.trait_environment(owner.generic_def(db)),
535                krate: crate_id,
536            }),
537            crate_id,
538            stdout: vec![],
539            stderr: vec![],
540            assert_placeholder_ty_is_unused,
541            stack_depth_limit: 100,
542            execution_limit: EXECUTION_LIMIT,
543            memory_limit: 1_000_000_000, // 2GB, 1GB for stack and 1GB for heap
544            layout_cache: RefCell::new(Default::default()),
545            projected_ty_cache: RefCell::new(Default::default()),
546            not_special_fn_cache: RefCell::new(Default::default()),
547            mir_or_dyn_index_cache: RefCell::new(Default::default()),
548            unused_locals_store: RefCell::new(Default::default()),
549            cached_ptr_size,
550            cached_fn_trait_func: lang_items.Fn_call,
551            cached_fn_mut_trait_func: lang_items.FnMut_call_mut,
552            cached_fn_once_trait_func: lang_items.FnOnce_call_once,
553            infcx,
554        })
555    }
556
557    #[inline]
558    fn interner(&self) -> DbInterner<'db> {
559        self.infcx.interner
560    }
561
562    #[inline]
563    fn lang_items(&self) -> &'db LangItems {
564        self.infcx.interner.lang_items()
565    }
566
567    fn place_addr(&self, p: &StoredPlace, locals: &Locals<'a, 'db>) -> Result<'db, Address> {
568        Ok(self.place_addr_and_ty_and_metadata(p, locals)?.0)
569    }
570
571    fn place_interval(&self, p: &StoredPlace, locals: &Locals<'a, 'db>) -> Result<'db, Interval> {
572        let place_addr_and_ty = self.place_addr_and_ty_and_metadata(p, locals)?;
573        Ok(Interval {
574            addr: place_addr_and_ty.0,
575            size: self.size_of_sized(
576                place_addr_and_ty.1,
577                locals,
578                "Type of place that we need its interval",
579            )?,
580        })
581    }
582
583    fn ptr_size(&self) -> usize {
584        self.cached_ptr_size
585    }
586
587    fn caller_location_fields(&self, owner: InferBodyId<'db>, span: MirSpan) -> (String, u32, u32) {
588        let Some((file_id, text_range)) = self.resolve_mir_span(owner, span) else {
589            return (String::new(), 0, 0);
590        };
591        let source_root = self.db.file_source_root(file_id).source_root_id(self.db);
592        let source_root = self.db.source_root(source_root).source_root(self.db);
593        let path = source_root.path_for_file(&file_id).map(|path| path.to_string());
594        let (line, col) = self.db.line_column(file_id, text_range.start()).unwrap_or((0, 0));
595        (path.unwrap_or_default(), line + 1, col + 1)
596    }
597
598    fn resolve_mir_span(
599        &self,
600        owner: InferBodyId<'db>,
601        span: MirSpan,
602    ) -> Option<(FileId, TextRange)> {
603        let (source_map, self_param_syntax) = match owner {
604            InferBodyId::DefWithBodyId(def) => {
605                let body = &Body::with_source_map(self.db, def).1;
606                (&**body, body.self_param_syntax())
607            }
608            InferBodyId::AnonConstId(def) => {
609                (ExpressionStore::with_source_map(self.db, def.loc(self.db).owner).1, None)
610            }
611        };
612        let span: InFile<SyntaxNodePtr> = match span {
613            MirSpan::ExprId(e) => source_map.expr_syntax(e).ok()?.map(|it| it.into()),
614            MirSpan::PatId(p) => source_map.pat_syntax(p).ok()?.map(|it| it.syntax_node_ptr()),
615            MirSpan::BindingId(b) => source_map
616                .patterns_for_binding(b)
617                .iter()
618                .find_map(|p| source_map.pat_syntax(*p).ok())?
619                .map(|it| it.syntax_node_ptr()),
620            MirSpan::SelfParam => self_param_syntax?.map(|it| it.syntax_node_ptr()),
621            MirSpan::Unknown => return None,
622        };
623        let file_id = span.file_id.original_file(self.db);
624        Some((file_id.file_id(self.db), span.value.text_range()))
625    }
626
627    fn projected_ty(&self, ty: PlaceTy<'db>, proj: PlaceElem) -> PlaceTy<'db> {
628        let pair = (ty, proj);
629        if let Some(r) = self.projected_ty_cache.borrow().get(&pair) {
630            return *r;
631        }
632        let (ty, proj) = pair;
633        let r = ty.projection_ty(&self.infcx, &proj, self.param_env.param_env);
634        self.projected_ty_cache.borrow_mut().insert((ty, proj), r);
635        r
636    }
637
638    fn place_addr_and_ty_and_metadata<'b>(
639        &'b self,
640        p: &StoredPlace,
641        locals: &'b Locals<'a, 'db>,
642    ) -> Result<'db, (Address, Ty<'db>, Option<IntervalOrOwned>)> {
643        let mut addr = locals.ptr[p.local].addr;
644        let mut ty = PlaceTy::from_ty(locals.body.locals[p.local].ty.as_ref());
645        let mut metadata: Option<IntervalOrOwned> = None; // locals are always sized
646        for proj in p.projection.as_slice() {
647            let prev_ty = ty;
648            ty = self.projected_ty(ty, *proj);
649            match proj {
650                ProjectionElem::Deref => {
651                    metadata = if self.size_align_of(ty.ty, locals)?.is_none() {
652                        Some(
653                            Interval { addr: addr.offset(self.ptr_size()), size: self.ptr_size() }
654                                .into(),
655                        )
656                    } else {
657                        None
658                    };
659                    let it = from_bytes!(usize, self.read_memory(addr, self.ptr_size())?);
660                    addr = Address::from_usize(it);
661                }
662                ProjectionElem::Index(op) => {
663                    let offset = from_bytes!(
664                        usize,
665                        self.read_memory(locals.ptr[*op].addr, self.ptr_size())?
666                    );
667                    metadata = None; // Result of index is always sized
668                    let ty_size = self.size_of_sized(ty.ty, locals, "array inner type")?;
669                    addr = addr.offset(ty_size * offset);
670                }
671                &ProjectionElem::ConstantIndex { from_end, offset } => {
672                    let offset = if from_end {
673                        let len = match prev_ty.ty.kind() {
674                            TyKind::Array(_, c) => match try_const_usize(self.db, c) {
675                                Some(it) => it as u64,
676                                None => {
677                                    not_supported!("indexing array with unknown const from end")
678                                }
679                            },
680                            TyKind::Slice(_) => match metadata {
681                                Some(it) => from_bytes!(u64, it.get(self)?),
682                                None => not_supported!("slice place without metadata"),
683                            },
684                            _ => not_supported!("bad type for const index"),
685                        };
686                        (len - offset - 1) as usize
687                    } else {
688                        offset as usize
689                    };
690                    metadata = None; // Result of index is always sized
691                    let ty_size = self.size_of_sized(ty.ty, locals, "array inner type")?;
692                    addr = addr.offset(ty_size * offset);
693                }
694                &ProjectionElem::Subslice { from, to } => {
695                    let inner_ty = match ty.ty.kind() {
696                        TyKind::Array(inner, _) | TyKind::Slice(inner) => inner,
697                        _ => Ty::new_error(self.interner(), ErrorGuaranteed),
698                    };
699                    metadata = match metadata {
700                        Some(it) => {
701                            let prev_len = from_bytes!(u64, it.get(self)?);
702                            Some(IntervalOrOwned::Owned(
703                                (prev_len - from - to).to_le_bytes().to_vec(),
704                            ))
705                        }
706                        None => None,
707                    };
708                    let ty_size = self.size_of_sized(inner_ty, locals, "array inner type")?;
709                    addr = addr.offset(ty_size * (from as usize));
710                }
711                ProjectionElem::Field(f) => {
712                    let layout = self.layout(prev_ty.ty)?;
713                    let variant_layout = match &layout.variants {
714                        Variants::Single { .. } | Variants::Empty => &layout,
715                        Variants::Multiple { variants, .. } => {
716                            &variants[match prev_ty.variant_id {
717                                Some(hir_def::VariantId::EnumVariantId(it)) => {
718                                    RustcEnumVariantIdx(it.index(self.db))
719                                }
720                                _ => {
721                                    return Err(MirEvalError::InternalError(
722                                        "mismatched layout".into(),
723                                    ));
724                                }
725                            }]
726                        }
727                    };
728                    let offset = variant_layout.fields.offset(f.0 as usize).bytes_usize();
729                    addr = addr.offset(offset);
730                    // Unsized field metadata is equal to the metadata of the struct
731                    if self.size_align_of(ty.ty, locals)?.is_some() {
732                        metadata = None;
733                    }
734                }
735                ProjectionElem::Downcast(_) => {
736                    // no runtime effect
737                }
738            }
739        }
740        Ok((addr, ty.ty, metadata))
741    }
742
743    fn layout(&self, ty: Ty<'db>) -> Result<'db, Arc<Layout>> {
744        if let Some(x) = self.layout_cache.borrow().get(&ty) {
745            return Ok(x.clone());
746        }
747        let r = self
748            .db
749            .layout_of_ty(ty.store(), self.param_env.store())
750            .map_err(|e| MirEvalError::LayoutError(e, ty.store()))?;
751        self.layout_cache.borrow_mut().insert(ty, r.clone());
752        Ok(r)
753    }
754
755    fn layout_adt(&self, adt: AdtId, subst: GenericArgs<'db>) -> Result<'db, Arc<Layout>> {
756        self.layout(Ty::new_adt(self.interner(), adt, subst))
757    }
758
759    fn place_ty<'b>(
760        &'b self,
761        p: &StoredPlace,
762        locals: &'b Locals<'a, 'db>,
763    ) -> Result<'db, Ty<'db>> {
764        Ok(self.place_addr_and_ty_and_metadata(p, locals)?.1)
765    }
766
767    fn operand_ty(&self, o: &Operand, locals: &Locals<'a, 'db>) -> Result<'db, Ty<'db>> {
768        Ok(match &o.kind {
769            OperandKind::Copy(p) | OperandKind::Move(p) => self.place_ty(p, locals)?,
770            OperandKind::Constant { konst: _, ty } => ty.as_ref(),
771            OperandKind::Allocation { allocation } => allocation.as_ref().ty,
772            &OperandKind::Static(s) => {
773                let ty = InferenceResult::of(self.db, DefWithBodyId::from(s))
774                    .expr_ty(Body::of(self.db, s.into()).root_expr());
775                Ty::new_ref(
776                    self.interner(),
777                    Region::new_static(self.interner()),
778                    ty,
779                    Mutability::Not,
780                )
781            }
782        })
783    }
784
785    fn operand_ty_and_eval(
786        &mut self,
787        o: &Operand,
788        locals: &mut Locals<'a, 'db>,
789    ) -> Result<'db, IntervalAndTy<'db>> {
790        Ok(IntervalAndTy {
791            interval: self.eval_operand(o, locals)?,
792            ty: self.operand_ty(o, locals)?,
793        })
794    }
795
796    fn interpret_mir(
797        &mut self,
798        body: &'db MirBody<'db>,
799        args: impl Iterator<Item = IntervalOrOwned>,
800    ) -> Result<'db, Interval> {
801        if let Some(it) = self.stack_depth_limit.checked_sub(1) {
802            self.stack_depth_limit = it;
803        } else {
804            return Err(MirEvalError::StackOverflow);
805        }
806        let mut current_block_idx = body.start_block;
807        let (mut locals, prev_stack_ptr) = self.create_locals_for_body(body, None)?;
808        self.fill_locals_for_body(body, &mut locals, args)?;
809        let prev_code_stack = mem::take(&mut self.code_stack);
810        let span = (MirSpan::Unknown, body.owner);
811        self.code_stack.push(StackFrame { locals, destination: None, prev_stack_ptr, span });
812        'stack: loop {
813            let Some(mut my_stack_frame) = self.code_stack.pop() else {
814                not_supported!("missing stack frame");
815            };
816            let e = (|| {
817                let locals = &mut my_stack_frame.locals;
818                let body = locals.body.clone();
819                loop {
820                    let current_block = &body.basic_blocks[current_block_idx];
821                    if let Some(it) = self.execution_limit.checked_sub(1) {
822                        self.execution_limit = it;
823                    } else {
824                        return Err(MirEvalError::ExecutionLimitExceeded);
825                    }
826                    for statement in &current_block.statements {
827                        match &statement.kind {
828                            StatementKind::Assign(l, r) => {
829                                let addr = self.place_addr(l, locals)?;
830                                let result = self.eval_rvalue(r, locals)?;
831                                self.copy_from_interval_or_owned(addr, result)?;
832                                locals.drop_flags.add_place(l.as_ref());
833                            }
834                            StatementKind::Deinit(_) => not_supported!("de-init statement"),
835                            StatementKind::StorageLive(_)
836                            | StatementKind::FakeRead(_)
837                            | StatementKind::StorageDead(_)
838                            | StatementKind::Nop => (),
839                        }
840                    }
841                    let Some(terminator) = current_block.terminator.as_ref() else {
842                        not_supported!("block without terminator");
843                    };
844                    match &terminator.kind {
845                        TerminatorKind::Goto { target } => {
846                            current_block_idx = *target;
847                        }
848                        TerminatorKind::Call {
849                            func,
850                            args,
851                            destination,
852                            target,
853                            cleanup: _,
854                            from_hir_call: _,
855                        } => {
856                            let destination_interval = self.place_interval(destination, locals)?;
857                            let fn_ty = self.operand_ty(func, locals)?;
858                            let args = args
859                                .iter()
860                                .map(|it| self.operand_ty_and_eval(it, locals))
861                                .collect::<Result<'db, Vec<_>>>()?;
862                            let stack_frame = match fn_ty.kind() {
863                                TyKind::FnPtr(..) => {
864                                    let bytes = self.eval_operand(func, locals)?;
865                                    self.exec_fn_pointer(
866                                        bytes,
867                                        destination_interval,
868                                        &args,
869                                        locals,
870                                        *target,
871                                        terminator.span,
872                                    )?
873                                }
874                                TyKind::FnDef(def, generic_args) => self.exec_fn_def(
875                                    def.0,
876                                    generic_args,
877                                    destination_interval,
878                                    &args,
879                                    locals,
880                                    *target,
881                                    terminator.span,
882                                )?,
883                                it => not_supported!("unknown function type {it:?}"),
884                            };
885                            locals.drop_flags.add_place(destination.as_ref());
886                            if let Some(stack_frame) = stack_frame {
887                                self.code_stack.push(my_stack_frame);
888                                current_block_idx = stack_frame.locals.body.start_block;
889                                self.code_stack.push(stack_frame);
890                                return Ok(None);
891                            } else {
892                                current_block_idx =
893                                    target.ok_or(MirEvalError::UndefinedBehavior(
894                                        "Diverging function returned".to_owned(),
895                                    ))?;
896                            }
897                        }
898                        TerminatorKind::SwitchInt { discr, targets } => {
899                            let val = u128::from_le_bytes(pad16(
900                                self.eval_operand(discr, locals)?.get(self)?,
901                                IsSigned::No,
902                            ));
903                            current_block_idx = targets.target_for_value(val);
904                        }
905                        TerminatorKind::Return => {
906                            break;
907                        }
908                        TerminatorKind::Unreachable => {
909                            return Err(MirEvalError::UndefinedBehavior(
910                                "unreachable executed".to_owned(),
911                            ));
912                        }
913                        TerminatorKind::Drop { place, target, unwind: _ } => {
914                            self.drop_place(place, locals, terminator.span)?;
915                            current_block_idx = *target;
916                        }
917                        _ => not_supported!("unknown terminator"),
918                    }
919                }
920                Ok(Some(my_stack_frame))
921            })();
922            let my_stack_frame = match e {
923                Ok(None) => continue 'stack,
924                Ok(Some(x)) => x,
925                Err(e) => {
926                    let my_code_stack = mem::replace(&mut self.code_stack, prev_code_stack);
927                    let mut error_stack = vec![];
928                    for frame in my_code_stack.into_iter().rev() {
929                        if let Some(f) = frame.locals.body.owner.as_function() {
930                            error_stack.push((Either::Left(f), frame.span.0, frame.span.1));
931                        }
932                    }
933                    return Err(MirEvalError::InFunction(Box::new(e), error_stack));
934                }
935            };
936            let return_interval = my_stack_frame.locals.ptr[return_slot()];
937            self.unused_locals_store
938                .borrow_mut()
939                .entry(my_stack_frame.locals.body.owner)
940                .or_default()
941                .push(my_stack_frame.locals);
942            match my_stack_frame.destination {
943                None => {
944                    self.code_stack = prev_code_stack;
945                    self.stack_depth_limit += 1;
946                    return Ok(return_interval);
947                }
948                Some(bb) => {
949                    // We don't support const promotion, so we can't truncate the stack yet.
950                    let _ = my_stack_frame.prev_stack_ptr;
951                    // self.stack.truncate(my_stack_frame.prev_stack_ptr);
952                    current_block_idx = bb;
953                }
954            }
955        }
956    }
957
958    fn fill_locals_for_body(
959        &mut self,
960        body: &'db MirBody<'db>,
961        locals: &mut Locals<'a, 'db>,
962        args: impl Iterator<Item = IntervalOrOwned>,
963    ) -> Result<'db, ()> {
964        let mut remain_args = body.param_locals.len();
965        for ((l, interval), value) in locals.ptr.iter().skip(1).zip(args) {
966            locals.drop_flags.add_place(l.into());
967            match value {
968                IntervalOrOwned::Owned(value) => interval.write_from_bytes(self, &value)?,
969                IntervalOrOwned::Borrowed(value) => interval.write_from_interval(self, value)?,
970            }
971            if remain_args == 0 {
972                return Err(MirEvalError::InternalError("too many arguments".into()));
973            }
974            remain_args -= 1;
975        }
976        if remain_args > 0 {
977            return Err(MirEvalError::InternalError("too few arguments".into()));
978        }
979        Ok(())
980    }
981
982    fn create_locals_for_body(
983        &mut self,
984        body: &'db MirBody<'db>,
985        destination: Option<Interval>,
986    ) -> Result<'db, (Locals<'a, 'db>, usize)> {
987        let mut locals =
988            match self.unused_locals_store.borrow_mut().entry(body.owner).or_default().pop() {
989                None => Locals { ptr: ArenaMap::new(), body, drop_flags: DropFlags::default() },
990                Some(mut l) => {
991                    l.drop_flags.clear();
992                    l.body = body;
993                    l
994                }
995            };
996        let stack_size = {
997            let mut stack_ptr = self.stack.len();
998            for (id, it) in body.locals.iter() {
999                if id == return_slot()
1000                    && let Some(destination) = destination
1001                {
1002                    locals.ptr.insert(id, destination);
1003                    continue;
1004                }
1005                let (size, align) = self.size_align_of_sized(
1006                    it.ty.as_ref(),
1007                    &locals,
1008                    "no unsized local in extending stack",
1009                )?;
1010                while !stack_ptr.is_multiple_of(align) {
1011                    stack_ptr += 1;
1012                }
1013                let my_ptr = stack_ptr;
1014                stack_ptr += size;
1015                locals.ptr.insert(id, Interval { addr: Stack(my_ptr), size });
1016            }
1017            stack_ptr - self.stack.len()
1018        };
1019        let prev_stack_pointer = self.stack.len();
1020        if stack_size > self.memory_limit {
1021            return Err(MirEvalError::Panic(format!(
1022                "Stack overflow. Tried to grow stack to {stack_size} bytes"
1023            )));
1024        }
1025        self.stack.extend(std::iter::repeat_n(0, stack_size));
1026        Ok((locals, prev_stack_pointer))
1027    }
1028
1029    fn eval_rvalue(
1030        &mut self,
1031        r: &Rvalue,
1032        locals: &mut Locals<'a, 'db>,
1033    ) -> Result<'db, IntervalOrOwned> {
1034        use IntervalOrOwned::*;
1035        Ok(match r {
1036            Rvalue::Use(it) => Borrowed(self.eval_operand(it, locals)?),
1037            Rvalue::Ref(_, p) => {
1038                let (addr, _, metadata) = self.place_addr_and_ty_and_metadata(p, locals)?;
1039                let mut r = addr.to_bytes().to_vec();
1040                if let Some(metadata) = metadata {
1041                    r.extend(metadata.get(self)?);
1042                }
1043                Owned(r)
1044            }
1045            Rvalue::Len(p) => {
1046                let (_, _, metadata) = self.place_addr_and_ty_and_metadata(p, locals)?;
1047                match metadata {
1048                    Some(m) => m,
1049                    None => {
1050                        return Err(MirEvalError::InternalError(
1051                            "type without metadata is used for Rvalue::Len".into(),
1052                        ));
1053                    }
1054                }
1055            }
1056            Rvalue::UnaryOp(op, val) => {
1057                let mut c = self.eval_operand(val, locals)?.get(self)?;
1058                let mut ty = self.operand_ty(val, locals)?;
1059                while let TyKind::Ref(_, z, _) = ty.kind() {
1060                    ty = z;
1061                    let size = self.size_of_sized(ty, locals, "operand of unary op")?;
1062                    c = self.read_memory(Address::from_bytes(c)?, size)?;
1063                }
1064                if let TyKind::Float(f) = ty.kind() {
1065                    match f {
1066                        rustc_type_ir::FloatTy::F16 => {
1067                            let c = -from_bytes!(f16, u16, c);
1068                            Owned(u16::try_from(c.to_bits()).unwrap().to_le_bytes().into())
1069                        }
1070                        rustc_type_ir::FloatTy::F32 => {
1071                            let c = -from_bytes!(f32, c);
1072                            Owned(c.to_le_bytes().into())
1073                        }
1074                        rustc_type_ir::FloatTy::F64 => {
1075                            let c = -from_bytes!(f64, c);
1076                            Owned(c.to_le_bytes().into())
1077                        }
1078                        rustc_type_ir::FloatTy::F128 => {
1079                            let c = -from_bytes!(f128, u128, c);
1080                            Owned(c.to_bits().to_le_bytes().into())
1081                        }
1082                    }
1083                } else {
1084                    let mut c = c.to_vec();
1085                    if matches!(ty.kind(), TyKind::Bool) {
1086                        c[0] = 1 - c[0];
1087                    } else {
1088                        match op {
1089                            UnOp::Not => c.iter_mut().for_each(|it| *it = !*it),
1090                            UnOp::Neg => {
1091                                c.iter_mut().for_each(|it| *it = !*it);
1092                                for k in c.iter_mut() {
1093                                    let o;
1094                                    (*k, o) = k.overflowing_add(1);
1095                                    if !o {
1096                                        break;
1097                                    }
1098                                }
1099                            }
1100                        }
1101                    }
1102                    Owned(c)
1103                }
1104            }
1105            Rvalue::CheckedBinaryOp(op, lhs, rhs) => 'binary_op: {
1106                let lc = self.eval_operand(lhs, locals)?;
1107                let rc = self.eval_operand(rhs, locals)?;
1108                let mut lc = lc.get(self)?;
1109                let mut rc = rc.get(self)?;
1110                let mut ty = self.operand_ty(lhs, locals)?;
1111                while let TyKind::Ref(_, z, _) = ty.kind() {
1112                    ty = z;
1113                    let size = if ty.is_str() {
1114                        if *op != BinOp::Eq {
1115                            return Err(MirEvalError::NotSupported(
1116                                "Only eq is builtin for `str`".to_owned(),
1117                            ));
1118                        }
1119                        let ls = from_bytes!(usize, &lc[self.ptr_size()..self.ptr_size() * 2]);
1120                        let rs = from_bytes!(usize, &rc[self.ptr_size()..self.ptr_size() * 2]);
1121                        if ls != rs {
1122                            break 'binary_op Owned(vec![0]);
1123                        }
1124                        lc = &lc[..self.ptr_size()];
1125                        rc = &rc[..self.ptr_size()];
1126                        lc = self.read_memory(Address::from_bytes(lc)?, ls)?;
1127                        rc = self.read_memory(Address::from_bytes(rc)?, ls)?;
1128                        break 'binary_op Owned(vec![u8::from(lc == rc)]);
1129                    } else {
1130                        self.size_of_sized(ty, locals, "operand of binary op")?
1131                    };
1132                    lc = self.read_memory(Address::from_bytes(lc)?, size)?;
1133                    rc = self.read_memory(Address::from_bytes(rc)?, size)?;
1134                }
1135                if let TyKind::Float(f) = ty.kind() {
1136                    match f {
1137                        rustc_type_ir::FloatTy::F16 => {
1138                            let l = from_bytes!(f16, u16, lc);
1139                            let r = from_bytes!(f16, u16, rc);
1140                            match op {
1141                                BinOp::Ge
1142                                | BinOp::Gt
1143                                | BinOp::Le
1144                                | BinOp::Lt
1145                                | BinOp::Eq
1146                                | BinOp::Ne => {
1147                                    let r = op.run_compare(l, r) as u8;
1148                                    Owned(vec![r])
1149                                }
1150                                BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div => {
1151                                    let r = match op {
1152                                        BinOp::Add => l + r,
1153                                        BinOp::Sub => l - r,
1154                                        BinOp::Mul => l * r,
1155                                        BinOp::Div => l / r,
1156                                        _ => unreachable!(),
1157                                    };
1158                                    Owned(
1159                                        u16::try_from(r.value.to_bits())
1160                                            .unwrap()
1161                                            .to_le_bytes()
1162                                            .into(),
1163                                    )
1164                                }
1165                                it => not_supported!(
1166                                    "invalid binop {it:?} on floating point operators"
1167                                ),
1168                            }
1169                        }
1170                        rustc_type_ir::FloatTy::F32 => {
1171                            let l = from_bytes!(f32, lc);
1172                            let r = from_bytes!(f32, rc);
1173                            match op {
1174                                BinOp::Ge
1175                                | BinOp::Gt
1176                                | BinOp::Le
1177                                | BinOp::Lt
1178                                | BinOp::Eq
1179                                | BinOp::Ne => {
1180                                    let r = op.run_compare(l, r) as u8;
1181                                    Owned(vec![r])
1182                                }
1183                                BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div => {
1184                                    let r = match op {
1185                                        BinOp::Add => l + r,
1186                                        BinOp::Sub => l - r,
1187                                        BinOp::Mul => l * r,
1188                                        BinOp::Div => l / r,
1189                                        _ => unreachable!(),
1190                                    };
1191                                    Owned(r.to_le_bytes().into())
1192                                }
1193                                it => not_supported!(
1194                                    "invalid binop {it:?} on floating point operators"
1195                                ),
1196                            }
1197                        }
1198                        rustc_type_ir::FloatTy::F64 => {
1199                            let l = from_bytes!(f64, lc);
1200                            let r = from_bytes!(f64, rc);
1201                            match op {
1202                                BinOp::Ge
1203                                | BinOp::Gt
1204                                | BinOp::Le
1205                                | BinOp::Lt
1206                                | BinOp::Eq
1207                                | BinOp::Ne => {
1208                                    let r = op.run_compare(l, r) as u8;
1209                                    Owned(vec![r])
1210                                }
1211                                BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div => {
1212                                    let r = match op {
1213                                        BinOp::Add => l + r,
1214                                        BinOp::Sub => l - r,
1215                                        BinOp::Mul => l * r,
1216                                        BinOp::Div => l / r,
1217                                        _ => unreachable!(),
1218                                    };
1219                                    Owned(r.to_le_bytes().into())
1220                                }
1221                                it => not_supported!(
1222                                    "invalid binop {it:?} on floating point operators"
1223                                ),
1224                            }
1225                        }
1226                        rustc_type_ir::FloatTy::F128 => {
1227                            let l = from_bytes!(f128, u128, lc);
1228                            let r = from_bytes!(f128, u128, rc);
1229                            match op {
1230                                BinOp::Ge
1231                                | BinOp::Gt
1232                                | BinOp::Le
1233                                | BinOp::Lt
1234                                | BinOp::Eq
1235                                | BinOp::Ne => {
1236                                    let r = op.run_compare(l, r) as u8;
1237                                    Owned(vec![r])
1238                                }
1239                                BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div => {
1240                                    let r = match op {
1241                                        BinOp::Add => l + r,
1242                                        BinOp::Sub => l - r,
1243                                        BinOp::Mul => l * r,
1244                                        BinOp::Div => l / r,
1245                                        _ => unreachable!(),
1246                                    };
1247                                    Owned(r.value.to_bits().to_le_bytes().into())
1248                                }
1249                                it => not_supported!(
1250                                    "invalid binop {it:?} on floating point operators"
1251                                ),
1252                            }
1253                        }
1254                    }
1255                } else {
1256                    let is_signed = matches!(ty.kind(), TyKind::Int(_));
1257                    let l128 = IntValue::from_bytes(lc, is_signed);
1258                    let r128 = IntValue::from_bytes(rc, is_signed);
1259                    match op {
1260                        BinOp::Ge | BinOp::Gt | BinOp::Le | BinOp::Lt | BinOp::Eq | BinOp::Ne => {
1261                            let r = op.run_compare(l128, r128) as u8;
1262                            Owned(vec![r])
1263                        }
1264                        BinOp::BitAnd
1265                        | BinOp::BitOr
1266                        | BinOp::BitXor
1267                        | BinOp::Add
1268                        | BinOp::Mul
1269                        | BinOp::Div
1270                        | BinOp::Rem
1271                        | BinOp::Sub => {
1272                            let r = match op {
1273                                BinOp::Add => l128.checked_add(r128).ok_or_else(|| {
1274                                    MirEvalError::Panic(format!("Overflow in {op:?}"))
1275                                })?,
1276                                BinOp::Mul => l128.checked_mul(r128).ok_or_else(|| {
1277                                    MirEvalError::Panic(format!("Overflow in {op:?}"))
1278                                })?,
1279                                BinOp::Div => l128.checked_div(r128).ok_or_else(|| {
1280                                    MirEvalError::Panic(format!("Overflow in {op:?}"))
1281                                })?,
1282                                BinOp::Rem => l128.checked_rem(r128).ok_or_else(|| {
1283                                    MirEvalError::Panic(format!("Overflow in {op:?}"))
1284                                })?,
1285                                BinOp::Sub => l128.checked_sub(r128).ok_or_else(|| {
1286                                    MirEvalError::Panic(format!("Overflow in {op:?}"))
1287                                })?,
1288                                BinOp::BitAnd => l128 & r128,
1289                                BinOp::BitOr => l128 | r128,
1290                                BinOp::BitXor => l128 ^ r128,
1291                                _ => unreachable!(),
1292                            };
1293                            Owned(r.to_bytes())
1294                        }
1295                        BinOp::Shl | BinOp::Shr => {
1296                            let r = 'b: {
1297                                if let Some(shift_amount) = r128.as_u32() {
1298                                    let r = match op {
1299                                        BinOp::Shl => l128.checked_shl(shift_amount),
1300                                        BinOp::Shr => l128.checked_shr(shift_amount),
1301                                        _ => unreachable!(),
1302                                    };
1303                                    if shift_amount as usize >= lc.len() * 8 {
1304                                        return Err(MirEvalError::Panic(format!(
1305                                            "Overflow in {op:?}"
1306                                        )));
1307                                    }
1308                                    if let Some(r) = r {
1309                                        break 'b r;
1310                                    }
1311                                };
1312                                return Err(MirEvalError::Panic(format!("Overflow in {op:?}")));
1313                            };
1314                            Owned(r.to_bytes())
1315                        }
1316                        BinOp::Offset => not_supported!("offset binop"),
1317                    }
1318                }
1319            }
1320            Rvalue::Discriminant(p) => {
1321                let ty = self.place_ty(p, locals)?;
1322                let bytes = self.eval_place(p, locals)?.get(self)?;
1323                let result = self.compute_discriminant(ty, bytes)?;
1324                Owned(result.to_le_bytes().to_vec())
1325            }
1326            Rvalue::Repeat(it, len) => {
1327                let len = match try_const_usize(self.db, len.as_ref()) {
1328                    Some(it) => it as usize,
1329                    None => not_supported!("non evaluatable array len in repeat Rvalue"),
1330                };
1331                let val = self.eval_operand(it, locals)?.get(self)?;
1332                let size = len * val.len();
1333                Owned(val.iter().copied().cycle().take(size).collect())
1334            }
1335            Rvalue::CopyForDeref(_) => not_supported!("copy for deref"),
1336            Rvalue::Aggregate(kind, values) => {
1337                let values = values
1338                    .iter()
1339                    .map(|it| self.eval_operand(it, locals))
1340                    .collect::<Result<'db, Vec<_>>>()?;
1341                match kind {
1342                    AggregateKind::Array(_) => {
1343                        let mut r = vec![];
1344                        for it in values {
1345                            let value = it.get(self)?;
1346                            r.extend(value);
1347                        }
1348                        Owned(r)
1349                    }
1350                    AggregateKind::Tuple(ty) => {
1351                        let layout = self.layout(ty.as_ref())?;
1352                        Owned(self.construct_with_layout(
1353                            layout.size.bytes_usize(),
1354                            &layout,
1355                            None,
1356                            values.iter().map(|&it| it.into()),
1357                        )?)
1358                    }
1359                    AggregateKind::Union(it, f) => {
1360                        let layout = self.layout_adt((*it).into(), GenericArgs::empty())?;
1361                        let offset = layout
1362                            .fields
1363                            .offset(u32::from(f.local_id.into_raw()) as usize)
1364                            .bytes_usize();
1365                        let op = values[0].get(self)?;
1366                        let mut result = vec![0; layout.size.bytes_usize()];
1367                        result[offset..offset + op.len()].copy_from_slice(op);
1368                        Owned(result)
1369                    }
1370                    AggregateKind::Adt(it, subst) => {
1371                        let (size, variant_layout, tag) =
1372                            self.layout_of_variant(*it, subst.as_ref(), locals)?;
1373                        Owned(self.construct_with_layout(
1374                            size,
1375                            &variant_layout,
1376                            tag,
1377                            values.iter().map(|&it| it.into()),
1378                        )?)
1379                    }
1380                    AggregateKind::Closure(ty) => {
1381                        let layout = self.layout(ty.as_ref())?;
1382                        Owned(self.construct_with_layout(
1383                            layout.size.bytes_usize(),
1384                            &layout,
1385                            None,
1386                            values.iter().map(|&it| it.into()),
1387                        )?)
1388                    }
1389                }
1390            }
1391            Rvalue::Cast(kind, operand, target_ty) => match kind {
1392                CastKind::PointerCoercion(cast) => match cast {
1393                    PointerCast::ReifyFnPointer | PointerCast::ClosureFnPointer(_) => {
1394                        let current_ty = self.operand_ty(operand, locals)?;
1395                        if let TyKind::FnDef(_, _) | TyKind::Closure(_, _) = current_ty.kind() {
1396                            let id = self.vtable_map.id(current_ty);
1397                            let ptr_size = self.ptr_size();
1398                            Owned(id.to_le_bytes()[0..ptr_size].to_vec())
1399                        } else {
1400                            not_supported!(
1401                                "creating a fn pointer from a non FnDef or Closure type"
1402                            );
1403                        }
1404                    }
1405                    PointerCast::Unsize => {
1406                        let current_ty = self.operand_ty(operand, locals)?;
1407                        let addr = self.eval_operand(operand, locals)?;
1408                        self.coerce_unsized(addr, current_ty, target_ty.as_ref())?
1409                    }
1410                    PointerCast::MutToConstPointer | PointerCast::UnsafeFnPointer => {
1411                        // This is no-op
1412                        Borrowed(self.eval_operand(operand, locals)?)
1413                    }
1414                    PointerCast::ArrayToPointer => {
1415                        // We should remove the metadata part if the current type is slice
1416                        Borrowed(self.eval_operand(operand, locals)?.slice(0..self.ptr_size()))
1417                    }
1418                },
1419                CastKind::DynStar => not_supported!("dyn star cast"),
1420                CastKind::IntToInt
1421                | CastKind::PtrToPtr
1422                | CastKind::PointerExposeAddress
1423                | CastKind::PointerFromExposedAddress => {
1424                    let current_ty = self.operand_ty(operand, locals)?;
1425                    let is_signed = matches!(current_ty.kind(), TyKind::Int(_)).into();
1426                    let current = pad16(self.eval_operand(operand, locals)?.get(self)?, is_signed);
1427                    let dest_size = self.size_of_sized(
1428                        target_ty.as_ref(),
1429                        locals,
1430                        "destination of int to int cast",
1431                    )?;
1432                    Owned(current[0..dest_size].to_vec())
1433                }
1434                CastKind::FloatToInt => {
1435                    let ty = self.operand_ty(operand, locals)?;
1436                    let TyKind::Float(ty) = ty.kind() else {
1437                        not_supported!("invalid float to int cast");
1438                    };
1439                    let value = self.eval_operand(operand, locals)?.get(self)?;
1440                    let value = match ty {
1441                        rustc_type_ir::FloatTy::F32 => {
1442                            let value = value.try_into().unwrap();
1443                            f32::from_le_bytes(value) as f64
1444                        }
1445                        rustc_type_ir::FloatTy::F64 => {
1446                            let value = value.try_into().unwrap();
1447                            f64::from_le_bytes(value)
1448                        }
1449                        rustc_type_ir::FloatTy::F16 | rustc_type_ir::FloatTy::F128 => {
1450                            not_supported!("unstable floating point type f16 and f128");
1451                        }
1452                    };
1453                    let is_signed = matches!(target_ty.as_ref().kind(), TyKind::Int(_));
1454                    let dest_size = self.size_of_sized(
1455                        target_ty.as_ref(),
1456                        locals,
1457                        "destination of float to int cast",
1458                    )?;
1459                    let dest_bits = dest_size * 8;
1460                    let (max, min) = if dest_bits == 128 {
1461                        (i128::MAX, i128::MIN)
1462                    } else if is_signed {
1463                        let max = 1i128 << (dest_bits - 1);
1464                        (max - 1, -max)
1465                    } else {
1466                        ((1i128 << dest_bits) - 1, 0)
1467                    };
1468                    let value = (value as i128).min(max).max(min);
1469                    let result = value.to_le_bytes();
1470                    Owned(result[0..dest_size].to_vec())
1471                }
1472                CastKind::FloatToFloat => {
1473                    let ty = self.operand_ty(operand, locals)?;
1474                    let TyKind::Float(ty) = ty.kind() else {
1475                        not_supported!("invalid float to int cast");
1476                    };
1477                    let value = self.eval_operand(operand, locals)?.get(self)?;
1478                    let value = match ty {
1479                        rustc_type_ir::FloatTy::F32 => {
1480                            let value = value.try_into().unwrap();
1481                            f32::from_le_bytes(value) as f64
1482                        }
1483                        rustc_type_ir::FloatTy::F64 => {
1484                            let value = value.try_into().unwrap();
1485                            f64::from_le_bytes(value)
1486                        }
1487                        rustc_type_ir::FloatTy::F16 | rustc_type_ir::FloatTy::F128 => {
1488                            not_supported!("unstable floating point type f16 and f128");
1489                        }
1490                    };
1491                    let TyKind::Float(target_ty) = target_ty.as_ref().kind() else {
1492                        not_supported!("invalid float to float cast");
1493                    };
1494                    match target_ty {
1495                        rustc_type_ir::FloatTy::F32 => Owned((value as f32).to_le_bytes().to_vec()),
1496                        rustc_type_ir::FloatTy::F64 => Owned(value.to_le_bytes().to_vec()),
1497                        rustc_type_ir::FloatTy::F16 | rustc_type_ir::FloatTy::F128 => {
1498                            not_supported!("unstable floating point type f16 and f128");
1499                        }
1500                    }
1501                }
1502                CastKind::IntToFloat => {
1503                    let current_ty = self.operand_ty(operand, locals)?;
1504                    let is_signed = matches!(current_ty.kind(), TyKind::Int(_));
1505                    let value =
1506                        pad16(self.eval_operand(operand, locals)?.get(self)?, is_signed.into());
1507                    let value = u128::from_le_bytes(value);
1508                    let TyKind::Float(target_ty) = target_ty.as_ref().kind() else {
1509                        not_supported!("invalid int to float cast");
1510                    };
1511                    match target_ty {
1512                        rustc_type_ir::FloatTy::F32 => {
1513                            let value = if is_signed { value as i128 as f32 } else { value as f32 };
1514                            Owned(value.to_le_bytes().to_vec())
1515                        }
1516                        rustc_type_ir::FloatTy::F64 => {
1517                            let value = if is_signed { value as i128 as f64 } else { value as f64 };
1518                            Owned(value.to_le_bytes().to_vec())
1519                        }
1520                        rustc_type_ir::FloatTy::F16 | rustc_type_ir::FloatTy::F128 => {
1521                            not_supported!("unstable floating point type f16 and f128");
1522                        }
1523                    }
1524                }
1525                CastKind::FnPtrToPtr => not_supported!("fn ptr to ptr cast"),
1526            },
1527            Rvalue::ThreadLocalRef(n)
1528            | Rvalue::AddressOf(n)
1529            | Rvalue::BinaryOp(n)
1530            | Rvalue::NullaryOp(n) => match *n {},
1531        })
1532    }
1533
1534    fn compute_discriminant(&self, ty: Ty<'db>, bytes: &[u8]) -> Result<'db, i128> {
1535        let layout = self.layout(ty)?;
1536        let TyKind::Adt(adt_def, _) = ty.kind() else {
1537            return Ok(0);
1538        };
1539        let AdtId::EnumId(e) = adt_def.def_id() else {
1540            return Ok(0);
1541        };
1542        match &layout.variants {
1543            Variants::Empty => Err(MirEvalError::UndefinedBehavior(
1544                "reading the discriminant of an uninhabited enum".to_owned(),
1545            )),
1546            Variants::Single { index } => {
1547                let r =
1548                    self.const_eval_discriminant(e.enum_variants(self.db).variants[index.0].0)?;
1549                Ok(r)
1550            }
1551            Variants::Multiple { tag, tag_encoding, variants, .. } => {
1552                let size = tag.size(self.target_data_layout).bytes_usize();
1553                let offset = layout.fields.offset(0).bytes_usize(); // The only field on enum variants is the tag field
1554                let is_signed = tag.is_signed().into();
1555                match tag_encoding {
1556                    TagEncoding::Direct => {
1557                        let tag = &bytes[offset..offset + size];
1558                        Ok(i128::from_le_bytes(pad16(tag, is_signed)))
1559                    }
1560                    TagEncoding::Niche { untagged_variant, niche_start, .. } => {
1561                        let tag = &bytes[offset..offset + size];
1562                        let candidate_tag = i128::from_le_bytes(pad16(tag, is_signed))
1563                            .wrapping_sub(*niche_start as i128)
1564                            as usize;
1565                        let idx = variants
1566                            .iter_enumerated()
1567                            .map(|(it, _)| it)
1568                            .filter(|it| it != untagged_variant)
1569                            .nth(candidate_tag)
1570                            .unwrap_or(*untagged_variant)
1571                            .0;
1572                        let result =
1573                            self.const_eval_discriminant(e.enum_variants(self.db).variants[idx].0)?;
1574                        Ok(result)
1575                    }
1576                }
1577            }
1578        }
1579    }
1580
1581    fn coerce_unsized_look_through_fields<T>(
1582        &self,
1583        ty: Ty<'db>,
1584        goal: impl Fn(TyKind<'db>) -> Option<T>,
1585    ) -> Result<'db, T> {
1586        let kind = ty.kind();
1587        if let Some(it) = goal(kind) {
1588            return Ok(it);
1589        }
1590        match kind {
1591            TyKind::Adt(adt_ef, subst) if let AdtId::StructId(struct_id) = adt_ef.def_id() => {
1592                let field_types = self.db.field_types(struct_id.into());
1593                if let Some(ty) = field_types
1594                    .iter()
1595                    .last()
1596                    .map(|it| it.1.ty().instantiate(self.interner(), subst))
1597                {
1598                    return self.coerce_unsized_look_through_fields(ty.skip_norm_wip(), goal);
1599                }
1600            }
1601            TyKind::Pat(ty, _) => return self.coerce_unsized_look_through_fields(ty, goal),
1602            _ => (),
1603        }
1604        Err(MirEvalError::CoerceUnsizedError(ty.store()))
1605    }
1606
1607    fn coerce_unsized(
1608        &mut self,
1609        addr: Interval,
1610        current_ty: Ty<'db>,
1611        target_ty: Ty<'db>,
1612    ) -> Result<'db, IntervalOrOwned> {
1613        fn for_ptr<'db>(it: TyKind<'db>) -> Option<Ty<'db>> {
1614            match it {
1615                TyKind::RawPtr(ty, _) | TyKind::Ref(_, ty, _) => Some(ty),
1616                _ => None,
1617            }
1618        }
1619        let target_ty = self.coerce_unsized_look_through_fields(target_ty, for_ptr)?;
1620        let current_ty = self.coerce_unsized_look_through_fields(current_ty, for_ptr)?;
1621
1622        self.unsizing_ptr_from_addr(target_ty, current_ty, addr)
1623    }
1624
1625    /// Adds metadata to the address and create the fat pointer result of the unsizing operation.
1626    fn unsizing_ptr_from_addr(
1627        &mut self,
1628        target_ty: Ty<'db>,
1629        current_ty: Ty<'db>,
1630        addr: Interval,
1631    ) -> Result<'db, IntervalOrOwned> {
1632        use IntervalOrOwned::*;
1633        Ok(match &target_ty.kind() {
1634            TyKind::Slice(_) => match &current_ty.kind() {
1635                TyKind::Array(_, size) => {
1636                    let len = match try_const_usize(self.db, *size) {
1637                        None => {
1638                            not_supported!("unevaluatble len of array in coerce unsized")
1639                        }
1640                        Some(it) => it as usize,
1641                    };
1642                    let mut r = Vec::with_capacity(16);
1643                    let addr = addr.get(self)?;
1644                    r.extend(addr.iter().copied());
1645                    r.extend(len.to_le_bytes());
1646                    Owned(r)
1647                }
1648                t => {
1649                    not_supported!("slice unsizing from non array type {t:?}")
1650                }
1651            },
1652            TyKind::Dynamic(..) => {
1653                let vtable = self.vtable_map.id(current_ty);
1654                let mut r = Vec::with_capacity(16);
1655                let addr = addr.get(self)?;
1656                r.extend(addr.iter().copied());
1657                r.extend(vtable.to_le_bytes());
1658                Owned(r)
1659            }
1660            TyKind::Adt(adt_def, target_subst) => match &current_ty.kind() {
1661                TyKind::Adt(current_adt_def, current_subst) => {
1662                    let id = adt_def.def_id();
1663                    let current_id = current_adt_def.def_id();
1664                    if id != current_id {
1665                        not_supported!("unsizing struct with different type");
1666                    }
1667                    let id = match id {
1668                        AdtId::StructId(s) => s,
1669                        AdtId::UnionId(_) => not_supported!("unsizing unions"),
1670                        AdtId::EnumId(_) => not_supported!("unsizing enums"),
1671                    };
1672                    let Some((last_field, _)) = id.fields(self.db).fields().iter().next_back()
1673                    else {
1674                        not_supported!("unsizing struct without field");
1675                    };
1676                    let target_last_field = self.db.field_types(id.into())[last_field]
1677                        .ty()
1678                        .instantiate(self.interner(), target_subst)
1679                        .skip_norm_wip();
1680                    let current_last_field = self.db.field_types(id.into())[last_field]
1681                        .ty()
1682                        .instantiate(self.interner(), current_subst)
1683                        .skip_norm_wip();
1684                    return self.unsizing_ptr_from_addr(
1685                        target_last_field,
1686                        current_last_field,
1687                        addr,
1688                    );
1689                }
1690                _ => not_supported!("unsizing struct with non adt type"),
1691            },
1692            _ => not_supported!("unknown unsized cast"),
1693        })
1694    }
1695
1696    fn layout_of_variant(
1697        &mut self,
1698        it: VariantId,
1699        subst: GenericArgs<'db>,
1700        locals: &Locals<'a, 'db>,
1701    ) -> Result<'db, (usize, Arc<Layout>, Option<(usize, usize, i128)>)> {
1702        let adt = it.adt_id(self.db);
1703        if let Some(f) = locals.body.owner.as_variant()
1704            && let VariantId::EnumVariantId(it) = it
1705            && let AdtId::EnumId(e) = adt
1706            && f.lookup(self.db).parent == e
1707        {
1708            // Computing the exact size of enums require resolving the enum discriminants. In order to prevent loops (and
1709            // infinite sized type errors) we use a dummy layout
1710            let i = self.const_eval_discriminant(it)?;
1711            return Ok((16, self.layout(Ty::new_empty_tuple(self.interner()))?, Some((0, 16, i))));
1712        }
1713        let layout = self.layout_adt(adt, subst)?;
1714        Ok(match &layout.variants {
1715            Variants::Single { .. } | Variants::Empty => (layout.size.bytes_usize(), layout, None),
1716            Variants::Multiple { variants, tag, tag_encoding, .. } => {
1717                let enum_variant_id = match it {
1718                    VariantId::EnumVariantId(it) => it,
1719                    _ => not_supported!("multi variant layout for non-enums"),
1720                };
1721                let mut discriminant = self.const_eval_discriminant(enum_variant_id)?;
1722                let rustc_enum_variant_idx = RustcEnumVariantIdx(enum_variant_id.index(self.db));
1723                let variant_layout = variants[rustc_enum_variant_idx].clone();
1724                let have_tag = match tag_encoding {
1725                    TagEncoding::Direct => true,
1726                    TagEncoding::Niche { untagged_variant, niche_variants: _, niche_start } => {
1727                        if *untagged_variant == rustc_enum_variant_idx {
1728                            false
1729                        } else {
1730                            discriminant = (variants
1731                                .iter_enumerated()
1732                                .filter(|(it, _)| it != untagged_variant)
1733                                .position(|(it, _)| it == rustc_enum_variant_idx)
1734                                .unwrap() as i128)
1735                                .wrapping_add(*niche_start as i128);
1736                            true
1737                        }
1738                    }
1739                };
1740                (
1741                    layout.size.bytes_usize(),
1742                    Arc::new(variant_layout),
1743                    if have_tag {
1744                        Some((
1745                            layout.fields.offset(0).bytes_usize(),
1746                            tag.size(self.target_data_layout).bytes_usize(),
1747                            discriminant,
1748                        ))
1749                    } else {
1750                        None
1751                    },
1752                )
1753            }
1754        })
1755    }
1756
1757    fn construct_with_layout(
1758        &mut self,
1759        size: usize, // Not necessarily equal to variant_layout.size
1760        variant_layout: &Layout,
1761        tag: Option<(usize, usize, i128)>,
1762        values: impl Iterator<Item = IntervalOrOwned>,
1763    ) -> Result<'db, Vec<u8>> {
1764        let mut result = vec![0; size];
1765        if let Some((offset, size, value)) = tag {
1766            match result.get_mut(offset..offset + size) {
1767                Some(it) => it.copy_from_slice(&value.to_le_bytes()[0..size]),
1768                None => {
1769                    return Err(MirEvalError::InternalError(
1770                        format!(
1771                            "encoded tag ({offset}, {size}, {value}) is out of bounds 0..{size}"
1772                        )
1773                        .into(),
1774                    ));
1775                }
1776            }
1777        }
1778        for (i, op) in values.enumerate() {
1779            let offset = variant_layout.fields.offset(i).bytes_usize();
1780            let op = op.get(self)?;
1781            match result.get_mut(offset..offset + op.len()) {
1782                Some(it) => it.copy_from_slice(op),
1783                None => {
1784                    return Err(MirEvalError::InternalError(
1785                        format!("field offset ({offset}) is out of bounds 0..{size}").into(),
1786                    ));
1787                }
1788            }
1789        }
1790        Ok(result)
1791    }
1792
1793    fn eval_operand(
1794        &mut self,
1795        it: &Operand,
1796        locals: &mut Locals<'a, 'db>,
1797    ) -> Result<'db, Interval> {
1798        Ok(match &it.kind {
1799            OperandKind::Copy(p) | OperandKind::Move(p) => {
1800                locals.drop_flags.remove_place(p.as_ref());
1801                self.eval_place(p, locals)?
1802            }
1803            OperandKind::Static(st) => {
1804                let addr = self.eval_static(*st, locals)?;
1805                Interval::new(addr, self.ptr_size())
1806            }
1807            OperandKind::Constant { konst, .. } => {
1808                self.allocate_const_in_heap(locals, konst.as_ref())?
1809            }
1810            OperandKind::Allocation { allocation } => {
1811                self.allocate_allocation_in_heap(locals, allocation.as_ref())?
1812            }
1813        })
1814    }
1815
1816    fn allocate_valtree_in_heap(
1817        &mut self,
1818        ty: Ty<'db>,
1819        valtree: ValTree<'db>,
1820    ) -> Result<'db, Interval> {
1821        match ty.kind() {
1822            TyKind::Bool => {
1823                let value = valtree.inner().to_leaf().try_to_bool().unwrap();
1824                let addr = self.heap_allocate(1, 1)?;
1825                self.write_memory(addr, &[u8::from(value)])?;
1826                Ok(Interval::new(addr, 1))
1827            }
1828            TyKind::Char => {
1829                let value = valtree.inner().to_leaf().to_u32();
1830                let addr = self.heap_allocate(4, 4)?;
1831                self.write_memory(addr, &value.to_le_bytes())?;
1832                Ok(Interval::new(addr, 4))
1833            }
1834            TyKind::Int(int_ty) => {
1835                let size = int_ty
1836                    .bit_width()
1837                    .map(Size::from_bits)
1838                    .unwrap_or_else(|| Size::from_bytes(self.ptr_size() as u64));
1839                let bytes = size.bytes_usize();
1840
1841                let value = valtree.inner().to_leaf().to_int(size);
1842                let addr = self.heap_allocate(bytes, bytes)?;
1843                self.write_memory(addr, &value.to_le_bytes()[..bytes])?;
1844                Ok(Interval::new(addr, bytes))
1845            }
1846            TyKind::Uint(uint_ty) => {
1847                let size = uint_ty
1848                    .bit_width()
1849                    .map(Size::from_bits)
1850                    .unwrap_or_else(|| Size::from_bytes(self.ptr_size() as u64));
1851                let bytes = size.bytes_usize();
1852
1853                let value = valtree.inner().to_leaf().to_uint(size);
1854                let addr = self.heap_allocate(bytes, bytes)?;
1855                self.write_memory(addr, &value.to_le_bytes()[..bytes])?;
1856                Ok(Interval::new(addr, bytes))
1857            }
1858            TyKind::Float(float_ty) => {
1859                let size = Size::from_bits(float_ty.bit_width());
1860                let bytes = size.bytes_usize();
1861
1862                let value = valtree.inner().to_leaf().to_uint(size);
1863                let addr = self.heap_allocate(bytes, bytes)?;
1864                self.write_memory(addr, &value.to_le_bytes()[..bytes])?;
1865                Ok(Interval::new(addr, bytes))
1866            }
1867            TyKind::RawPtr(..) => {
1868                let size = self.ptr_size();
1869                let value = valtree.inner().to_leaf().to_uint(Size::from_bytes(size));
1870                let addr = self.heap_allocate(size, size)?;
1871                self.write_memory(addr, &value.to_le_bytes()[..size])?;
1872                Ok(Interval::new(addr, size))
1873            }
1874            TyKind::Ref(_, inner_ty, _) => match inner_ty.kind() {
1875                TyKind::Str => {
1876                    let bytes = valtree
1877                        .inner()
1878                        .to_branch()
1879                        .iter()
1880                        .map(|konst| match konst.kind() {
1881                            ConstKind::Value(value) => Ok(value.value.inner().to_leaf().to_u8()),
1882                            _ => not_supported!("unsupported const"),
1883                        })
1884                        .collect::<Result<'_, Vec<_>>>()?;
1885                    let bytes_addr = self.heap_allocate(bytes.len(), 1)?;
1886                    self.write_memory(bytes_addr, &bytes)?;
1887                    let ref_addr = self.heap_allocate(self.ptr_size() * 2, self.ptr_size())?;
1888                    self.write_memory(ref_addr, &bytes_addr.to_bytes())?;
1889                    let mut len = [0; 16];
1890                    len[..size_of::<usize>()].copy_from_slice(&bytes.len().to_le_bytes());
1891                    self.write_memory(ref_addr.offset(self.ptr_size()), &len[..self.ptr_size()])?;
1892                    Ok(Interval::new(ref_addr, self.ptr_size() * 2))
1893                }
1894                TyKind::Slice(inner_ty) => {
1895                    let item_layout = self.layout(inner_ty)?;
1896                    let items = valtree
1897                        .inner()
1898                        .to_branch()
1899                        .iter()
1900                        .map(|konst| match konst.kind() {
1901                            ConstKind::Value(value) => {
1902                                self.allocate_valtree_in_heap(value.ty, value.value)
1903                            }
1904                            _ => not_supported!("unsupported const"),
1905                        })
1906                        .collect::<Result<'_, Vec<_>>>()?;
1907                    let item_size = item_layout.size.bytes_usize();
1908                    let items_addr = self.heap_allocate(
1909                        items.len() * item_size,
1910                        item_layout.align.bytes() as usize,
1911                    )?;
1912                    for (i, item) in items.iter().enumerate() {
1913                        self.copy_from_interval(items_addr.offset(i * item_size), *item)?;
1914                    }
1915                    let ref_addr = self.heap_allocate(self.ptr_size() * 2, self.ptr_size())?;
1916                    self.write_memory(ref_addr, &items_addr.to_bytes())?;
1917                    let mut len = [0; 16];
1918                    len[..size_of::<usize>()].copy_from_slice(&items.len().to_le_bytes());
1919                    self.write_memory(ref_addr.offset(self.ptr_size()), &len[..self.ptr_size()])?;
1920                    Ok(Interval::new(ref_addr, self.ptr_size() * 2))
1921                }
1922                TyKind::Dynamic(..) => not_supported!("`dyn Trait` consts not supported yet"),
1923                _ => {
1924                    let inner_addr = self.allocate_valtree_in_heap(inner_ty, valtree)?;
1925                    let ref_addr = self.heap_allocate(self.ptr_size(), self.ptr_size())?;
1926                    self.write_memory(ref_addr, &inner_addr.addr.to_bytes())?;
1927                    Ok(Interval::new(ref_addr, self.ptr_size()))
1928                }
1929            },
1930            TyKind::Adt(_, _) | TyKind::Array(_, _) | TyKind::Tuple(_) => {
1931                not_supported!(
1932                    "ADTs, arrays and tuples are unsupported in consts currently (requires `adt_const_params`)"
1933                )
1934            }
1935            TyKind::Pat(_, _)
1936            | TyKind::Slice(_)
1937            | TyKind::FnDef(_, _)
1938            | TyKind::Foreign(_)
1939            | TyKind::Dynamic(_, _)
1940            | TyKind::UnsafeBinder(..)
1941            | TyKind::FnPtr(..)
1942            | TyKind::Closure(_, _)
1943            | TyKind::CoroutineClosure(_, _)
1944            | TyKind::Coroutine(_, _)
1945            | TyKind::CoroutineWitness(_, _)
1946            | TyKind::Never
1947            | TyKind::Alias(..)
1948            | TyKind::Param(_)
1949            | TyKind::Bound(..)
1950            | TyKind::Placeholder(_)
1951            | TyKind::Infer(_)
1952            | TyKind::Str
1953            | TyKind::Error(_) => not_supported!("unsupported const"),
1954        }
1955    }
1956
1957    fn allocate_const_in_heap(
1958        &mut self,
1959        locals: &Locals<'a, 'db>,
1960        konst: Const<'db>,
1961    ) -> Result<'db, Interval> {
1962        match konst.kind() {
1963            ConstKind::Value(value) => self.allocate_valtree_in_heap(value.ty, value.value),
1964            ConstKind::Unevaluated(UnevaluatedConst { def: const_id, args: subst }) => {
1965                let mut id = const_id.0;
1966                let mut subst = subst;
1967                if let GeneralConstId::ConstId(c) = id {
1968                    let (c, s) = lookup_impl_const(&self.infcx, self.param_env.param_env, c, subst);
1969                    id = GeneralConstId::ConstId(c);
1970                    subst = s;
1971                }
1972                let allocation = match id {
1973                    GeneralConstId::ConstId(const_id) => {
1974                        self.db.const_eval(const_id, subst, Some(self.param_env)).map_err(|e| {
1975                            let name = id.name(self.db);
1976                            MirEvalError::ConstEvalError(name, Box::new(e))
1977                        })?
1978                    }
1979                    GeneralConstId::StaticId(static_id) => {
1980                        self.db.const_eval_static(static_id).map_err(|e| {
1981                            let name = id.name(self.db);
1982                            MirEvalError::ConstEvalError(name, Box::new(e))
1983                        })?
1984                    }
1985                    GeneralConstId::AnonConstId(anon_const_id) => self
1986                        .db
1987                        .anon_const_eval(anon_const_id, subst, Some(self.param_env))
1988                        .map_err(|e| {
1989                            let name = id.name(self.db);
1990                            MirEvalError::ConstEvalError(name, Box::new(e))
1991                        })?,
1992                };
1993                self.allocate_allocation_in_heap(locals, allocation)
1994            }
1995            _ => not_supported!("evaluating unknown const"),
1996        }
1997    }
1998
1999    fn allocate_allocation_in_heap(
2000        &mut self,
2001        locals: &Locals<'a, 'db>,
2002        allocation: Allocation<'db>,
2003    ) -> Result<'db, Interval> {
2004        let AllocationData { ty, memory: ref v, ref memory_map } = *allocation;
2005        let patch_map = memory_map.transform_addresses(|b, align| {
2006            let addr = self.heap_allocate(b.len(), align)?;
2007            self.write_memory(addr, b)?;
2008            Ok(addr.to_usize())
2009        })?;
2010        let (size, align) = self.size_align_of(allocation.ty, locals)?.unwrap_or((v.len(), 1));
2011        let v: Cow<'_, [u8]> = if size != v.len() {
2012            // Handle self enum
2013            if size == 16 && v.len() < 16 {
2014                Cow::Owned(pad16(v, IsSigned::No).to_vec())
2015            } else if size < 16 && v.len() == 16 {
2016                Cow::Borrowed(&v[0..size])
2017            } else {
2018                return Err(MirEvalError::InvalidConst);
2019            }
2020        } else {
2021            Cow::Borrowed(v)
2022        };
2023        let addr = self.heap_allocate(size, align)?;
2024        self.write_memory(addr, &v)?;
2025        self.patch_addresses(
2026            &patch_map,
2027            |bytes| match memory_map {
2028                MemoryMap::Empty | MemoryMap::Simple(_) => {
2029                    Err(MirEvalError::InvalidVTableId(from_bytes!(usize, bytes)))
2030                }
2031                MemoryMap::Complex(cm) => cm.vtable.ty_of_bytes(bytes),
2032            },
2033            addr,
2034            ty,
2035            locals,
2036        )?;
2037        Ok(Interval::new(addr, size))
2038    }
2039
2040    fn eval_place(&mut self, p: &StoredPlace, locals: &Locals<'a, 'db>) -> Result<'db, Interval> {
2041        let addr = self.place_addr(p, locals)?;
2042        Ok(Interval::new(
2043            addr,
2044            self.size_of_sized(self.place_ty(p, locals)?, locals, "type of this place")?,
2045        ))
2046    }
2047
2048    fn read_memory(&self, addr: Address, size: usize) -> Result<'db, &[u8]> {
2049        if size == 0 {
2050            return Ok(&[]);
2051        }
2052        let (mem, pos) = match addr {
2053            Stack(it) => (&self.stack, it),
2054            Heap(it) => (&self.heap, it),
2055            Invalid(it) => {
2056                return Err(MirEvalError::UndefinedBehavior(format!(
2057                    "read invalid memory address {it} with size {size}"
2058                )));
2059            }
2060        };
2061        mem.get(pos..pos + size)
2062            .ok_or_else(|| MirEvalError::UndefinedBehavior("out of bound memory read".to_owned()))
2063    }
2064
2065    fn write_memory_using_ref(&mut self, addr: Address, size: usize) -> Result<'db, &mut [u8]> {
2066        let (mem, pos) = match addr {
2067            Stack(it) => (&mut self.stack, it),
2068            Heap(it) => (&mut self.heap, it),
2069            Invalid(it) => {
2070                return Err(MirEvalError::UndefinedBehavior(format!(
2071                    "write invalid memory address {it} with size {size}"
2072                )));
2073            }
2074        };
2075        mem.get_mut(pos..pos + size)
2076            .ok_or_else(|| MirEvalError::UndefinedBehavior("out of bound memory write".to_owned()))
2077    }
2078
2079    fn write_memory(&mut self, addr: Address, r: &[u8]) -> Result<'db, ()> {
2080        if r.is_empty() {
2081            return Ok(());
2082        }
2083        self.write_memory_using_ref(addr, r.len())?.copy_from_slice(r);
2084        Ok(())
2085    }
2086
2087    fn copy_from_interval_or_owned(
2088        &mut self,
2089        addr: Address,
2090        r: IntervalOrOwned,
2091    ) -> Result<'db, ()> {
2092        match r {
2093            IntervalOrOwned::Borrowed(r) => self.copy_from_interval(addr, r),
2094            IntervalOrOwned::Owned(r) => self.write_memory(addr, &r),
2095        }
2096    }
2097
2098    fn copy_from_interval(&mut self, addr: Address, r: Interval) -> Result<'db, ()> {
2099        if r.size == 0 {
2100            return Ok(());
2101        }
2102
2103        let oob = || MirEvalError::UndefinedBehavior("out of bounds memory write".to_owned());
2104
2105        match (addr, r.addr) {
2106            (Stack(dst), Stack(src)) => {
2107                if self.stack.len() < src + r.size || self.stack.len() < dst + r.size {
2108                    return Err(oob());
2109                }
2110                self.stack.copy_within(src..src + r.size, dst)
2111            }
2112            (Heap(dst), Heap(src)) => {
2113                if self.heap.len() < src + r.size || self.heap.len() < dst + r.size {
2114                    return Err(oob());
2115                }
2116                self.heap.copy_within(src..src + r.size, dst)
2117            }
2118            (Stack(dst), Heap(src)) => {
2119                self.stack
2120                    .get_mut(dst..dst + r.size)
2121                    .ok_or_else(oob)?
2122                    .copy_from_slice(self.heap.get(src..src + r.size).ok_or_else(oob)?);
2123            }
2124            (Heap(dst), Stack(src)) => {
2125                self.heap
2126                    .get_mut(dst..dst + r.size)
2127                    .ok_or_else(oob)?
2128                    .copy_from_slice(self.stack.get(src..src + r.size).ok_or_else(oob)?);
2129            }
2130            _ => {
2131                return Err(MirEvalError::UndefinedBehavior(format!(
2132                    "invalid memory write at address {addr:?}"
2133                )));
2134            }
2135        }
2136
2137        Ok(())
2138    }
2139
2140    fn size_align_of(
2141        &self,
2142        ty: Ty<'db>,
2143        locals: &Locals<'a, 'db>,
2144    ) -> Result<'db, Option<(usize, usize)>> {
2145        if let Some(layout) = self.layout_cache.borrow().get(&ty) {
2146            return Ok(layout
2147                .is_sized()
2148                .then(|| (layout.size.bytes_usize(), layout.align.bytes() as usize)));
2149        }
2150        if let Some(f) = locals.body.owner.as_variant()
2151            && let Some((AdtId::EnumId(e), _)) = ty.as_adt()
2152            && f.lookup(self.db).parent == e
2153        {
2154            // Computing the exact size of enums require resolving the enum discriminants. In order to prevent loops (and
2155            // infinite sized type errors) we use a dummy size
2156            return Ok(Some((16, 16)));
2157        }
2158        let layout = self.layout(ty);
2159        if self.assert_placeholder_ty_is_unused
2160            && matches!(layout, Err(MirEvalError::LayoutError(LayoutError::HasPlaceholder, _)))
2161        {
2162            return Ok(Some((0, 1)));
2163        }
2164        let layout = layout?;
2165        Ok(layout.is_sized().then(|| (layout.size.bytes_usize(), layout.align.bytes() as usize)))
2166    }
2167
2168    /// A version of `self.size_of` which returns error if the type is unsized. `what` argument should
2169    /// be something that complete this: `error: type {ty} was unsized. {what} should be sized`
2170    fn size_of_sized(
2171        &self,
2172        ty: Ty<'db>,
2173        locals: &Locals<'a, 'db>,
2174        what: &'static str,
2175    ) -> Result<'db, usize> {
2176        match self.size_align_of(ty, locals)? {
2177            Some(it) => Ok(it.0),
2178            None => Err(MirEvalError::TypeIsUnsized(ty.store(), what)),
2179        }
2180    }
2181
2182    /// A version of `self.size_align_of` which returns error if the type is unsized. `what` argument should
2183    /// be something that complete this: `error: type {ty} was unsized. {what} should be sized`
2184    fn size_align_of_sized(
2185        &self,
2186        ty: Ty<'db>,
2187        locals: &Locals<'a, 'db>,
2188        what: &'static str,
2189    ) -> Result<'db, (usize, usize)> {
2190        match self.size_align_of(ty, locals)? {
2191            Some(it) => Ok(it),
2192            None => Err(MirEvalError::TypeIsUnsized(ty.store(), what)),
2193        }
2194    }
2195
2196    fn heap_allocate(&mut self, size: usize, align: usize) -> Result<'db, Address> {
2197        if !align.is_power_of_two() || align > 10000 {
2198            return Err(MirEvalError::UndefinedBehavior(format!("Alignment {align} is invalid")));
2199        }
2200        while !self.heap.len().is_multiple_of(align) {
2201            self.heap.push(0);
2202        }
2203        if size.checked_add(self.heap.len()).is_none_or(|x| x > self.memory_limit) {
2204            return Err(MirEvalError::Panic(format!("Memory allocation of {size} bytes failed")));
2205        }
2206        let pos = self.heap.len();
2207        self.heap.extend(std::iter::repeat_n(0, size));
2208        Ok(Address::Heap(pos))
2209    }
2210
2211    fn detect_fn_trait(&self, def: FunctionId) -> Option<FnTrait> {
2212        let def = Some(def);
2213        if def == self.cached_fn_trait_func {
2214            Some(FnTrait::Fn)
2215        } else if def == self.cached_fn_mut_trait_func {
2216            Some(FnTrait::FnMut)
2217        } else if def == self.cached_fn_once_trait_func {
2218            Some(FnTrait::FnOnce)
2219        } else {
2220            None
2221        }
2222    }
2223
2224    fn create_memory_map(
2225        &self,
2226        bytes: &[u8],
2227        ty: Ty<'db>,
2228        locals: &Locals<'a, 'db>,
2229    ) -> Result<'db, ComplexMemoryMap<'db>> {
2230        fn rec<'a, 'db>(
2231            this: &Evaluator<'a, 'db>,
2232            bytes: &[u8],
2233            ty: Ty<'db>,
2234            locals: &Locals<'a, 'db>,
2235            mm: &mut ComplexMemoryMap<'db>,
2236            stack_depth_limit: usize,
2237        ) -> Result<'db, ()> {
2238            if stack_depth_limit.checked_sub(1).is_none() {
2239                return Err(MirEvalError::StackOverflow);
2240            }
2241            match ty.kind() {
2242                TyKind::Ref(_, t, _) => {
2243                    let size = this.size_align_of(t, locals)?;
2244                    match size {
2245                        Some((size, _)) => {
2246                            let addr_usize = from_bytes!(usize, bytes);
2247                            let bytes =
2248                                this.read_memory(Address::from_usize(addr_usize), size)?.to_vec();
2249                            mm.insert(addr_usize, bytes.clone().into());
2250                            rec(this, &bytes, t, locals, mm, stack_depth_limit - 1)?;
2251                        }
2252                        None => {
2253                            let mut check_inner = None;
2254                            let (addr, meta) = bytes.split_at(bytes.len() / 2);
2255                            let element_size = match t.kind() {
2256                                TyKind::Str => 1,
2257                                TyKind::Slice(t) => {
2258                                    check_inner = Some(t);
2259                                    this.size_of_sized(t, locals, "slice inner type")?
2260                                }
2261                                TyKind::Dynamic(..) => {
2262                                    let t = this.vtable_map.ty_of_bytes(meta)?;
2263                                    check_inner = Some(t);
2264                                    this.size_of_sized(t, locals, "dyn concrete type")?
2265                                }
2266                                _ => return Ok(()),
2267                            };
2268                            let count = match t.kind() {
2269                                TyKind::Dynamic(..) => 1,
2270                                _ => from_bytes!(usize, meta),
2271                            };
2272                            let size = element_size * count;
2273                            let addr = Address::from_bytes(addr)?;
2274                            let b = this.read_memory(addr, size)?;
2275                            mm.insert(addr.to_usize(), b.into());
2276                            if let Some(ty) = check_inner {
2277                                for i in 0..count {
2278                                    let offset = element_size * i;
2279                                    rec(
2280                                        this,
2281                                        &b[offset..offset + element_size],
2282                                        ty,
2283                                        locals,
2284                                        mm,
2285                                        stack_depth_limit - 1,
2286                                    )?;
2287                                }
2288                            }
2289                        }
2290                    }
2291                }
2292                TyKind::Array(inner, len) => {
2293                    let len = match try_const_usize(this.db, len) {
2294                        Some(it) => it as usize,
2295                        None => not_supported!("non evaluatable array len in patching addresses"),
2296                    };
2297                    let size = this.size_of_sized(inner, locals, "inner of array")?;
2298                    for i in 0..len {
2299                        let offset = i * size;
2300                        rec(
2301                            this,
2302                            &bytes[offset..offset + size],
2303                            inner,
2304                            locals,
2305                            mm,
2306                            stack_depth_limit - 1,
2307                        )?;
2308                    }
2309                }
2310                TyKind::Tuple(subst) => {
2311                    let layout = this.layout(ty)?;
2312                    for (id, ty) in subst.iter().enumerate() {
2313                        let offset = layout.fields.offset(id).bytes_usize();
2314                        let size = this.layout(ty)?.size.bytes_usize();
2315                        rec(
2316                            this,
2317                            &bytes[offset..offset + size],
2318                            ty,
2319                            locals,
2320                            mm,
2321                            stack_depth_limit - 1,
2322                        )?;
2323                    }
2324                }
2325                TyKind::Adt(adt, subst) => match adt.def_id() {
2326                    AdtId::StructId(s) => {
2327                        let data = s.fields(this.db);
2328                        let layout = this.layout(ty)?;
2329                        let field_types = this.db.field_types(s.into());
2330                        for (f, _) in data.fields().iter() {
2331                            let offset = layout
2332                                .fields
2333                                .offset(u32::from(f.into_raw()) as usize)
2334                                .bytes_usize();
2335                            let ty = field_types[f]
2336                                .ty()
2337                                .instantiate(this.interner(), subst)
2338                                .skip_norm_wip();
2339                            let size = this.layout(ty)?.size.bytes_usize();
2340                            rec(
2341                                this,
2342                                &bytes[offset..offset + size],
2343                                ty,
2344                                locals,
2345                                mm,
2346                                stack_depth_limit - 1,
2347                            )?;
2348                        }
2349                    }
2350                    AdtId::EnumId(e) => {
2351                        let layout = this.layout(ty)?;
2352                        if let Some((v, l)) = detect_variant_from_bytes(
2353                            &layout,
2354                            this.db,
2355                            this.target_data_layout,
2356                            bytes,
2357                            e,
2358                        ) {
2359                            let data = v.fields(this.db);
2360                            let field_types = this.db.field_types(v.into());
2361                            for (f, _) in data.fields().iter() {
2362                                let offset =
2363                                    l.fields.offset(u32::from(f.into_raw()) as usize).bytes_usize();
2364                                let ty = field_types[f]
2365                                    .ty()
2366                                    .instantiate(this.interner(), subst)
2367                                    .skip_norm_wip();
2368                                let size = this.layout(ty)?.size.bytes_usize();
2369                                rec(
2370                                    this,
2371                                    &bytes[offset..offset + size],
2372                                    ty,
2373                                    locals,
2374                                    mm,
2375                                    stack_depth_limit - 1,
2376                                )?;
2377                            }
2378                        }
2379                    }
2380                    AdtId::UnionId(_) => (),
2381                },
2382                TyKind::Alias(AliasTy { kind: AliasTyKind::Projection { .. }, .. }) => {
2383                    let mut ocx = ObligationCtxt::new(&this.infcx);
2384                    let ty = ocx
2385                        .structurally_normalize_ty(
2386                            &ObligationCause::dummy(),
2387                            this.param_env.param_env,
2388                            ty,
2389                        )
2390                        .map_err(|_| MirEvalError::NotSupported("couldn't normalize".to_owned()))?;
2391
2392                    rec(this, bytes, ty, locals, mm, stack_depth_limit - 1)?;
2393                }
2394                _ => (),
2395            }
2396            Ok(())
2397        }
2398        let mut mm = ComplexMemoryMap::default();
2399        rec(self, bytes, ty, locals, &mut mm, self.stack_depth_limit - 1)?;
2400        Ok(mm)
2401    }
2402
2403    fn patch_addresses(
2404        &mut self,
2405        patch_map: &FxHashMap<usize, usize>,
2406        ty_of_bytes: impl Fn(&[u8]) -> Result<'db, Ty<'db>> + Copy,
2407        addr: Address,
2408        ty: Ty<'db>,
2409        locals: &Locals<'a, 'db>,
2410    ) -> Result<'db, ()> {
2411        let layout = self.layout(ty)?;
2412        let my_size = self.size_of_sized(ty, locals, "value to patch address")?;
2413        use rustc_type_ir::TyKind;
2414        match ty.kind() {
2415            TyKind::Ref(_, t, _) => {
2416                let size = self.size_align_of(t, locals)?;
2417                match size {
2418                    Some(_) => {
2419                        let current = from_bytes!(usize, self.read_memory(addr, my_size)?);
2420                        let patched = match patch_map.get(&current) {
2421                            Some(it) => {
2422                                self.write_memory(addr, &it.to_le_bytes())?;
2423                                *it
2424                            }
2425                            None => current,
2426                        };
2427                        self.patch_addresses(
2428                            patch_map,
2429                            ty_of_bytes,
2430                            Address::from_usize(patched),
2431                            t,
2432                            locals,
2433                        )?;
2434                    }
2435                    None => {
2436                        let bytes = self.read_memory(addr, my_size)?;
2437                        let (current, metadata) = bytes.split_at(my_size / 2);
2438                        let metadata = metadata.to_vec();
2439                        let current = from_bytes!(usize, current);
2440                        let patched = match patch_map.get(&current) {
2441                            Some(it) => {
2442                                self.write_memory(addr, &it.to_le_bytes())?;
2443                                *it
2444                            }
2445                            None => current,
2446                        };
2447                        let patched = Address::from_usize(patched);
2448                        if let TyKind::Slice(inner) = t.kind() {
2449                            let len = from_bytes!(usize, metadata);
2450                            let size = self.size_of_sized(inner, locals, "slice item to patch")?;
2451                            for i in 0..len {
2452                                self.patch_addresses(
2453                                    patch_map,
2454                                    ty_of_bytes,
2455                                    patched.offset(i * size),
2456                                    inner,
2457                                    locals,
2458                                )?;
2459                            }
2460                        }
2461                    }
2462                }
2463            }
2464            TyKind::FnPtr(_, _) => {
2465                let ty = ty_of_bytes(self.read_memory(addr, my_size)?)?;
2466                let new_id = self.vtable_map.id(ty);
2467                self.write_memory(addr, &new_id.to_le_bytes())?;
2468            }
2469            TyKind::Adt(id, args) => match id.def_id() {
2470                AdtId::StructId(s) => {
2471                    for (i, (_, field)) in self.db.field_types(s.into()).iter().enumerate() {
2472                        let offset = layout.fields.offset(i).bytes_usize();
2473                        let ty = field.ty().instantiate(self.interner(), args).skip_norm_wip();
2474                        self.patch_addresses(
2475                            patch_map,
2476                            ty_of_bytes,
2477                            addr.offset(offset),
2478                            ty,
2479                            locals,
2480                        )?;
2481                    }
2482                }
2483                AdtId::UnionId(_) => (),
2484                AdtId::EnumId(e) => {
2485                    if let Some((ev, layout)) = detect_variant_from_bytes(
2486                        &layout,
2487                        self.db,
2488                        self.target_data_layout,
2489                        self.read_memory(addr, layout.size.bytes_usize())?,
2490                        e,
2491                    ) {
2492                        for (i, (_, field)) in self.db.field_types(ev.into()).iter().enumerate() {
2493                            let offset = layout.fields.offset(i).bytes_usize();
2494                            let ty = field.ty().instantiate(self.interner(), args).skip_norm_wip();
2495                            self.patch_addresses(
2496                                patch_map,
2497                                ty_of_bytes,
2498                                addr.offset(offset),
2499                                ty,
2500                                locals,
2501                            )?;
2502                        }
2503                    }
2504                }
2505            },
2506            TyKind::Tuple(tys) => {
2507                for (id, ty) in tys.iter().enumerate() {
2508                    let offset = layout.fields.offset(id).bytes_usize();
2509                    self.patch_addresses(patch_map, ty_of_bytes, addr.offset(offset), ty, locals)?;
2510                }
2511            }
2512            TyKind::Array(inner, len) => {
2513                let len = match consteval::try_const_usize(self.db, len) {
2514                    Some(it) => it as usize,
2515                    None => not_supported!("non evaluatable array len in patching addresses"),
2516                };
2517                let size = self.size_of_sized(inner, locals, "inner of array")?;
2518                for i in 0..len {
2519                    self.patch_addresses(
2520                        patch_map,
2521                        ty_of_bytes,
2522                        addr.offset(i * size),
2523                        inner,
2524                        locals,
2525                    )?;
2526                }
2527            }
2528            TyKind::Bool
2529            | TyKind::Char
2530            | TyKind::Int(_)
2531            | TyKind::Uint(_)
2532            | TyKind::Float(_)
2533            | TyKind::Slice(_)
2534            | TyKind::RawPtr(_, _)
2535            | TyKind::FnDef(_, _)
2536            | TyKind::Str
2537            | TyKind::Never
2538            | TyKind::Closure(_, _)
2539            | TyKind::Coroutine(_, _)
2540            | TyKind::CoroutineWitness(_, _)
2541            | TyKind::Foreign(_)
2542            | TyKind::Error(_)
2543            | TyKind::Placeholder(_)
2544            | TyKind::Dynamic(_, _)
2545            | TyKind::Alias(..)
2546            | TyKind::Bound(_, _)
2547            | TyKind::Infer(_)
2548            | TyKind::Pat(_, _)
2549            | TyKind::Param(_)
2550            | TyKind::UnsafeBinder(_)
2551            | TyKind::CoroutineClosure(_, _) => (),
2552        }
2553        Ok(())
2554    }
2555
2556    fn exec_fn_pointer(
2557        &mut self,
2558        bytes: Interval,
2559        destination: Interval,
2560        args: &[IntervalAndTy<'db>],
2561        locals: &Locals<'a, 'db>,
2562        target_bb: Option<BasicBlockId>,
2563        span: MirSpan,
2564    ) -> Result<'db, Option<StackFrame<'a, 'db>>> {
2565        let id = from_bytes!(usize, bytes.get(self)?);
2566        let next_ty = self.vtable_map.ty(id)?;
2567        use rustc_type_ir::TyKind;
2568        match next_ty.kind() {
2569            TyKind::FnDef(def, generic_args) => {
2570                self.exec_fn_def(def.0, generic_args, destination, args, locals, target_bb, span)
2571            }
2572            TyKind::Closure(id, generic_args) => self.exec_closure(
2573                id.0,
2574                bytes.slice(0..0),
2575                generic_args,
2576                destination,
2577                args,
2578                locals,
2579                span,
2580            ),
2581            _ => Err(MirEvalError::InternalError("function pointer to non function".into())),
2582        }
2583    }
2584
2585    fn exec_closure(
2586        &mut self,
2587        closure: InternedClosureId<'db>,
2588        closure_data: Interval,
2589        generic_args: GenericArgs<'db>,
2590        destination: Interval,
2591        args: &[IntervalAndTy<'db>],
2592        locals: &Locals<'a, 'db>,
2593        span: MirSpan,
2594    ) -> Result<'db, Option<StackFrame<'a, 'db>>> {
2595        let mir_body = self
2596            .db
2597            .monomorphized_mir_body_for_closure(
2598                closure,
2599                generic_args.store(),
2600                self.param_env.store(),
2601            )
2602            .map_err(|it| MirEvalError::MirLowerErrorForClosure(closure, it))?;
2603        let closure_data =
2604            if mir_body.locals[mir_body.param_locals[0]].ty.as_ref().as_reference().is_some() {
2605                closure_data.addr.to_bytes().to_vec()
2606            } else {
2607                closure_data.get(self)?.to_owned()
2608            };
2609        let arg_bytes = iter::once(Ok(closure_data))
2610            .chain(args.iter().map(|it| Ok(it.get(self)?.to_owned())))
2611            .collect::<Result<'db, Vec<_>>>()?;
2612        let interval = self
2613            .interpret_mir(mir_body, arg_bytes.into_iter().map(IntervalOrOwned::Owned))
2614            .map_err(|e| {
2615                MirEvalError::InFunction(
2616                    Box::new(e),
2617                    vec![(Either::Right(closure), span, locals.body.owner)],
2618                )
2619            })?;
2620        destination.write_from_interval(self, interval)?;
2621        Ok(None)
2622    }
2623
2624    fn exec_fn_def(
2625        &mut self,
2626        def: CallableDefId,
2627        generic_args: GenericArgs<'db>,
2628        destination: Interval,
2629        args: &[IntervalAndTy<'db>],
2630        locals: &Locals<'a, 'db>,
2631        target_bb: Option<BasicBlockId>,
2632        span: MirSpan,
2633    ) -> Result<'db, Option<StackFrame<'a, 'db>>> {
2634        match def {
2635            CallableDefId::FunctionId(def) => {
2636                if self.detect_fn_trait(def).is_some() {
2637                    return self.exec_fn_trait(
2638                        def,
2639                        args,
2640                        generic_args,
2641                        locals,
2642                        destination,
2643                        target_bb,
2644                        span,
2645                    );
2646                }
2647                self.exec_fn_with_args(
2648                    def,
2649                    args,
2650                    generic_args,
2651                    locals,
2652                    destination,
2653                    target_bb,
2654                    span,
2655                )
2656            }
2657            CallableDefId::StructId(id) => {
2658                let (size, variant_layout, tag) =
2659                    self.layout_of_variant(id.into(), generic_args, locals)?;
2660                let result = self.construct_with_layout(
2661                    size,
2662                    &variant_layout,
2663                    tag,
2664                    args.iter().map(|it| it.interval.into()),
2665                )?;
2666                destination.write_from_bytes(self, &result)?;
2667                Ok(None)
2668            }
2669            CallableDefId::EnumVariantId(id) => {
2670                let (size, variant_layout, tag) =
2671                    self.layout_of_variant(id.into(), generic_args, locals)?;
2672                let result = self.construct_with_layout(
2673                    size,
2674                    &variant_layout,
2675                    tag,
2676                    args.iter().map(|it| it.interval.into()),
2677                )?;
2678                destination.write_from_bytes(self, &result)?;
2679                Ok(None)
2680            }
2681        }
2682    }
2683
2684    fn get_mir_or_dyn_index(
2685        &self,
2686        def: FunctionId,
2687        generic_args: GenericArgs<'db>,
2688        locals: &Locals<'a, 'db>,
2689        span: MirSpan,
2690    ) -> Result<'db, MirOrDynIndex<'db>> {
2691        let pair = (def, generic_args);
2692        if let Some(r) = self.mir_or_dyn_index_cache.borrow().get(&pair) {
2693            return Ok(r.clone());
2694        }
2695        let (def, generic_args) = pair;
2696        let r = if let Some(self_ty_idx) =
2697            is_dyn_method(self.interner(), self.param_env.param_env, def, generic_args)
2698        {
2699            MirOrDynIndex::Dyn(self_ty_idx)
2700        } else {
2701            let (imp, generic_args) = self.db.lookup_impl_method(
2702                ParamEnvAndCrate { param_env: self.param_env.param_env, krate: self.crate_id },
2703                def,
2704                generic_args,
2705            );
2706            let Either::Left(imp) = imp else {
2707                not_supported!("evaluating builtin derive impls is not supported")
2708            };
2709
2710            let mir_body = self
2711                .db
2712                .monomorphized_mir_body(imp.into(), generic_args.store(), self.param_env.store())
2713                .map_err(|e| {
2714                    MirEvalError::InFunction(
2715                        Box::new(MirEvalError::MirLowerError(imp, e)),
2716                        vec![(Either::Left(imp), span, locals.body.owner)],
2717                    )
2718                })?;
2719            MirOrDynIndex::Mir(mir_body)
2720        };
2721        self.mir_or_dyn_index_cache.borrow_mut().insert((def, generic_args), r.clone());
2722        Ok(r)
2723    }
2724
2725    fn exec_fn_with_args(
2726        &mut self,
2727        mut def: FunctionId,
2728        args: &[IntervalAndTy<'db>],
2729        generic_args: GenericArgs<'db>,
2730        locals: &Locals<'a, 'db>,
2731        destination: Interval,
2732        target_bb: Option<BasicBlockId>,
2733        span: MirSpan,
2734    ) -> Result<'db, Option<StackFrame<'a, 'db>>> {
2735        if self.detect_and_exec_special_function(
2736            def,
2737            args,
2738            generic_args,
2739            locals,
2740            destination,
2741            span,
2742        )? {
2743            return Ok(None);
2744        }
2745        if let Some(redirect_def) = self.detect_and_redirect_special_function(def)? {
2746            def = redirect_def;
2747        }
2748        let arg_bytes = args.iter().map(|it| IntervalOrOwned::Borrowed(it.interval));
2749        match self.get_mir_or_dyn_index(def, generic_args, locals, span)? {
2750            MirOrDynIndex::Dyn(self_ty_idx) => {
2751                // In the layout of current possible receiver, which at the moment of writing this code is one of
2752                // `&T`, `&mut T`, `Box<T>`, `Rc<T>`, `Arc<T>`, and `Pin<P>` where `P` is one of possible receivers,
2753                // the vtable is exactly in the `[ptr_size..2*ptr_size]` bytes. So we can use it without branching on
2754                // the type.
2755                let first_arg = arg_bytes.clone().next().unwrap();
2756                let first_arg = first_arg.get(self)?;
2757                let ty = self
2758                    .vtable_map
2759                    .ty_of_bytes(&first_arg[self.ptr_size()..self.ptr_size() * 2])?;
2760                let mut args_for_target = args.to_vec();
2761                args_for_target[0] = IntervalAndTy {
2762                    interval: args_for_target[0].interval.slice(0..self.ptr_size()),
2763                    ty,
2764                };
2765                let generics_for_target = GenericArgs::new_from_iter(
2766                    generic_args
2767                        .iter()
2768                        .enumerate()
2769                        .map(|(i, it)| if i == self_ty_idx { ty.into() } else { it }),
2770                );
2771                self.exec_fn_with_args(
2772                    def,
2773                    &args_for_target,
2774                    generics_for_target,
2775                    locals,
2776                    destination,
2777                    target_bb,
2778                    span,
2779                )
2780            }
2781            MirOrDynIndex::Mir(body) => self.exec_looked_up_function(
2782                body,
2783                locals,
2784                def,
2785                arg_bytes,
2786                span,
2787                destination,
2788                target_bb,
2789            ),
2790        }
2791    }
2792
2793    fn exec_looked_up_function(
2794        &mut self,
2795        mir_body: &'db MirBody<'db>,
2796        locals: &Locals<'a, 'db>,
2797        def: FunctionId,
2798        arg_bytes: impl Iterator<Item = IntervalOrOwned>,
2799        span: MirSpan,
2800        destination: Interval,
2801        target_bb: Option<BasicBlockId>,
2802    ) -> Result<'db, Option<StackFrame<'a, 'db>>> {
2803        if let Some(target_bb) = target_bb {
2804            let (mut locals, prev_stack_ptr) =
2805                self.create_locals_for_body(mir_body, Some(destination))?;
2806            self.fill_locals_for_body(mir_body, &mut locals, arg_bytes.into_iter())?;
2807            let span = (span, locals.body.owner);
2808            Ok(Some(StackFrame { locals, destination: Some(target_bb), prev_stack_ptr, span }))
2809        } else {
2810            let result = self.interpret_mir(mir_body, arg_bytes).map_err(|e| {
2811                MirEvalError::InFunction(
2812                    Box::new(e),
2813                    vec![(Either::Left(def), span, locals.body.owner)],
2814                )
2815            })?;
2816            destination.write_from_interval(self, result)?;
2817            Ok(None)
2818        }
2819    }
2820
2821    fn exec_fn_trait(
2822        &mut self,
2823        def: FunctionId,
2824        args: &[IntervalAndTy<'db>],
2825        generic_args: GenericArgs<'db>,
2826        locals: &Locals<'a, 'db>,
2827        destination: Interval,
2828        target_bb: Option<BasicBlockId>,
2829        span: MirSpan,
2830    ) -> Result<'db, Option<StackFrame<'a, 'db>>> {
2831        let func = args
2832            .first()
2833            .ok_or_else(|| MirEvalError::InternalError("fn trait with no arg".into()))?;
2834        let mut func_ty = func.ty;
2835        let mut func_data = func.interval;
2836        while let TyKind::Ref(_, z, _) = func_ty.kind() {
2837            func_ty = z;
2838            if matches!(func_ty.kind(), TyKind::Dynamic(..)) {
2839                let id =
2840                    from_bytes!(usize, &func_data.get(self)?[self.ptr_size()..self.ptr_size() * 2]);
2841                func_data = func_data.slice(0..self.ptr_size());
2842                func_ty = self.vtable_map.ty(id)?;
2843            }
2844            let size = self.size_of_sized(func_ty, locals, "self type of fn trait")?;
2845            func_data = Interval { addr: Address::from_bytes(func_data.get(self)?)?, size };
2846        }
2847        match func_ty.kind() {
2848            TyKind::FnDef(def, subst) => {
2849                self.exec_fn_def(def.0, subst, destination, &args[1..], locals, target_bb, span)
2850            }
2851            TyKind::FnPtr(..) => {
2852                self.exec_fn_pointer(func_data, destination, &args[1..], locals, target_bb, span)
2853            }
2854            TyKind::Closure(closure, subst) => self.exec_closure(
2855                closure.0,
2856                func_data,
2857                GenericArgs::new_from_slice(subst.as_closure().parent_args()),
2858                destination,
2859                &args[1..],
2860                locals,
2861                span,
2862            ),
2863            _ => {
2864                // try to execute the manual impl of `FnTrait` for structs (nightly feature used in std)
2865                let arg0 = func;
2866                let args = &args[1..];
2867                let arg1 = {
2868                    let ty = Ty::new_tup_from_iter(self.interner(), args.iter().map(|it| it.ty));
2869                    let layout = self.layout(ty)?;
2870                    let result = self.construct_with_layout(
2871                        layout.size.bytes_usize(),
2872                        &layout,
2873                        None,
2874                        args.iter().map(|it| IntervalOrOwned::Borrowed(it.interval)),
2875                    )?;
2876                    // FIXME: there is some leak here
2877                    let size = layout.size.bytes_usize();
2878                    let addr = self.heap_allocate(size, layout.align.bytes() as usize)?;
2879                    self.write_memory(addr, &result)?;
2880                    IntervalAndTy { interval: Interval { addr, size }, ty }
2881                };
2882                self.exec_fn_with_args(
2883                    def,
2884                    &[arg0.clone(), arg1],
2885                    generic_args,
2886                    locals,
2887                    destination,
2888                    target_bb,
2889                    span,
2890                )
2891            }
2892        }
2893    }
2894
2895    fn eval_static(&mut self, st: StaticId, locals: &Locals<'a, 'db>) -> Result<'db, Address> {
2896        if let Some(o) = self.static_locations.get(&st) {
2897            return Ok(*o);
2898        };
2899        let static_data = StaticSignature::of(self.db, st);
2900        let result = if !static_data.flags.contains(StaticFlags::EXTERN) {
2901            let allocation = self.db.const_eval_static(st).map_err(|e| {
2902                MirEvalError::ConstEvalError(static_data.name.as_str().to_owned(), Box::new(e))
2903            })?;
2904            self.allocate_allocation_in_heap(locals, allocation)?
2905        } else {
2906            let ty = InferenceResult::of(self.db, DefWithBodyId::from(st))
2907                .expr_ty(Body::of(self.db, st.into()).root_expr());
2908            let Some((size, align)) = self.size_align_of(ty, locals)? else {
2909                not_supported!("unsized extern static");
2910            };
2911            let addr = self.heap_allocate(size, align)?;
2912            Interval::new(addr, size)
2913        };
2914        let addr = self.heap_allocate(self.ptr_size(), self.ptr_size())?;
2915        self.write_memory(addr, &result.addr.to_bytes())?;
2916        self.static_locations.insert(st, addr);
2917        Ok(addr)
2918    }
2919
2920    fn const_eval_discriminant(&self, variant: EnumVariantId) -> Result<'db, i128> {
2921        let r = self.db.const_eval_discriminant(variant);
2922        match r {
2923            Ok(r) => Ok(r),
2924            Err(e) => {
2925                let db = self.db;
2926                let loc = variant.lookup(db);
2927                let edition = self.crate_id.data(self.db).edition;
2928                let name = format!(
2929                    "{}::{}",
2930                    EnumSignature::of(self.db, loc.parent).name.display(db, edition),
2931                    loc.parent
2932                        .enum_variants(self.db)
2933                        .variant_name_by_id(variant)
2934                        .unwrap()
2935                        .display(db, edition),
2936                );
2937                Err(MirEvalError::ConstEvalError(name, Box::new(e)))
2938            }
2939        }
2940    }
2941
2942    fn drop_place(
2943        &mut self,
2944        place: &StoredPlace,
2945        locals: &mut Locals<'a, 'db>,
2946        span: MirSpan,
2947    ) -> Result<'db, ()> {
2948        let (addr, ty, metadata) = self.place_addr_and_ty_and_metadata(place, locals)?;
2949        if !locals.drop_flags.remove_place(place.as_ref()) {
2950            return Ok(());
2951        }
2952        let metadata = match metadata {
2953            Some(it) => it.get(self)?.to_vec(),
2954            None => vec![],
2955        };
2956        self.run_drop_glue_deep(ty, locals, addr, &metadata, span)
2957    }
2958
2959    fn run_drop_glue_deep(
2960        &mut self,
2961        ty: Ty<'db>,
2962        locals: &Locals<'a, 'db>,
2963        addr: Address,
2964        metadata: &[u8],
2965        span: MirSpan,
2966    ) -> Result<'db, ()> {
2967        let Some(drop_fn) = self.lang_items().Drop_drop else {
2968            // in some tests we don't have drop trait in minicore, and
2969            // we can ignore drop in them.
2970            return Ok(());
2971        };
2972
2973        let generic_args = GenericArgs::new_from_slice(&[ty.into()]);
2974        let (drop_impl, drop_args) = self.db.lookup_impl_method(
2975            ParamEnvAndCrate { param_env: self.param_env.param_env, krate: self.crate_id },
2976            drop_fn,
2977            generic_args,
2978        );
2979        if let Either::Left(drop_impl) = drop_impl
2980            && matches!(drop_impl.lookup(self.db).container, ItemContainerId::ImplId(_))
2981            && let Ok(body) = self.db.monomorphized_mir_body(
2982                drop_impl.into(),
2983                drop_args.store(),
2984                self.param_env.store(),
2985            )
2986        {
2987            self.exec_looked_up_function(
2988                body,
2989                locals,
2990                drop_impl,
2991                iter::once(IntervalOrOwned::Owned(addr.to_bytes().to_vec())),
2992                span,
2993                Interval { addr: Address::Invalid(0), size: 0 },
2994                None,
2995            )?;
2996        }
2997        match ty.kind() {
2998            TyKind::Adt(adt_def, subst) => {
2999                let id = adt_def.def_id();
3000                match id {
3001                    AdtId::StructId(s) => {
3002                        let data = StructSignature::of(self.db, s);
3003                        if data.flags.contains(StructFlags::IS_MANUALLY_DROP) {
3004                            return Ok(());
3005                        }
3006                        let layout = self.layout_adt(id, subst)?;
3007                        let variant_fields = s.fields(self.db);
3008                        match variant_fields.shape {
3009                            FieldsShape::Record | FieldsShape::Tuple => {
3010                                let field_types = self.db.field_types(s.into());
3011                                for (field, _) in variant_fields.fields().iter() {
3012                                    let offset = layout
3013                                        .fields
3014                                        .offset(u32::from(field.into_raw()) as usize)
3015                                        .bytes_usize();
3016                                    let addr = addr.offset(offset);
3017                                    let ty = field_types[field]
3018                                        .ty()
3019                                        .instantiate(self.interner(), subst)
3020                                        .skip_norm_wip();
3021                                    self.run_drop_glue_deep(ty, locals, addr, &[], span)?;
3022                                }
3023                            }
3024                            FieldsShape::Unit => (),
3025                        }
3026                    }
3027                    AdtId::UnionId(_) => (), // union fields don't need drop
3028                    AdtId::EnumId(_) => (),
3029                }
3030            }
3031            TyKind::Dynamic(..) => {
3032                if !metadata.is_empty() {
3033                    let concrete_ty = self.vtable_map.ty_of_bytes(metadata)?;
3034                    self.run_drop_glue_deep(concrete_ty, locals, addr, &[], span)?;
3035                }
3036            }
3037            TyKind::Bool
3038            | TyKind::Char
3039            | TyKind::Int(_)
3040            | TyKind::Uint(_)
3041            | TyKind::Float(_)
3042            | TyKind::Tuple(_)
3043            | TyKind::Array(_, _)
3044            | TyKind::Slice(_)
3045            | TyKind::RawPtr(_, _)
3046            | TyKind::Ref(_, _, _)
3047            | TyKind::Alias(..)
3048            | TyKind::FnDef(_, _)
3049            | TyKind::Str
3050            | TyKind::Never
3051            | TyKind::Closure(_, _)
3052            | TyKind::Coroutine(_, _)
3053            | TyKind::CoroutineClosure(..)
3054            | TyKind::CoroutineWitness(_, _)
3055            | TyKind::Foreign(_)
3056            | TyKind::Error(_)
3057            | TyKind::Param(_)
3058            | TyKind::Placeholder(_)
3059            | TyKind::FnPtr(..)
3060            | TyKind::Bound(..)
3061            | TyKind::Infer(..)
3062            | TyKind::Pat(..)
3063            | TyKind::UnsafeBinder(..) => (),
3064        };
3065        Ok(())
3066    }
3067
3068    fn write_to_stdout(&mut self, interval: Interval) -> Result<'db, ()> {
3069        self.stdout.extend(interval.get(self)?.to_vec());
3070        Ok(())
3071    }
3072
3073    fn write_to_stderr(&mut self, interval: Interval) -> Result<'db, ()> {
3074        self.stderr.extend(interval.get(self)?.to_vec());
3075        Ok(())
3076    }
3077}
3078
3079pub fn render_const_using_debug_impl<'db>(
3080    db: &'db dyn HirDatabase,
3081    owner: InferBodyId<'db>,
3082    c: Allocation<'db>,
3083    ty: Ty<'db>,
3084) -> Result<'db, String> {
3085    let mut evaluator = Evaluator::new(db, owner, false, None)?;
3086    let locals = &Locals {
3087        ptr: ArenaMap::new(),
3088        body: db
3089            .mir_body(owner)
3090            .map_err(|_| MirEvalError::NotSupported("unreachable".to_owned()))?,
3091        drop_flags: DropFlags::default(),
3092    };
3093    let data = evaluator.allocate_allocation_in_heap(locals, c)?;
3094    let lang_items = evaluator.interner().lang_items();
3095    let resolver = owner.resolver(db);
3096    let Some(debug_fmt_fn) = lang_items.Debug_fmt else {
3097        not_supported!("core::fmt::Debug::fmt not found");
3098    };
3099    let ptr_size = evaluator.ptr_size();
3100    // Construct the arguments of `format_args!("{:?}", THE_CONST)` directly in memory and hand
3101    // them to `std::fmt::format`.
3102    //
3103    // `core::fmt::rt::Argument` is a niche-encoded `Placeholder { value: NonNull<()>, formatter }`,
3104    // i.e. two words: a pointer to the value, and the type-erased `<T as Debug>::fmt` function.
3105    // A non-null `value` is what distinguishes the `Placeholder` variant from `Count`.
3106    let argument = evaluator.heap_allocate(ptr_size * 2, ptr_size)?;
3107    evaluator.write_memory(argument, &data.addr.to_bytes())?;
3108    let debug_fmt_fn_ptr = evaluator.vtable_map.id(Ty::new_fn_def(
3109        evaluator.interner(),
3110        CallableDefId::FunctionId(debug_fmt_fn).into(),
3111        GenericArgs::new_from_slice(&[ty.into()]),
3112    ));
3113    evaluator.write_memory(argument.offset(ptr_size), &debug_fmt_fn_ptr.to_le_bytes())?;
3114    // Since Rust 1.93 `core::fmt::Arguments` is two words wide:
3115    //   struct Arguments<'a> { template: NonNull<u8>, args: NonNull<Argument<'a>> }
3116    // `template` points at a byte-encoded format string; `format_args!("{:?}", x)` encodes to a
3117    // single default placeholder (`0xC0`) followed by the end marker (`0x00`). `args` points at
3118    // our one-element argument array, and must stay pointer-aligned: `core` uses the low bit of
3119    // `args` as a tag (1 = inline `&str` form, 0 = placeholder form), and heap allocations here
3120    // are pointer-aligned so the bit is 0 as required.
3121    let template = evaluator.heap_allocate(2, 1)?;
3122    evaluator.write_memory(template, &[0xC0, 0x00])?;
3123    let arguments = evaluator.heap_allocate(ptr_size * 2, ptr_size)?;
3124    evaluator.write_memory(arguments, &template.to_bytes())?;
3125    evaluator.write_memory(arguments.offset(ptr_size), &argument.to_bytes())?;
3126    let Some(ValueNs::FunctionId(format_fn)) = resolver.resolve_path_in_value_ns_fully(
3127        db,
3128        &hir_def::expr_store::path::Path::from_known_path_with_no_generic(path![std::fmt::format]),
3129        HygieneId::ROOT,
3130    ) else {
3131        not_supported!("std::fmt::format not found");
3132    };
3133    let interval = evaluator.interpret_mir(
3134        db.mir_body(format_fn.into()).map_err(|e| MirEvalError::MirLowerError(format_fn, e))?,
3135        [IntervalOrOwned::Borrowed(Interval { addr: arguments, size: ptr_size * 2 })].into_iter(),
3136    )?;
3137    let message_string = interval.get(&evaluator)?;
3138    let words = [
3139        from_bytes!(usize, message_string[0..ptr_size]),
3140        from_bytes!(usize, message_string[ptr_size..2 * ptr_size]),
3141        from_bytes!(usize, message_string[2 * ptr_size..3 * ptr_size]),
3142    ];
3143    let Some(addr) = words.into_iter().map(Address::from_usize).find(|it| matches!(it, Heap(_)))
3144    else {
3145        // No heap buffer means the formatted string is empty.
3146        return Ok(String::new());
3147    };
3148    let size = words
3149        .into_iter()
3150        .filter(|&it| !matches!(Address::from_usize(it), Heap(_)))
3151        .min()
3152        .unwrap_or(0);
3153    Ok(std::string::String::from_utf8_lossy(evaluator.read_memory(addr, size)?).into_owned())
3154}
3155
3156#[derive(PartialEq, Eq)]
3157pub enum IsSigned {
3158    Yes,
3159    No,
3160}
3161
3162impl From<bool> for IsSigned {
3163    fn from(value: bool) -> Self {
3164        if value { Self::Yes } else { Self::No }
3165    }
3166}
3167
3168pub fn pad16(it: &[u8], is_signed: IsSigned) -> [u8; 16] {
3169    let is_negative = is_signed == IsSigned::Yes && it.last().is_some_and(|n| *n > 127);
3170    let mut res = [if is_negative { 255 } else { 0 }; 16];
3171    res[..it.len()].copy_from_slice(it);
3172    res
3173}
3174
3175macro_rules! for_each_int_type {
3176    ($call_macro:path, $args:tt) => {
3177        $call_macro! {
3178            $args
3179            I8
3180            U8
3181            I16
3182            U16
3183            I32
3184            U32
3185            I64
3186            U64
3187            I128
3188            U128
3189        }
3190    };
3191}
3192
3193#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3194enum IntValue {
3195    I8(i8),
3196    U8(u8),
3197    I16(i16),
3198    U16(u16),
3199    I32(i32),
3200    U32(u32),
3201    I64(i64),
3202    U64(u64),
3203    I128(i128),
3204    U128(u128),
3205}
3206
3207macro_rules! checked_int_op {
3208    ( [ $op:ident ] $( $int_ty:ident )+ ) => {
3209        fn $op(self, other: Self) -> Option<Self> {
3210            match (self, other) {
3211                $( (Self::$int_ty(a), Self::$int_ty(b)) => a.$op(b).map(Self::$int_ty), )+
3212                _ => panic!("incompatible integer types"),
3213            }
3214        }
3215    };
3216}
3217
3218macro_rules! int_bit_shifts {
3219    ( [ $op:ident ] $( $int_ty:ident )+ ) => {
3220        fn $op(self, amount: u32) -> Option<Self> {
3221            match self {
3222                $( Self::$int_ty(this) => this.$op(amount).map(Self::$int_ty), )+
3223            }
3224        }
3225    };
3226}
3227
3228macro_rules! wrapping_int_bit_shifts {
3229    ( [ $op:ident ] $( $int_ty:ident )+ ) => {
3230        fn $op(self, amount: Self) -> Option<Self> {
3231            // Wrapping shifts only use the low bits of the shift count.
3232            let amount = amount.as_u128()? as u32;
3233            Some(match self {
3234                $( Self::$int_ty(this) => Self::$int_ty(this.$op(amount)), )+
3235            })
3236        }
3237    };
3238}
3239
3240macro_rules! overflowing_int_op {
3241    ( [ $op:ident ] $( $int_ty:ident )+ ) => {
3242        fn $op(self, other: Self) -> (Self, bool) {
3243            match (self, other) {
3244                $( (Self::$int_ty(a), Self::$int_ty(b)) => {
3245                    let (value, overflow) = a.$op(b);
3246                    (Self::$int_ty(value), overflow)
3247                }, )+
3248                _ => panic!("incompatible integer types"),
3249            }
3250        }
3251    };
3252}
3253
3254macro_rules! unchecked_int_op {
3255    ( [ $name:ident, $op:tt ]  $( $int_ty:ident )+ ) => {
3256        fn $name(self, other: Self) -> Self {
3257            match (self, other) {
3258                $( (Self::$int_ty(a), Self::$int_ty(b)) => Self::$int_ty(a $op b), )+
3259                _ => panic!("incompatible integer types"),
3260            }
3261        }
3262    };
3263}
3264
3265impl IntValue {
3266    fn from_bytes(bytes: &[u8], is_signed: bool) -> Self {
3267        match (bytes.len(), is_signed) {
3268            (1, false) => Self::U8(u8::from_le_bytes(bytes.try_into().unwrap())),
3269            (1, true) => Self::I8(i8::from_le_bytes(bytes.try_into().unwrap())),
3270            (2, false) => Self::U16(u16::from_le_bytes(bytes.try_into().unwrap())),
3271            (2, true) => Self::I16(i16::from_le_bytes(bytes.try_into().unwrap())),
3272            (4, false) => Self::U32(u32::from_le_bytes(bytes.try_into().unwrap())),
3273            (4, true) => Self::I32(i32::from_le_bytes(bytes.try_into().unwrap())),
3274            (8, false) => Self::U64(u64::from_le_bytes(bytes.try_into().unwrap())),
3275            (8, true) => Self::I64(i64::from_le_bytes(bytes.try_into().unwrap())),
3276            (16, false) => Self::U128(u128::from_le_bytes(bytes.try_into().unwrap())),
3277            (16, true) => Self::I128(i128::from_le_bytes(bytes.try_into().unwrap())),
3278            (len, is_signed) => {
3279                never!("invalid integer size: {len}, signed: {is_signed}");
3280                Self::I32(0)
3281            }
3282        }
3283    }
3284
3285    fn to_bytes(self) -> Vec<u8> {
3286        macro_rules! m {
3287            ( [] $( $int_ty:ident )+ ) => {
3288                match self {
3289                    $( Self::$int_ty(v) => v.to_le_bytes().to_vec() ),+
3290                }
3291            };
3292        }
3293        for_each_int_type! { m, [] }
3294    }
3295
3296    fn as_u32(self) -> Option<u32> {
3297        macro_rules! m {
3298            ( [] $( $int_ty:ident )+ ) => {
3299                match self {
3300                    $( Self::$int_ty(v) => v.try_into().ok() ),+
3301                }
3302            };
3303        }
3304        for_each_int_type! { m, [] }
3305    }
3306
3307    fn as_u128(self) -> Option<u128> {
3308        macro_rules! m {
3309            ( [] $( $int_ty:ident )+ ) => {
3310                match self {
3311                    $( Self::$int_ty(v) => v.try_into().ok() ),+
3312                }
3313            };
3314        }
3315        for_each_int_type! { m, [] }
3316    }
3317
3318    for_each_int_type!(checked_int_op, [checked_add]);
3319    for_each_int_type!(checked_int_op, [checked_sub]);
3320    for_each_int_type!(checked_int_op, [checked_div]);
3321    for_each_int_type!(checked_int_op, [checked_rem]);
3322    for_each_int_type!(checked_int_op, [checked_mul]);
3323
3324    for_each_int_type!(overflowing_int_op, [overflowing_add]);
3325    for_each_int_type!(overflowing_int_op, [overflowing_sub]);
3326    for_each_int_type!(overflowing_int_op, [overflowing_mul]);
3327
3328    for_each_int_type!(int_bit_shifts, [checked_shl]);
3329    for_each_int_type!(int_bit_shifts, [checked_shr]);
3330    for_each_int_type!(wrapping_int_bit_shifts, [wrapping_shl]);
3331    for_each_int_type!(wrapping_int_bit_shifts, [wrapping_shr]);
3332}
3333
3334impl std::ops::BitAnd for IntValue {
3335    type Output = Self;
3336    for_each_int_type!(unchecked_int_op, [bitand, &]);
3337}
3338impl std::ops::BitOr for IntValue {
3339    type Output = Self;
3340    for_each_int_type!(unchecked_int_op, [bitor, |]);
3341}
3342impl std::ops::BitXor for IntValue {
3343    type Output = Self;
3344    for_each_int_type!(unchecked_int_op, [bitxor, ^]);
3345}