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