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, PlaceRef, PlaceTy, ProjectionElem, Rvalue,
61    StatementKind, 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    #[allow(clippy::double_parens)]
313    fn from_bytes<'db>(it: &[u8]) -> Result<'db, Self> {
314        Ok(Address::from_usize(from_bytes!(usize, it)))
315    }
316
317    fn from_usize(it: usize) -> Self {
318        if it > STACK_OFFSET {
319            Stack(it - STACK_OFFSET)
320        } else if it > HEAP_OFFSET {
321            Heap(it - HEAP_OFFSET)
322        } else {
323            Invalid(it)
324        }
325    }
326
327    fn to_bytes(&self) -> [u8; size_of::<usize>()] {
328        usize::to_le_bytes(self.to_usize())
329    }
330
331    fn to_usize(&self) -> usize {
332        match self {
333            Stack(it) => *it + STACK_OFFSET,
334            Heap(it) => *it + HEAP_OFFSET,
335            Invalid(it) => *it,
336        }
337    }
338
339    fn map(&self, f: impl FnOnce(usize) -> usize) -> Address {
340        match self {
341            Stack(it) => Stack(f(*it)),
342            Heap(it) => Heap(f(*it)),
343            Invalid(it) => Invalid(f(*it)),
344        }
345    }
346
347    fn offset(&self, offset: usize) -> Address {
348        self.map(|it| it + offset)
349    }
350}
351
352#[derive(Clone, PartialEq, Eq, SalsaValue)]
353pub enum MirEvalError<'db> {
354    ConstEvalError(String, Box<ConstEvalError<'db>>),
355    LayoutError(LayoutError, StoredTy),
356    TargetDataLayoutNotAvailable(TargetLoadError),
357    /// Means that code had undefined behavior. We don't try to actively detect UB, but if it was detected
358    /// then use this type of error.
359    UndefinedBehavior(String),
360    Panic(String),
361    // FIXME: This should be folded into ConstEvalError?
362    MirLowerError(FunctionId, MirLowerError<'db>),
363    MirLowerErrorForClosure(InternedClosureId<'db>, MirLowerError<'db>),
364    TypeIsUnsized(StoredTy, &'static str),
365    NotSupported(String),
366    InvalidConst,
367    InFunction(
368        Box<MirEvalError<'db>>,
369        Vec<(Either<FunctionId, InternedClosureId<'db>>, MirSpan, InferBodyId<'db>)>,
370    ),
371    ExecutionLimitExceeded,
372    StackOverflow,
373    /// FIXME: Fold this into InternalError
374    InvalidVTableId(usize),
375    /// ?
376    CoerceUnsizedError(StoredTy),
377    /// These should not occur, usually indicates a bug in mir lowering.
378    InternalError(Box<str>),
379}
380
381impl MirEvalError<'_> {
382    pub fn pretty_print(
383        &self,
384        f: &mut String,
385        db: &dyn HirDatabase,
386        span_formatter: impl Fn(FileId, TextRange) -> String,
387        display_target: DisplayTarget,
388    ) -> std::result::Result<(), std::fmt::Error> {
389        writeln!(f, "Mir eval error:")?;
390        let mut err = self;
391        while let MirEvalError::InFunction(e, stack) = err {
392            err = e;
393            for (func, span, def) in stack.iter().take(30).rev() {
394                match func {
395                    Either::Left(func) => {
396                        let function_name = FunctionSignature::of(db, *func);
397                        writeln!(
398                            f,
399                            "In function {} ({:?})",
400                            function_name.name.display(db, display_target.edition),
401                            func
402                        )?;
403                    }
404                    Either::Right(closure) => {
405                        writeln!(f, "In {closure:?}")?;
406                    }
407                }
408                let (source_map, self_param_syntax) = match *def {
409                    InferBodyId::DefWithBodyId(def) => {
410                        let body = &Body::with_source_map(db, def).1;
411                        (&**body, body.self_param_syntax())
412                    }
413                    InferBodyId::AnonConstId(def) => {
414                        let store = ExpressionStore::with_source_map(db, def.loc(db).owner).1;
415                        (store, None)
416                    }
417                };
418                let span: InFile<SyntaxNodePtr> = match *span {
419                    MirSpan::ExprId(e) => match source_map.expr_syntax(e) {
420                        Ok(s) => s.map(|it| it.into()),
421                        Err(_) => continue,
422                    },
423                    MirSpan::PatId(p) => match source_map.pat_syntax(p) {
424                        Ok(s) => s.map(|it| it.syntax_node_ptr()),
425                        Err(_) => continue,
426                    },
427                    MirSpan::BindingId(b) => {
428                        match source_map
429                            .patterns_for_binding(b)
430                            .iter()
431                            .find_map(|p| source_map.pat_syntax(*p).ok())
432                        {
433                            Some(s) => s.map(|it| it.syntax_node_ptr()),
434                            None => continue,
435                        }
436                    }
437                    MirSpan::SelfParam => match self_param_syntax {
438                        Some(s) => s.map(|it| it.syntax_node_ptr()),
439                        None => continue,
440                    },
441                    MirSpan::Unknown => continue,
442                };
443                let file_id = span.file_id.original_file(db);
444                let text_range = span.value.text_range();
445                writeln!(f, "{}", span_formatter(file_id.file_id(db), text_range))?;
446            }
447        }
448        match err {
449            MirEvalError::InFunction(..) => unreachable!(),
450            MirEvalError::LayoutError(err, ty) => {
451                write!(
452                    f,
453                    "Layout for type `{}` is not available due {err:?}",
454                    ty.as_ref()
455                        .display(db, display_target)
456                        .with_closure_style(ClosureStyle::ClosureWithId)
457                )?;
458            }
459            MirEvalError::MirLowerError(func, err) => {
460                let function_name = FunctionSignature::of(db, *func);
461                let self_ = match func.lookup(db).container {
462                    ItemContainerId::ImplId(impl_id) => Some({
463                        db.impl_self_ty(impl_id)
464                            .instantiate_identity()
465                            .skip_norm_wip()
466                            .display(db, display_target)
467                            .to_string()
468                    }),
469                    ItemContainerId::TraitId(it) => Some(
470                        TraitSignature::of(db, it)
471                            .name
472                            .display(db, display_target.edition)
473                            .to_string(),
474                    ),
475                    _ => None,
476                };
477                writeln!(
478                    f,
479                    "MIR lowering for function `{}{}{}` ({:?}) failed due:",
480                    self_.as_deref().unwrap_or_default(),
481                    if self_.is_some() { "::" } else { "" },
482                    function_name.name.display(db, display_target.edition),
483                    func
484                )?;
485                err.pretty_print(f, db, span_formatter, display_target)?;
486            }
487            MirEvalError::ConstEvalError(name, err) => {
488                MirLowerError::ConstEvalError((**name).into(), err.clone()).pretty_print(
489                    f,
490                    db,
491                    span_formatter,
492                    display_target,
493                )?;
494            }
495            MirEvalError::UndefinedBehavior(_)
496            | MirEvalError::TargetDataLayoutNotAvailable(_)
497            | MirEvalError::Panic(_)
498            | MirEvalError::MirLowerErrorForClosure(_, _)
499            | MirEvalError::TypeIsUnsized(_, _)
500            | MirEvalError::NotSupported(_)
501            | MirEvalError::InvalidConst
502            | MirEvalError::ExecutionLimitExceeded
503            | MirEvalError::StackOverflow
504            | MirEvalError::CoerceUnsizedError(_)
505            | MirEvalError::InternalError(_)
506            | MirEvalError::InvalidVTableId(_) => writeln!(f, "{err:?}")?,
507        }
508        Ok(())
509    }
510
511    pub fn is_panic(&self) -> Option<&str> {
512        let mut err = self;
513        while let MirEvalError::InFunction(e, _) = err {
514            err = e;
515        }
516        match err {
517            MirEvalError::Panic(msg) => Some(msg),
518            _ => None,
519        }
520    }
521}
522
523impl std::fmt::Debug for MirEvalError<'_> {
524    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
525        match self {
526            Self::ConstEvalError(arg0, arg1) => {
527                f.debug_tuple("ConstEvalError").field(arg0).field(arg1).finish()
528            }
529            Self::LayoutError(arg0, arg1) => {
530                f.debug_tuple("LayoutError").field(arg0).field(arg1).finish()
531            }
532            Self::UndefinedBehavior(arg0) => {
533                f.debug_tuple("UndefinedBehavior").field(arg0).finish()
534            }
535            Self::Panic(msg) => write!(f, "Panic with message:\n{msg:?}"),
536            Self::TargetDataLayoutNotAvailable(arg0) => {
537                f.debug_tuple("TargetDataLayoutNotAvailable").field(arg0).finish()
538            }
539            Self::TypeIsUnsized(ty, it) => write!(f, "{ty:?} is unsized. {it} should be sized."),
540            Self::ExecutionLimitExceeded => write!(f, "execution limit exceeded"),
541            Self::StackOverflow => write!(f, "stack overflow"),
542            Self::MirLowerError(arg0, arg1) => {
543                f.debug_tuple("MirLowerError").field(arg0).field(arg1).finish()
544            }
545            Self::MirLowerErrorForClosure(arg0, arg1) => {
546                f.debug_tuple("MirLowerError").field(arg0).field(arg1).finish()
547            }
548            Self::CoerceUnsizedError(arg0) => {
549                f.debug_tuple("CoerceUnsizedError").field(arg0).finish()
550            }
551            Self::InternalError(arg0) => f.debug_tuple("InternalError").field(arg0).finish(),
552            Self::InvalidVTableId(arg0) => f.debug_tuple("InvalidVTableId").field(arg0).finish(),
553            Self::NotSupported(arg0) => f.debug_tuple("NotSupported").field(arg0).finish(),
554            Self::InvalidConst => f.write_str("InvalidConst"),
555            Self::InFunction(e, stack) => {
556                f.debug_struct("WithStack").field("error", e).field("stack", &stack).finish()
557            }
558        }
559    }
560}
561
562type Result<'db, T> = std::result::Result<T, MirEvalError<'db>>;
563
564#[derive(Debug, Default)]
565struct DropFlags<'db> {
566    need_drop: FxHashSet<PlaceRef<'db>>,
567}
568
569impl<'db> DropFlags<'db> {
570    fn add_place(&mut self, p: PlaceRef<'db>) {
571        if p.iterate_over_parents().any(|it| self.need_drop.contains(&it)) {
572            return;
573        }
574        self.need_drop.retain(|it| !p.is_parent(*it));
575        self.need_drop.insert(p);
576    }
577
578    fn remove_place(&mut self, p: PlaceRef<'db>) -> bool {
579        // FIXME: replace parents with parts
580        if let Some(parent) = p.iterate_over_parents().find(|it| self.need_drop.contains(it)) {
581            self.need_drop.remove(&parent);
582            return true;
583        }
584        self.need_drop.remove(&p)
585    }
586
587    fn clear(&mut self) {
588        self.need_drop.clear();
589    }
590}
591
592#[derive(Debug)]
593struct Locals<'a, 'db> {
594    ptr: ArenaMap<LocalId, Interval>,
595    body: &'db MirBody<'db>,
596    drop_flags: DropFlags<'a>,
597}
598
599pub struct MirOutput {
600    stdout: Vec<u8>,
601    stderr: Vec<u8>,
602}
603
604impl MirOutput {
605    pub fn stdout(&self) -> Cow<'_, str> {
606        String::from_utf8_lossy(&self.stdout)
607    }
608    pub fn stderr(&self) -> Cow<'_, str> {
609        String::from_utf8_lossy(&self.stderr)
610    }
611}
612
613pub fn interpret_mir<'db>(
614    db: &'db dyn HirDatabase,
615    body: &'db MirBody<'db>,
616    // FIXME: This is workaround. Ideally, const generics should have a separate body (issue #7434), but now
617    // they share their body with their parent, so in MIR lowering we have locals of the parent body, which
618    // might have placeholders. With this argument, we (wrongly) assume that every placeholder type has
619    // a zero size, hoping that they are all outside of our current body. Even without a fix for #7434, we can
620    // (and probably should) do better here, for example by excluding bindings outside of the target expression.
621    assert_placeholder_ty_is_unused: bool,
622    trait_env: Option<ParamEnvAndCrate<'db>>,
623) -> Result<'db, (Result<'db, Allocation<'db>>, MirOutput)> {
624    let ty = body.locals[return_slot()].ty.as_ref();
625    let mut evaluator = Evaluator::new(db, body.owner, assert_placeholder_ty_is_unused, trait_env)?;
626    let it: Result<'db, Allocation<'db>> = (|| {
627        if evaluator.ptr_size() != size_of::<usize>() {
628            not_supported!("targets with different pointer size from host");
629        }
630        let interval = evaluator.interpret_mir(body, None.into_iter())?;
631        let bytes = interval.get(&evaluator)?;
632        let mut memory_map = evaluator.create_memory_map(
633            bytes,
634            ty,
635            &Locals { ptr: ArenaMap::new(), body, drop_flags: DropFlags::default() },
636        )?;
637        let bytes = Box::from(bytes);
638        let memory_map = if memory_map.memory.is_empty() && evaluator.vtable_map.is_empty() {
639            MemoryMap::Empty
640        } else {
641            memory_map.vtable = mem::take(&mut evaluator.vtable_map);
642            memory_map.vtable.shrink_to_fit();
643            MemoryMap::Complex(Box::new(memory_map))
644        };
645        Ok(Allocation::new(AllocationData { ty, memory: bytes, memory_map }))
646    })();
647    Ok((it, MirOutput { stdout: evaluator.stdout, stderr: evaluator.stderr }))
648}
649
650#[cfg(test)]
651const EXECUTION_LIMIT: usize = 100_000;
652#[cfg(not(test))]
653const EXECUTION_LIMIT: usize = 10_000_000;
654
655impl<'a, 'db> Evaluator<'a, 'db> {
656    pub fn new(
657        db: &'db dyn HirDatabase,
658        owner: InferBodyId<'db>,
659        assert_placeholder_ty_is_unused: bool,
660        trait_env: Option<ParamEnvAndCrate<'db>>,
661    ) -> Result<'db, Evaluator<'a, 'db>> {
662        let module = owner.module(db);
663        let crate_id = module.krate(db);
664        let target_data_layout = match db.target_data_layout(crate_id) {
665            Ok(target_data_layout) => target_data_layout,
666            Err(e) => return Err(MirEvalError::TargetDataLayoutNotAvailable(e)),
667        };
668        let cached_ptr_size = target_data_layout.pointer_size().bytes_usize();
669        let interner = DbInterner::new_with(db, crate_id);
670        let infcx = interner.infer_ctxt().build(TypingMode::PostAnalysis);
671        let lang_items = interner.lang_items();
672        Ok(Evaluator {
673            target_data_layout,
674            stack: vec![0],
675            heap: vec![0],
676            code_stack: vec![],
677            vtable_map: VTableMap::default(),
678            thread_local_storage: TlsData::default(),
679            static_locations: Default::default(),
680            db,
681            random_state: oorandom::Rand64::new(0),
682            param_env: trait_env.unwrap_or_else(|| ParamEnvAndCrate {
683                param_env: db.trait_environment(owner.generic_def(db)),
684                krate: crate_id,
685            }),
686            crate_id,
687            stdout: vec![],
688            stderr: vec![],
689            assert_placeholder_ty_is_unused,
690            stack_depth_limit: 100,
691            execution_limit: EXECUTION_LIMIT,
692            memory_limit: 1_000_000_000, // 2GB, 1GB for stack and 1GB for heap
693            layout_cache: RefCell::new(Default::default()),
694            projected_ty_cache: RefCell::new(Default::default()),
695            not_special_fn_cache: RefCell::new(Default::default()),
696            mir_or_dyn_index_cache: RefCell::new(Default::default()),
697            unused_locals_store: RefCell::new(Default::default()),
698            cached_ptr_size,
699            cached_fn_trait_func: lang_items.Fn_call,
700            cached_fn_mut_trait_func: lang_items.FnMut_call_mut,
701            cached_fn_once_trait_func: lang_items.FnOnce_call_once,
702            infcx,
703        })
704    }
705
706    #[inline]
707    fn interner(&self) -> DbInterner<'db> {
708        self.infcx.interner
709    }
710
711    #[inline]
712    fn lang_items(&self) -> &'db LangItems {
713        self.infcx.interner.lang_items()
714    }
715
716    fn place_addr(&self, p: &Place, locals: &Locals<'a, 'db>) -> Result<'db, Address> {
717        Ok(self.place_addr_and_ty_and_metadata(p, locals)?.0)
718    }
719
720    fn place_interval(&self, p: &Place, locals: &Locals<'a, 'db>) -> Result<'db, Interval> {
721        let place_addr_and_ty = self.place_addr_and_ty_and_metadata(p, locals)?;
722        Ok(Interval {
723            addr: place_addr_and_ty.0,
724            size: self.size_of_sized(
725                place_addr_and_ty.1,
726                locals,
727                "Type of place that we need its interval",
728            )?,
729        })
730    }
731
732    fn ptr_size(&self) -> usize {
733        self.cached_ptr_size
734    }
735
736    fn caller_location_fields(&self, owner: InferBodyId<'db>, span: MirSpan) -> (String, u32, u32) {
737        let Some((file_id, text_range)) = self.resolve_mir_span(owner, span) else {
738            return (String::new(), 0, 0);
739        };
740        let source_root = self.db.file_source_root(file_id).source_root_id(self.db);
741        let source_root = self.db.source_root(source_root).source_root(self.db);
742        let path = source_root.path_for_file(&file_id).map(|path| path.to_string());
743        let (line, col) = self.db.line_column(file_id, text_range.start()).unwrap_or((0, 0));
744        (path.unwrap_or_default(), line + 1, col + 1)
745    }
746
747    fn resolve_mir_span(
748        &self,
749        owner: InferBodyId<'db>,
750        span: MirSpan,
751    ) -> Option<(FileId, TextRange)> {
752        let (source_map, self_param_syntax) = match owner {
753            InferBodyId::DefWithBodyId(def) => {
754                let body = &Body::with_source_map(self.db, def).1;
755                (&**body, body.self_param_syntax())
756            }
757            InferBodyId::AnonConstId(def) => {
758                (ExpressionStore::with_source_map(self.db, def.loc(self.db).owner).1, None)
759            }
760        };
761        let span: InFile<SyntaxNodePtr> = match span {
762            MirSpan::ExprId(e) => source_map.expr_syntax(e).ok()?.map(|it| it.into()),
763            MirSpan::PatId(p) => source_map.pat_syntax(p).ok()?.map(|it| it.syntax_node_ptr()),
764            MirSpan::BindingId(b) => source_map
765                .patterns_for_binding(b)
766                .iter()
767                .find_map(|p| source_map.pat_syntax(*p).ok())?
768                .map(|it| it.syntax_node_ptr()),
769            MirSpan::SelfParam => self_param_syntax?.map(|it| it.syntax_node_ptr()),
770            MirSpan::Unknown => return None,
771        };
772        let file_id = span.file_id.original_file(self.db);
773        Some((file_id.file_id(self.db), span.value.text_range()))
774    }
775
776    fn projected_ty(&self, ty: PlaceTy<'db>, proj: PlaceElem) -> PlaceTy<'db> {
777        let pair = (ty, proj);
778        if let Some(r) = self.projected_ty_cache.borrow().get(&pair) {
779            return *r;
780        }
781        let (ty, proj) = pair;
782        let r = ty.projection_ty(&self.infcx, &proj, self.param_env.param_env);
783        self.projected_ty_cache.borrow_mut().insert((ty, proj), r);
784        r
785    }
786
787    fn place_addr_and_ty_and_metadata<'b>(
788        &'b self,
789        p: &Place,
790        locals: &'b Locals<'a, 'db>,
791    ) -> Result<'db, (Address, Ty<'db>, Option<IntervalOrOwned>)> {
792        let mut addr = locals.ptr[p.local].addr;
793        let mut ty = PlaceTy::from_ty(locals.body.locals[p.local].ty.as_ref());
794        let mut metadata: Option<IntervalOrOwned> = None; // locals are always sized
795        for proj in p.projection.lookup() {
796            let prev_ty = ty;
797            ty = self.projected_ty(ty, *proj);
798            match proj {
799                ProjectionElem::Deref => {
800                    metadata = if self.size_align_of(ty.ty, locals)?.is_none() {
801                        Some(
802                            Interval { addr: addr.offset(self.ptr_size()), size: self.ptr_size() }
803                                .into(),
804                        )
805                    } else {
806                        None
807                    };
808                    let it = from_bytes!(usize, self.read_memory(addr, self.ptr_size())?);
809                    addr = Address::from_usize(it);
810                }
811                ProjectionElem::Index(op) => {
812                    let offset = from_bytes!(
813                        usize,
814                        self.read_memory(locals.ptr[*op].addr, self.ptr_size())?
815                    );
816                    metadata = None; // Result of index is always sized
817                    let ty_size =
818                        self.size_of_sized(ty.ty, locals, "array inner type should be sized")?;
819                    addr = addr.offset(ty_size * offset);
820                }
821                &ProjectionElem::ConstantIndex { from_end, offset } => {
822                    let offset = if from_end {
823                        let len = match prev_ty.ty.kind() {
824                            TyKind::Array(_, c) => match try_const_usize(self.db, c) {
825                                Some(it) => it as u64,
826                                None => {
827                                    not_supported!("indexing array with unknown const from end")
828                                }
829                            },
830                            TyKind::Slice(_) => match metadata {
831                                Some(it) => from_bytes!(u64, it.get(self)?),
832                                None => not_supported!("slice place without metadata"),
833                            },
834                            _ => not_supported!("bad type for const index"),
835                        };
836                        (len - offset - 1) as usize
837                    } else {
838                        offset as usize
839                    };
840                    metadata = None; // Result of index is always sized
841                    let ty_size =
842                        self.size_of_sized(ty.ty, locals, "array inner type should be sized")?;
843                    addr = addr.offset(ty_size * offset);
844                }
845                &ProjectionElem::Subslice { from, to } => {
846                    let inner_ty = match ty.ty.kind() {
847                        TyKind::Array(inner, _) | TyKind::Slice(inner) => inner,
848                        _ => Ty::new_error(self.interner(), ErrorGuaranteed),
849                    };
850                    metadata = match metadata {
851                        Some(it) => {
852                            let prev_len = from_bytes!(u64, it.get(self)?);
853                            Some(IntervalOrOwned::Owned(
854                                (prev_len - from - to).to_le_bytes().to_vec(),
855                            ))
856                        }
857                        None => None,
858                    };
859                    let ty_size =
860                        self.size_of_sized(inner_ty, locals, "array inner type should be sized")?;
861                    addr = addr.offset(ty_size * (from as usize));
862                }
863                ProjectionElem::Field(f) => {
864                    let layout = self.layout(prev_ty.ty)?;
865                    let variant_layout = match &layout.variants {
866                        Variants::Single { .. } | Variants::Empty => &layout,
867                        Variants::Multiple { variants, .. } => {
868                            &variants[match prev_ty.variant_id {
869                                Some(hir_def::VariantId::EnumVariantId(it)) => {
870                                    RustcEnumVariantIdx(it.index(self.db))
871                                }
872                                _ => {
873                                    return Err(MirEvalError::InternalError(
874                                        "mismatched layout".into(),
875                                    ));
876                                }
877                            }]
878                        }
879                    };
880                    let offset = variant_layout.fields.offset(f.0 as usize).bytes_usize();
881                    addr = addr.offset(offset);
882                    // Unsized field metadata is equal to the metadata of the struct
883                    if self.size_align_of(ty.ty, locals)?.is_some() {
884                        metadata = None;
885                    }
886                }
887                ProjectionElem::Downcast(_) => {
888                    // no runtime effect
889                }
890            }
891        }
892        Ok((addr, ty.ty, metadata))
893    }
894
895    fn layout(&self, ty: Ty<'db>) -> Result<'db, Arc<Layout>> {
896        if let Some(x) = self.layout_cache.borrow().get(&ty) {
897            return Ok(x.clone());
898        }
899        let r = self
900            .db
901            .layout_of_ty(ty.store(), self.param_env.store())
902            .map_err(|e| MirEvalError::LayoutError(e, ty.store()))?;
903        self.layout_cache.borrow_mut().insert(ty, r.clone());
904        Ok(r)
905    }
906
907    fn layout_adt(&self, adt: AdtId, subst: GenericArgs<'db>) -> Result<'db, Arc<Layout>> {
908        self.layout(Ty::new_adt(self.interner(), adt, subst))
909    }
910
911    fn place_ty<'b>(&'b self, p: &Place, locals: &'b Locals<'a, 'db>) -> 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    #[allow(clippy::double_parens)]
2096    fn allocate_const_in_heap(
2097        &mut self,
2098        locals: &Locals<'a, 'db>,
2099        konst: Const<'db>,
2100    ) -> Result<'db, Interval> {
2101        match konst.kind() {
2102            ConstKind::Value(value) => self.allocate_valtree_in_heap(value.ty, value.value),
2103            ConstKind::Unevaluated(UnevaluatedConst { def: const_id, args: subst }) => {
2104                let mut id = const_id.0;
2105                let mut subst = subst;
2106                if let GeneralConstId::ConstId(c) = id {
2107                    let (c, s) = lookup_impl_const(&self.infcx, self.param_env.param_env, c, subst);
2108                    id = GeneralConstId::ConstId(c);
2109                    subst = s;
2110                }
2111                let allocation = match id {
2112                    GeneralConstId::ConstId(const_id) => {
2113                        self.db.const_eval(const_id, subst, Some(self.param_env)).map_err(|e| {
2114                            let name = id.name(self.db);
2115                            MirEvalError::ConstEvalError(name, Box::new(e))
2116                        })?
2117                    }
2118                    GeneralConstId::StaticId(static_id) => {
2119                        self.db.const_eval_static(static_id).map_err(|e| {
2120                            let name = id.name(self.db);
2121                            MirEvalError::ConstEvalError(name, Box::new(e))
2122                        })?
2123                    }
2124                    GeneralConstId::AnonConstId(anon_const_id) => self
2125                        .db
2126                        .anon_const_eval(anon_const_id, subst, Some(self.param_env))
2127                        .map_err(|e| {
2128                            let name = id.name(self.db);
2129                            MirEvalError::ConstEvalError(name, Box::new(e))
2130                        })?,
2131                };
2132                self.allocate_allocation_in_heap(locals, allocation)
2133            }
2134            _ => not_supported!("evaluating unknown const"),
2135        }
2136    }
2137
2138    fn allocate_allocation_in_heap(
2139        &mut self,
2140        locals: &Locals<'a, 'db>,
2141        allocation: Allocation<'db>,
2142    ) -> Result<'db, Interval> {
2143        let AllocationData { ty, memory: ref v, ref memory_map } = *allocation;
2144        let patch_map = memory_map.transform_addresses(|b, align| {
2145            let addr = self.heap_allocate(b.len(), align)?;
2146            self.write_memory(addr, b)?;
2147            Ok(addr.to_usize())
2148        })?;
2149        let (size, align) = self.size_align_of(allocation.ty, locals)?.unwrap_or((v.len(), 1));
2150        let v: Cow<'_, [u8]> = if size != v.len() {
2151            // Handle self enum
2152            if size == 16 && v.len() < 16 {
2153                Cow::Owned(pad16(v, IsSigned::No).to_vec())
2154            } else if size < 16 && v.len() == 16 {
2155                Cow::Borrowed(&v[0..size])
2156            } else {
2157                return Err(MirEvalError::InvalidConst);
2158            }
2159        } else {
2160            Cow::Borrowed(v)
2161        };
2162        let addr = self.heap_allocate(size, align)?;
2163        self.write_memory(addr, &v)?;
2164        self.patch_addresses(
2165            &patch_map,
2166            |bytes| match memory_map {
2167                MemoryMap::Empty | MemoryMap::Simple(_) => {
2168                    Err(MirEvalError::InvalidVTableId(from_bytes!(usize, bytes)))
2169                }
2170                MemoryMap::Complex(cm) => cm.vtable.ty_of_bytes(bytes),
2171            },
2172            addr,
2173            ty,
2174            locals,
2175        )?;
2176        Ok(Interval::new(addr, size))
2177    }
2178
2179    fn eval_place(&mut self, p: &Place, locals: &Locals<'a, 'db>) -> Result<'db, Interval> {
2180        let addr = self.place_addr(p, locals)?;
2181        Ok(Interval::new(
2182            addr,
2183            self.size_of_sized(self.place_ty(p, locals)?, locals, "type of this place")?,
2184        ))
2185    }
2186
2187    fn read_memory(&self, addr: Address, size: usize) -> Result<'db, &[u8]> {
2188        if size == 0 {
2189            return Ok(&[]);
2190        }
2191        let (mem, pos) = match addr {
2192            Stack(it) => (&self.stack, it),
2193            Heap(it) => (&self.heap, it),
2194            Invalid(it) => {
2195                return Err(MirEvalError::UndefinedBehavior(format!(
2196                    "read invalid memory address {it} with size {size}"
2197                )));
2198            }
2199        };
2200        mem.get(pos..pos + size)
2201            .ok_or_else(|| MirEvalError::UndefinedBehavior("out of bound memory read".to_owned()))
2202    }
2203
2204    fn write_memory_using_ref(&mut self, addr: Address, size: usize) -> Result<'db, &mut [u8]> {
2205        let (mem, pos) = match addr {
2206            Stack(it) => (&mut self.stack, it),
2207            Heap(it) => (&mut self.heap, it),
2208            Invalid(it) => {
2209                return Err(MirEvalError::UndefinedBehavior(format!(
2210                    "write invalid memory address {it} with size {size}"
2211                )));
2212            }
2213        };
2214        mem.get_mut(pos..pos + size)
2215            .ok_or_else(|| MirEvalError::UndefinedBehavior("out of bound memory write".to_owned()))
2216    }
2217
2218    fn write_memory(&mut self, addr: Address, r: &[u8]) -> Result<'db, ()> {
2219        if r.is_empty() {
2220            return Ok(());
2221        }
2222        self.write_memory_using_ref(addr, r.len())?.copy_from_slice(r);
2223        Ok(())
2224    }
2225
2226    fn copy_from_interval_or_owned(
2227        &mut self,
2228        addr: Address,
2229        r: IntervalOrOwned,
2230    ) -> Result<'db, ()> {
2231        match r {
2232            IntervalOrOwned::Borrowed(r) => self.copy_from_interval(addr, r),
2233            IntervalOrOwned::Owned(r) => self.write_memory(addr, &r),
2234        }
2235    }
2236
2237    fn copy_from_interval(&mut self, addr: Address, r: Interval) -> Result<'db, ()> {
2238        if r.size == 0 {
2239            return Ok(());
2240        }
2241
2242        let oob = || MirEvalError::UndefinedBehavior("out of bounds memory write".to_owned());
2243
2244        match (addr, r.addr) {
2245            (Stack(dst), Stack(src)) => {
2246                if self.stack.len() < src + r.size || self.stack.len() < dst + r.size {
2247                    return Err(oob());
2248                }
2249                self.stack.copy_within(src..src + r.size, dst)
2250            }
2251            (Heap(dst), Heap(src)) => {
2252                if self.stack.len() < src + r.size || self.stack.len() < dst + r.size {
2253                    return Err(oob());
2254                }
2255                self.heap.copy_within(src..src + r.size, dst)
2256            }
2257            (Stack(dst), Heap(src)) => {
2258                self.stack
2259                    .get_mut(dst..dst + r.size)
2260                    .ok_or_else(oob)?
2261                    .copy_from_slice(self.heap.get(src..src + r.size).ok_or_else(oob)?);
2262            }
2263            (Heap(dst), Stack(src)) => {
2264                self.heap
2265                    .get_mut(dst..dst + r.size)
2266                    .ok_or_else(oob)?
2267                    .copy_from_slice(self.stack.get(src..src + r.size).ok_or_else(oob)?);
2268            }
2269            _ => {
2270                return Err(MirEvalError::UndefinedBehavior(format!(
2271                    "invalid memory write at address {addr:?}"
2272                )));
2273            }
2274        }
2275
2276        Ok(())
2277    }
2278
2279    fn size_align_of(
2280        &self,
2281        ty: Ty<'db>,
2282        locals: &Locals<'a, 'db>,
2283    ) -> Result<'db, Option<(usize, usize)>> {
2284        if let Some(layout) = self.layout_cache.borrow().get(&ty) {
2285            return Ok(layout
2286                .is_sized()
2287                .then(|| (layout.size.bytes_usize(), layout.align.bytes() as usize)));
2288        }
2289        if let Some(f) = locals.body.owner.as_variant()
2290            && let Some((AdtId::EnumId(e), _)) = ty.as_adt()
2291            && f.lookup(self.db).parent == e
2292        {
2293            // Computing the exact size of enums require resolving the enum discriminants. In order to prevent loops (and
2294            // infinite sized type errors) we use a dummy size
2295            return Ok(Some((16, 16)));
2296        }
2297        let layout = self.layout(ty);
2298        if self.assert_placeholder_ty_is_unused
2299            && matches!(layout, Err(MirEvalError::LayoutError(LayoutError::HasPlaceholder, _)))
2300        {
2301            return Ok(Some((0, 1)));
2302        }
2303        let layout = layout?;
2304        Ok(layout.is_sized().then(|| (layout.size.bytes_usize(), layout.align.bytes() as usize)))
2305    }
2306
2307    /// A version of `self.size_of` which returns error if the type is unsized. `what` argument should
2308    /// be something that complete this: `error: type {ty} was unsized. {what} should be sized`
2309    fn size_of_sized(
2310        &self,
2311        ty: Ty<'db>,
2312        locals: &Locals<'a, 'db>,
2313        what: &'static str,
2314    ) -> Result<'db, usize> {
2315        match self.size_align_of(ty, locals)? {
2316            Some(it) => Ok(it.0),
2317            None => Err(MirEvalError::TypeIsUnsized(ty.store(), what)),
2318        }
2319    }
2320
2321    /// A version of `self.size_align_of` which returns error if the type is unsized. `what` argument should
2322    /// be something that complete this: `error: type {ty} was unsized. {what} should be sized`
2323    fn size_align_of_sized(
2324        &self,
2325        ty: Ty<'db>,
2326        locals: &Locals<'a, 'db>,
2327        what: &'static str,
2328    ) -> Result<'db, (usize, usize)> {
2329        match self.size_align_of(ty, locals)? {
2330            Some(it) => Ok(it),
2331            None => Err(MirEvalError::TypeIsUnsized(ty.store(), what)),
2332        }
2333    }
2334
2335    fn heap_allocate(&mut self, size: usize, align: usize) -> Result<'db, Address> {
2336        if !align.is_power_of_two() || align > 10000 {
2337            return Err(MirEvalError::UndefinedBehavior(format!("Alignment {align} is invalid")));
2338        }
2339        while !self.heap.len().is_multiple_of(align) {
2340            self.heap.push(0);
2341        }
2342        if size.checked_add(self.heap.len()).is_none_or(|x| x > self.memory_limit) {
2343            return Err(MirEvalError::Panic(format!("Memory allocation of {size} bytes failed")));
2344        }
2345        let pos = self.heap.len();
2346        self.heap.extend(std::iter::repeat_n(0, size));
2347        Ok(Address::Heap(pos))
2348    }
2349
2350    fn detect_fn_trait(&self, def: FunctionId) -> Option<FnTrait> {
2351        let def = Some(def);
2352        if def == self.cached_fn_trait_func {
2353            Some(FnTrait::Fn)
2354        } else if def == self.cached_fn_mut_trait_func {
2355            Some(FnTrait::FnMut)
2356        } else if def == self.cached_fn_once_trait_func {
2357            Some(FnTrait::FnOnce)
2358        } else {
2359            None
2360        }
2361    }
2362
2363    fn create_memory_map(
2364        &self,
2365        bytes: &[u8],
2366        ty: Ty<'db>,
2367        locals: &Locals<'a, 'db>,
2368    ) -> Result<'db, ComplexMemoryMap<'db>> {
2369        fn rec<'a, 'db>(
2370            this: &Evaluator<'a, 'db>,
2371            bytes: &[u8],
2372            ty: Ty<'db>,
2373            locals: &Locals<'a, 'db>,
2374            mm: &mut ComplexMemoryMap<'db>,
2375            stack_depth_limit: usize,
2376        ) -> Result<'db, ()> {
2377            if stack_depth_limit.checked_sub(1).is_none() {
2378                return Err(MirEvalError::StackOverflow);
2379            }
2380            match ty.kind() {
2381                TyKind::Ref(_, t, _) => {
2382                    let size = this.size_align_of(t, locals)?;
2383                    match size {
2384                        Some((size, _)) => {
2385                            let addr_usize = from_bytes!(usize, bytes);
2386                            let bytes =
2387                                this.read_memory(Address::from_usize(addr_usize), size)?.to_vec();
2388                            mm.insert(addr_usize, bytes.clone().into());
2389                            rec(this, &bytes, t, locals, mm, stack_depth_limit - 1)?;
2390                        }
2391                        None => {
2392                            let mut check_inner = None;
2393                            let (addr, meta) = bytes.split_at(bytes.len() / 2);
2394                            let element_size = match t.kind() {
2395                                TyKind::Str => 1,
2396                                TyKind::Slice(t) => {
2397                                    check_inner = Some(t);
2398                                    this.size_of_sized(t, locals, "slice inner type")?
2399                                }
2400                                TyKind::Dynamic(..) => {
2401                                    let t = this.vtable_map.ty_of_bytes(meta)?;
2402                                    check_inner = Some(t);
2403                                    this.size_of_sized(t, locals, "dyn concrete type")?
2404                                }
2405                                _ => return Ok(()),
2406                            };
2407                            let count = match t.kind() {
2408                                TyKind::Dynamic(..) => 1,
2409                                _ => from_bytes!(usize, meta),
2410                            };
2411                            let size = element_size * count;
2412                            let addr = Address::from_bytes(addr)?;
2413                            let b = this.read_memory(addr, size)?;
2414                            mm.insert(addr.to_usize(), b.into());
2415                            if let Some(ty) = check_inner {
2416                                for i in 0..count {
2417                                    let offset = element_size * i;
2418                                    rec(
2419                                        this,
2420                                        &b[offset..offset + element_size],
2421                                        ty,
2422                                        locals,
2423                                        mm,
2424                                        stack_depth_limit - 1,
2425                                    )?;
2426                                }
2427                            }
2428                        }
2429                    }
2430                }
2431                TyKind::Array(inner, len) => {
2432                    let len = match try_const_usize(this.db, len) {
2433                        Some(it) => it as usize,
2434                        None => not_supported!("non evaluatable array len in patching addresses"),
2435                    };
2436                    let size = this.size_of_sized(inner, locals, "inner of array")?;
2437                    for i in 0..len {
2438                        let offset = i * size;
2439                        rec(
2440                            this,
2441                            &bytes[offset..offset + size],
2442                            inner,
2443                            locals,
2444                            mm,
2445                            stack_depth_limit - 1,
2446                        )?;
2447                    }
2448                }
2449                TyKind::Tuple(subst) => {
2450                    let layout = this.layout(ty)?;
2451                    for (id, ty) in subst.iter().enumerate() {
2452                        let offset = layout.fields.offset(id).bytes_usize();
2453                        let size = this.layout(ty)?.size.bytes_usize();
2454                        rec(
2455                            this,
2456                            &bytes[offset..offset + size],
2457                            ty,
2458                            locals,
2459                            mm,
2460                            stack_depth_limit - 1,
2461                        )?;
2462                    }
2463                }
2464                TyKind::Adt(adt, subst) => match adt.def_id() {
2465                    AdtId::StructId(s) => {
2466                        let data = s.fields(this.db);
2467                        let layout = this.layout(ty)?;
2468                        let field_types = this.db.field_types(s.into());
2469                        for (f, _) in data.fields().iter() {
2470                            let offset = layout
2471                                .fields
2472                                .offset(u32::from(f.into_raw()) as usize)
2473                                .bytes_usize();
2474                            let ty = field_types[f]
2475                                .ty()
2476                                .instantiate(this.interner(), subst)
2477                                .skip_norm_wip();
2478                            let size = this.layout(ty)?.size.bytes_usize();
2479                            rec(
2480                                this,
2481                                &bytes[offset..offset + size],
2482                                ty,
2483                                locals,
2484                                mm,
2485                                stack_depth_limit - 1,
2486                            )?;
2487                        }
2488                    }
2489                    AdtId::EnumId(e) => {
2490                        let layout = this.layout(ty)?;
2491                        if let Some((v, l)) = detect_variant_from_bytes(
2492                            &layout,
2493                            this.db,
2494                            this.target_data_layout,
2495                            bytes,
2496                            e,
2497                        ) {
2498                            let data = v.fields(this.db);
2499                            let field_types = this.db.field_types(v.into());
2500                            for (f, _) in data.fields().iter() {
2501                                let offset =
2502                                    l.fields.offset(u32::from(f.into_raw()) as usize).bytes_usize();
2503                                let ty = field_types[f]
2504                                    .ty()
2505                                    .instantiate(this.interner(), subst)
2506                                    .skip_norm_wip();
2507                                let size = this.layout(ty)?.size.bytes_usize();
2508                                rec(
2509                                    this,
2510                                    &bytes[offset..offset + size],
2511                                    ty,
2512                                    locals,
2513                                    mm,
2514                                    stack_depth_limit - 1,
2515                                )?;
2516                            }
2517                        }
2518                    }
2519                    AdtId::UnionId(_) => (),
2520                },
2521                TyKind::Alias(AliasTy { kind: AliasTyKind::Projection { .. }, .. }) => {
2522                    let mut ocx = ObligationCtxt::new(&this.infcx);
2523                    let ty = ocx
2524                        .structurally_normalize_ty(
2525                            &ObligationCause::dummy(),
2526                            this.param_env.param_env,
2527                            ty,
2528                        )
2529                        .map_err(|_| MirEvalError::NotSupported("couldn't normalize".to_owned()))?;
2530
2531                    rec(this, bytes, ty, locals, mm, stack_depth_limit - 1)?;
2532                }
2533                _ => (),
2534            }
2535            Ok(())
2536        }
2537        let mut mm = ComplexMemoryMap::default();
2538        rec(self, bytes, ty, locals, &mut mm, self.stack_depth_limit - 1)?;
2539        Ok(mm)
2540    }
2541
2542    fn patch_addresses(
2543        &mut self,
2544        patch_map: &FxHashMap<usize, usize>,
2545        ty_of_bytes: impl Fn(&[u8]) -> Result<'db, Ty<'db>> + Copy,
2546        addr: Address,
2547        ty: Ty<'db>,
2548        locals: &Locals<'a, 'db>,
2549    ) -> Result<'db, ()> {
2550        let layout = self.layout(ty)?;
2551        let my_size = self.size_of_sized(ty, locals, "value to patch address")?;
2552        use rustc_type_ir::TyKind;
2553        match ty.kind() {
2554            TyKind::Ref(_, t, _) => {
2555                let size = self.size_align_of(t, locals)?;
2556                match size {
2557                    Some(_) => {
2558                        let current = from_bytes!(usize, self.read_memory(addr, my_size)?);
2559                        let patched = match patch_map.get(&current) {
2560                            Some(it) => {
2561                                self.write_memory(addr, &it.to_le_bytes())?;
2562                                *it
2563                            }
2564                            None => current,
2565                        };
2566                        self.patch_addresses(
2567                            patch_map,
2568                            ty_of_bytes,
2569                            Address::from_usize(patched),
2570                            t,
2571                            locals,
2572                        )?;
2573                    }
2574                    None => {
2575                        let bytes = self.read_memory(addr, my_size)?;
2576                        let (current, metadata) = bytes.split_at(my_size / 2);
2577                        let metadata = metadata.to_vec();
2578                        let current = from_bytes!(usize, current);
2579                        let patched = match patch_map.get(&current) {
2580                            Some(it) => {
2581                                self.write_memory(addr, &it.to_le_bytes())?;
2582                                *it
2583                            }
2584                            None => current,
2585                        };
2586                        let patched = Address::from_usize(patched);
2587                        if let TyKind::Slice(inner) = t.kind() {
2588                            let len = from_bytes!(usize, metadata);
2589                            let size = self.size_of_sized(inner, locals, "slice item to patch")?;
2590                            for i in 0..len {
2591                                self.patch_addresses(
2592                                    patch_map,
2593                                    ty_of_bytes,
2594                                    patched.offset(i * size),
2595                                    inner,
2596                                    locals,
2597                                )?;
2598                            }
2599                        }
2600                    }
2601                }
2602            }
2603            TyKind::FnPtr(_, _) => {
2604                let ty = ty_of_bytes(self.read_memory(addr, my_size)?)?;
2605                let new_id = self.vtable_map.id(ty);
2606                self.write_memory(addr, &new_id.to_le_bytes())?;
2607            }
2608            TyKind::Adt(id, args) => match id.def_id() {
2609                AdtId::StructId(s) => {
2610                    for (i, (_, field)) in self.db.field_types(s.into()).iter().enumerate() {
2611                        let offset = layout.fields.offset(i).bytes_usize();
2612                        let ty = field.ty().instantiate(self.interner(), args).skip_norm_wip();
2613                        self.patch_addresses(
2614                            patch_map,
2615                            ty_of_bytes,
2616                            addr.offset(offset),
2617                            ty,
2618                            locals,
2619                        )?;
2620                    }
2621                }
2622                AdtId::UnionId(_) => (),
2623                AdtId::EnumId(e) => {
2624                    if let Some((ev, layout)) = detect_variant_from_bytes(
2625                        &layout,
2626                        self.db,
2627                        self.target_data_layout,
2628                        self.read_memory(addr, layout.size.bytes_usize())?,
2629                        e,
2630                    ) {
2631                        for (i, (_, field)) in self.db.field_types(ev.into()).iter().enumerate() {
2632                            let offset = layout.fields.offset(i).bytes_usize();
2633                            let ty = field.ty().instantiate(self.interner(), args).skip_norm_wip();
2634                            self.patch_addresses(
2635                                patch_map,
2636                                ty_of_bytes,
2637                                addr.offset(offset),
2638                                ty,
2639                                locals,
2640                            )?;
2641                        }
2642                    }
2643                }
2644            },
2645            TyKind::Tuple(tys) => {
2646                for (id, ty) in tys.iter().enumerate() {
2647                    let offset = layout.fields.offset(id).bytes_usize();
2648                    self.patch_addresses(patch_map, ty_of_bytes, addr.offset(offset), ty, locals)?;
2649                }
2650            }
2651            TyKind::Array(inner, len) => {
2652                let len = match consteval::try_const_usize(self.db, len) {
2653                    Some(it) => it as usize,
2654                    None => not_supported!("non evaluatable array len in patching addresses"),
2655                };
2656                let size = self.size_of_sized(inner, locals, "inner of array")?;
2657                for i in 0..len {
2658                    self.patch_addresses(
2659                        patch_map,
2660                        ty_of_bytes,
2661                        addr.offset(i * size),
2662                        inner,
2663                        locals,
2664                    )?;
2665                }
2666            }
2667            TyKind::Bool
2668            | TyKind::Char
2669            | TyKind::Int(_)
2670            | TyKind::Uint(_)
2671            | TyKind::Float(_)
2672            | TyKind::Slice(_)
2673            | TyKind::RawPtr(_, _)
2674            | TyKind::FnDef(_, _)
2675            | TyKind::Str
2676            | TyKind::Never
2677            | TyKind::Closure(_, _)
2678            | TyKind::Coroutine(_, _)
2679            | TyKind::CoroutineWitness(_, _)
2680            | TyKind::Foreign(_)
2681            | TyKind::Error(_)
2682            | TyKind::Placeholder(_)
2683            | TyKind::Dynamic(_, _)
2684            | TyKind::Alias(..)
2685            | TyKind::Bound(_, _)
2686            | TyKind::Infer(_)
2687            | TyKind::Pat(_, _)
2688            | TyKind::Param(_)
2689            | TyKind::UnsafeBinder(_)
2690            | TyKind::CoroutineClosure(_, _) => (),
2691        }
2692        Ok(())
2693    }
2694
2695    fn exec_fn_pointer(
2696        &mut self,
2697        bytes: Interval,
2698        destination: Interval,
2699        args: &[IntervalAndTy<'db>],
2700        locals: &Locals<'a, 'db>,
2701        target_bb: Option<BasicBlockId>,
2702        span: MirSpan,
2703    ) -> Result<'db, Option<StackFrame<'a, 'db>>> {
2704        let id = from_bytes!(usize, bytes.get(self)?);
2705        let next_ty = self.vtable_map.ty(id)?;
2706        use rustc_type_ir::TyKind;
2707        match next_ty.kind() {
2708            TyKind::FnDef(def, generic_args) => {
2709                self.exec_fn_def(def.0, generic_args, destination, args, locals, target_bb, span)
2710            }
2711            TyKind::Closure(id, generic_args) => self.exec_closure(
2712                id.0,
2713                bytes.slice(0..0),
2714                generic_args,
2715                destination,
2716                args,
2717                locals,
2718                span,
2719            ),
2720            _ => Err(MirEvalError::InternalError("function pointer to non function".into())),
2721        }
2722    }
2723
2724    fn exec_closure(
2725        &mut self,
2726        closure: InternedClosureId<'db>,
2727        closure_data: Interval,
2728        generic_args: GenericArgs<'db>,
2729        destination: Interval,
2730        args: &[IntervalAndTy<'db>],
2731        locals: &Locals<'a, 'db>,
2732        span: MirSpan,
2733    ) -> Result<'db, Option<StackFrame<'a, 'db>>> {
2734        let mir_body = self
2735            .db
2736            .monomorphized_mir_body_for_closure(
2737                closure,
2738                generic_args.store(),
2739                self.param_env.store(),
2740            )
2741            .map_err(|it| MirEvalError::MirLowerErrorForClosure(closure, it))?;
2742        let closure_data =
2743            if mir_body.locals[mir_body.param_locals[0]].ty.as_ref().as_reference().is_some() {
2744                closure_data.addr.to_bytes().to_vec()
2745            } else {
2746                closure_data.get(self)?.to_owned()
2747            };
2748        let arg_bytes = iter::once(Ok(closure_data))
2749            .chain(args.iter().map(|it| Ok(it.get(self)?.to_owned())))
2750            .collect::<Result<'db, Vec<_>>>()?;
2751        let interval = self
2752            .interpret_mir(mir_body, arg_bytes.into_iter().map(IntervalOrOwned::Owned))
2753            .map_err(|e| {
2754                MirEvalError::InFunction(
2755                    Box::new(e),
2756                    vec![(Either::Right(closure), span, locals.body.owner)],
2757                )
2758            })?;
2759        destination.write_from_interval(self, interval)?;
2760        Ok(None)
2761    }
2762
2763    fn exec_fn_def(
2764        &mut self,
2765        def: CallableDefId,
2766        generic_args: GenericArgs<'db>,
2767        destination: Interval,
2768        args: &[IntervalAndTy<'db>],
2769        locals: &Locals<'a, 'db>,
2770        target_bb: Option<BasicBlockId>,
2771        span: MirSpan,
2772    ) -> Result<'db, Option<StackFrame<'a, 'db>>> {
2773        match def {
2774            CallableDefId::FunctionId(def) => {
2775                if self.detect_fn_trait(def).is_some() {
2776                    return self.exec_fn_trait(
2777                        def,
2778                        args,
2779                        generic_args,
2780                        locals,
2781                        destination,
2782                        target_bb,
2783                        span,
2784                    );
2785                }
2786                self.exec_fn_with_args(
2787                    def,
2788                    args,
2789                    generic_args,
2790                    locals,
2791                    destination,
2792                    target_bb,
2793                    span,
2794                )
2795            }
2796            CallableDefId::StructId(id) => {
2797                let (size, variant_layout, tag) =
2798                    self.layout_of_variant(id.into(), generic_args, locals)?;
2799                let result = self.construct_with_layout(
2800                    size,
2801                    &variant_layout,
2802                    tag,
2803                    args.iter().map(|it| it.interval.into()),
2804                )?;
2805                destination.write_from_bytes(self, &result)?;
2806                Ok(None)
2807            }
2808            CallableDefId::EnumVariantId(id) => {
2809                let (size, variant_layout, tag) =
2810                    self.layout_of_variant(id.into(), generic_args, locals)?;
2811                let result = self.construct_with_layout(
2812                    size,
2813                    &variant_layout,
2814                    tag,
2815                    args.iter().map(|it| it.interval.into()),
2816                )?;
2817                destination.write_from_bytes(self, &result)?;
2818                Ok(None)
2819            }
2820        }
2821    }
2822
2823    fn get_mir_or_dyn_index(
2824        &self,
2825        def: FunctionId,
2826        generic_args: GenericArgs<'db>,
2827        locals: &Locals<'a, 'db>,
2828        span: MirSpan,
2829    ) -> Result<'db, MirOrDynIndex<'db>> {
2830        let pair = (def, generic_args);
2831        if let Some(r) = self.mir_or_dyn_index_cache.borrow().get(&pair) {
2832            return Ok(r.clone());
2833        }
2834        let (def, generic_args) = pair;
2835        let r = if let Some(self_ty_idx) =
2836            is_dyn_method(self.interner(), self.param_env.param_env, def, generic_args)
2837        {
2838            MirOrDynIndex::Dyn(self_ty_idx)
2839        } else {
2840            let (imp, generic_args) = self.db.lookup_impl_method(
2841                ParamEnvAndCrate { param_env: self.param_env.param_env, krate: self.crate_id },
2842                def,
2843                generic_args,
2844            );
2845            let Either::Left(imp) = imp else {
2846                not_supported!("evaluating builtin derive impls is not supported")
2847            };
2848
2849            let mir_body = self
2850                .db
2851                .monomorphized_mir_body(imp.into(), generic_args.store(), self.param_env.store())
2852                .map_err(|e| {
2853                    MirEvalError::InFunction(
2854                        Box::new(MirEvalError::MirLowerError(imp, e)),
2855                        vec![(Either::Left(imp), span, locals.body.owner)],
2856                    )
2857                })?;
2858            MirOrDynIndex::Mir(mir_body)
2859        };
2860        self.mir_or_dyn_index_cache.borrow_mut().insert((def, generic_args), r.clone());
2861        Ok(r)
2862    }
2863
2864    fn exec_fn_with_args(
2865        &mut self,
2866        mut def: FunctionId,
2867        args: &[IntervalAndTy<'db>],
2868        generic_args: GenericArgs<'db>,
2869        locals: &Locals<'a, 'db>,
2870        destination: Interval,
2871        target_bb: Option<BasicBlockId>,
2872        span: MirSpan,
2873    ) -> Result<'db, Option<StackFrame<'a, 'db>>> {
2874        if self.detect_and_exec_special_function(
2875            def,
2876            args,
2877            generic_args,
2878            locals,
2879            destination,
2880            span,
2881        )? {
2882            return Ok(None);
2883        }
2884        if let Some(redirect_def) = self.detect_and_redirect_special_function(def)? {
2885            def = redirect_def;
2886        }
2887        let arg_bytes = args.iter().map(|it| IntervalOrOwned::Borrowed(it.interval));
2888        match self.get_mir_or_dyn_index(def, generic_args, locals, span)? {
2889            MirOrDynIndex::Dyn(self_ty_idx) => {
2890                // In the layout of current possible receiver, which at the moment of writing this code is one of
2891                // `&T`, `&mut T`, `Box<T>`, `Rc<T>`, `Arc<T>`, and `Pin<P>` where `P` is one of possible receivers,
2892                // the vtable is exactly in the `[ptr_size..2*ptr_size]` bytes. So we can use it without branching on
2893                // the type.
2894                let first_arg = arg_bytes.clone().next().unwrap();
2895                let first_arg = first_arg.get(self)?;
2896                let ty = self
2897                    .vtable_map
2898                    .ty_of_bytes(&first_arg[self.ptr_size()..self.ptr_size() * 2])?;
2899                let mut args_for_target = args.to_vec();
2900                args_for_target[0] = IntervalAndTy {
2901                    interval: args_for_target[0].interval.slice(0..self.ptr_size()),
2902                    ty,
2903                };
2904                let generics_for_target = GenericArgs::new_from_iter(
2905                    self.interner(),
2906                    generic_args
2907                        .iter()
2908                        .enumerate()
2909                        .map(|(i, it)| if i == self_ty_idx { ty.into() } else { it }),
2910                );
2911                self.exec_fn_with_args(
2912                    def,
2913                    &args_for_target,
2914                    generics_for_target,
2915                    locals,
2916                    destination,
2917                    target_bb,
2918                    span,
2919                )
2920            }
2921            MirOrDynIndex::Mir(body) => self.exec_looked_up_function(
2922                body,
2923                locals,
2924                def,
2925                arg_bytes,
2926                span,
2927                destination,
2928                target_bb,
2929            ),
2930        }
2931    }
2932
2933    fn exec_looked_up_function(
2934        &mut self,
2935        mir_body: &'db MirBody<'db>,
2936        locals: &Locals<'a, 'db>,
2937        def: FunctionId,
2938        arg_bytes: impl Iterator<Item = IntervalOrOwned>,
2939        span: MirSpan,
2940        destination: Interval,
2941        target_bb: Option<BasicBlockId>,
2942    ) -> Result<'db, Option<StackFrame<'a, 'db>>> {
2943        if let Some(target_bb) = target_bb {
2944            let (mut locals, prev_stack_ptr) =
2945                self.create_locals_for_body(mir_body, Some(destination))?;
2946            self.fill_locals_for_body(mir_body, &mut locals, arg_bytes.into_iter())?;
2947            let span = (span, locals.body.owner);
2948            Ok(Some(StackFrame { locals, destination: Some(target_bb), prev_stack_ptr, span }))
2949        } else {
2950            let result = self.interpret_mir(mir_body, arg_bytes).map_err(|e| {
2951                MirEvalError::InFunction(
2952                    Box::new(e),
2953                    vec![(Either::Left(def), span, locals.body.owner)],
2954                )
2955            })?;
2956            destination.write_from_interval(self, result)?;
2957            Ok(None)
2958        }
2959    }
2960
2961    fn exec_fn_trait(
2962        &mut self,
2963        def: FunctionId,
2964        args: &[IntervalAndTy<'db>],
2965        generic_args: GenericArgs<'db>,
2966        locals: &Locals<'a, 'db>,
2967        destination: Interval,
2968        target_bb: Option<BasicBlockId>,
2969        span: MirSpan,
2970    ) -> Result<'db, Option<StackFrame<'a, 'db>>> {
2971        let func = args
2972            .first()
2973            .ok_or_else(|| MirEvalError::InternalError("fn trait with no arg".into()))?;
2974        let mut func_ty = func.ty;
2975        let mut func_data = func.interval;
2976        while let TyKind::Ref(_, z, _) = func_ty.kind() {
2977            func_ty = z;
2978            if matches!(func_ty.kind(), TyKind::Dynamic(..)) {
2979                let id =
2980                    from_bytes!(usize, &func_data.get(self)?[self.ptr_size()..self.ptr_size() * 2]);
2981                func_data = func_data.slice(0..self.ptr_size());
2982                func_ty = self.vtable_map.ty(id)?;
2983            }
2984            let size = self.size_of_sized(func_ty, locals, "self type of fn trait")?;
2985            func_data = Interval { addr: Address::from_bytes(func_data.get(self)?)?, size };
2986        }
2987        match func_ty.kind() {
2988            TyKind::FnDef(def, subst) => {
2989                self.exec_fn_def(def.0, subst, destination, &args[1..], locals, target_bb, span)
2990            }
2991            TyKind::FnPtr(..) => {
2992                self.exec_fn_pointer(func_data, destination, &args[1..], locals, target_bb, span)
2993            }
2994            TyKind::Closure(closure, subst) => self.exec_closure(
2995                closure.0,
2996                func_data,
2997                GenericArgs::new_from_slice(subst.as_closure().parent_args()),
2998                destination,
2999                &args[1..],
3000                locals,
3001                span,
3002            ),
3003            _ => {
3004                // try to execute the manual impl of `FnTrait` for structs (nightly feature used in std)
3005                let arg0 = func;
3006                let args = &args[1..];
3007                let arg1 = {
3008                    let ty = Ty::new_tup_from_iter(self.interner(), args.iter().map(|it| it.ty));
3009                    let layout = self.layout(ty)?;
3010                    let result = self.construct_with_layout(
3011                        layout.size.bytes_usize(),
3012                        &layout,
3013                        None,
3014                        args.iter().map(|it| IntervalOrOwned::Borrowed(it.interval)),
3015                    )?;
3016                    // FIXME: there is some leak here
3017                    let size = layout.size.bytes_usize();
3018                    let addr = self.heap_allocate(size, layout.align.bytes() as usize)?;
3019                    self.write_memory(addr, &result)?;
3020                    IntervalAndTy { interval: Interval { addr, size }, ty }
3021                };
3022                self.exec_fn_with_args(
3023                    def,
3024                    &[arg0.clone(), arg1],
3025                    generic_args,
3026                    locals,
3027                    destination,
3028                    target_bb,
3029                    span,
3030                )
3031            }
3032        }
3033    }
3034
3035    fn eval_static(&mut self, st: StaticId, locals: &Locals<'a, 'db>) -> Result<'db, Address> {
3036        if let Some(o) = self.static_locations.get(&st) {
3037            return Ok(*o);
3038        };
3039        let static_data = StaticSignature::of(self.db, st);
3040        let result = if !static_data.flags.contains(StaticFlags::EXTERN) {
3041            let allocation = self.db.const_eval_static(st).map_err(|e| {
3042                MirEvalError::ConstEvalError(static_data.name.as_str().to_owned(), Box::new(e))
3043            })?;
3044            self.allocate_allocation_in_heap(locals, allocation)?
3045        } else {
3046            let ty = InferenceResult::of(self.db, DefWithBodyId::from(st))
3047                .expr_ty(Body::of(self.db, st.into()).root_expr());
3048            let Some((size, align)) = self.size_align_of(ty, locals)? else {
3049                not_supported!("unsized extern static");
3050            };
3051            let addr = self.heap_allocate(size, align)?;
3052            Interval::new(addr, size)
3053        };
3054        let addr = self.heap_allocate(self.ptr_size(), self.ptr_size())?;
3055        self.write_memory(addr, &result.addr.to_bytes())?;
3056        self.static_locations.insert(st, addr);
3057        Ok(addr)
3058    }
3059
3060    fn const_eval_discriminant(&self, variant: EnumVariantId) -> Result<'db, i128> {
3061        let r = self.db.const_eval_discriminant(variant);
3062        match r {
3063            Ok(r) => Ok(r),
3064            Err(e) => {
3065                let db = self.db;
3066                let loc = variant.lookup(db);
3067                let edition = self.crate_id.data(self.db).edition;
3068                let name = format!(
3069                    "{}::{}",
3070                    EnumSignature::of(self.db, loc.parent).name.display(db, edition),
3071                    loc.parent
3072                        .enum_variants(self.db)
3073                        .variant_name_by_id(variant)
3074                        .unwrap()
3075                        .display(db, edition),
3076                );
3077                Err(MirEvalError::ConstEvalError(name, Box::new(e)))
3078            }
3079        }
3080    }
3081
3082    fn drop_place(
3083        &mut self,
3084        place: &Place,
3085        locals: &mut Locals<'a, 'db>,
3086        span: MirSpan,
3087    ) -> Result<'db, ()> {
3088        let (addr, ty, metadata) = self.place_addr_and_ty_and_metadata(place, locals)?;
3089        if !locals.drop_flags.remove_place(place.as_ref()) {
3090            return Ok(());
3091        }
3092        let metadata = match metadata {
3093            Some(it) => it.get(self)?.to_vec(),
3094            None => vec![],
3095        };
3096        self.run_drop_glue_deep(ty, locals, addr, &metadata, span)
3097    }
3098
3099    fn run_drop_glue_deep(
3100        &mut self,
3101        ty: Ty<'db>,
3102        locals: &Locals<'a, 'db>,
3103        addr: Address,
3104        metadata: &[u8],
3105        span: MirSpan,
3106    ) -> Result<'db, ()> {
3107        let Some(drop_fn) = self.lang_items().Drop_drop else {
3108            // in some tests we don't have drop trait in minicore, and
3109            // we can ignore drop in them.
3110            return Ok(());
3111        };
3112
3113        let generic_args = GenericArgs::new_from_slice(&[ty.into()]);
3114        let (drop_impl, drop_args) = self.db.lookup_impl_method(
3115            ParamEnvAndCrate { param_env: self.param_env.param_env, krate: self.crate_id },
3116            drop_fn,
3117            generic_args,
3118        );
3119        if let Either::Left(drop_impl) = drop_impl
3120            && matches!(drop_impl.lookup(self.db).container, ItemContainerId::ImplId(_))
3121            && let Ok(body) = self.db.monomorphized_mir_body(
3122                drop_impl.into(),
3123                drop_args.store(),
3124                self.param_env.store(),
3125            )
3126        {
3127            self.exec_looked_up_function(
3128                body,
3129                locals,
3130                drop_impl,
3131                iter::once(IntervalOrOwned::Owned(addr.to_bytes().to_vec())),
3132                span,
3133                Interval { addr: Address::Invalid(0), size: 0 },
3134                None,
3135            )?;
3136        }
3137        match ty.kind() {
3138            TyKind::Adt(adt_def, subst) => {
3139                let id = adt_def.def_id();
3140                match id {
3141                    AdtId::StructId(s) => {
3142                        let data = StructSignature::of(self.db, s);
3143                        if data.flags.contains(StructFlags::IS_MANUALLY_DROP) {
3144                            return Ok(());
3145                        }
3146                        let layout = self.layout_adt(id, subst)?;
3147                        let variant_fields = s.fields(self.db);
3148                        match variant_fields.shape {
3149                            FieldsShape::Record | FieldsShape::Tuple => {
3150                                let field_types = self.db.field_types(s.into());
3151                                for (field, _) in variant_fields.fields().iter() {
3152                                    let offset = layout
3153                                        .fields
3154                                        .offset(u32::from(field.into_raw()) as usize)
3155                                        .bytes_usize();
3156                                    let addr = addr.offset(offset);
3157                                    let ty = field_types[field]
3158                                        .ty()
3159                                        .instantiate(self.interner(), subst)
3160                                        .skip_norm_wip();
3161                                    self.run_drop_glue_deep(ty, locals, addr, &[], span)?;
3162                                }
3163                            }
3164                            FieldsShape::Unit => (),
3165                        }
3166                    }
3167                    AdtId::UnionId(_) => (), // union fields don't need drop
3168                    AdtId::EnumId(_) => (),
3169                }
3170            }
3171            TyKind::Dynamic(..) => {
3172                if !metadata.is_empty() {
3173                    let concrete_ty = self.vtable_map.ty_of_bytes(metadata)?;
3174                    self.run_drop_glue_deep(concrete_ty, locals, addr, &[], span)?;
3175                }
3176            }
3177            TyKind::Bool
3178            | TyKind::Char
3179            | TyKind::Int(_)
3180            | TyKind::Uint(_)
3181            | TyKind::Float(_)
3182            | TyKind::Tuple(_)
3183            | TyKind::Array(_, _)
3184            | TyKind::Slice(_)
3185            | TyKind::RawPtr(_, _)
3186            | TyKind::Ref(_, _, _)
3187            | TyKind::Alias(..)
3188            | TyKind::FnDef(_, _)
3189            | TyKind::Str
3190            | TyKind::Never
3191            | TyKind::Closure(_, _)
3192            | TyKind::Coroutine(_, _)
3193            | TyKind::CoroutineClosure(..)
3194            | TyKind::CoroutineWitness(_, _)
3195            | TyKind::Foreign(_)
3196            | TyKind::Error(_)
3197            | TyKind::Param(_)
3198            | TyKind::Placeholder(_)
3199            | TyKind::FnPtr(..)
3200            | TyKind::Bound(..)
3201            | TyKind::Infer(..)
3202            | TyKind::Pat(..)
3203            | TyKind::UnsafeBinder(..) => (),
3204        };
3205        Ok(())
3206    }
3207
3208    fn write_to_stdout(&mut self, interval: Interval) -> Result<'db, ()> {
3209        self.stdout.extend(interval.get(self)?.to_vec());
3210        Ok(())
3211    }
3212
3213    fn write_to_stderr(&mut self, interval: Interval) -> Result<'db, ()> {
3214        self.stderr.extend(interval.get(self)?.to_vec());
3215        Ok(())
3216    }
3217}
3218
3219pub fn render_const_using_debug_impl<'db>(
3220    db: &'db dyn HirDatabase,
3221    owner: InferBodyId<'db>,
3222    c: Allocation<'db>,
3223    ty: Ty<'db>,
3224) -> Result<'db, String> {
3225    let mut evaluator = Evaluator::new(db, owner, false, None)?;
3226    let locals = &Locals {
3227        ptr: ArenaMap::new(),
3228        body: db
3229            .mir_body(owner)
3230            .map_err(|_| MirEvalError::NotSupported("unreachable".to_owned()))?,
3231        drop_flags: DropFlags::default(),
3232    };
3233    let data = evaluator.allocate_allocation_in_heap(locals, c)?;
3234    let lang_items = evaluator.interner().lang_items();
3235    let resolver = owner.resolver(db);
3236    let Some(debug_fmt_fn) = lang_items.Debug_fmt else {
3237        not_supported!("core::fmt::Debug::fmt not found");
3238    };
3239    let ptr_size = evaluator.ptr_size();
3240    // Construct the arguments of `format_args!("{:?}", THE_CONST)` directly in memory and hand
3241    // them to `std::fmt::format`.
3242    //
3243    // `core::fmt::rt::Argument` is a niche-encoded `Placeholder { value: NonNull<()>, formatter }`,
3244    // i.e. two words: a pointer to the value, and the type-erased `<T as Debug>::fmt` function.
3245    // A non-null `value` is what distinguishes the `Placeholder` variant from `Count`.
3246    let argument = evaluator.heap_allocate(ptr_size * 2, ptr_size)?;
3247    evaluator.write_memory(argument, &data.addr.to_bytes())?;
3248    let debug_fmt_fn_ptr = evaluator.vtable_map.id(Ty::new_fn_def(
3249        evaluator.interner(),
3250        CallableDefId::FunctionId(debug_fmt_fn).into(),
3251        GenericArgs::new_from_slice(&[ty.into()]),
3252    ));
3253    evaluator.write_memory(argument.offset(ptr_size), &debug_fmt_fn_ptr.to_le_bytes())?;
3254    // Since Rust 1.93 `core::fmt::Arguments` is two words wide:
3255    //   struct Arguments<'a> { template: NonNull<u8>, args: NonNull<Argument<'a>> }
3256    // `template` points at a byte-encoded format string; `format_args!("{:?}", x)` encodes to a
3257    // single default placeholder (`0xC0`) followed by the end marker (`0x00`). `args` points at
3258    // our one-element argument array, and must stay pointer-aligned: `core` uses the low bit of
3259    // `args` as a tag (1 = inline `&str` form, 0 = placeholder form), and heap allocations here
3260    // are pointer-aligned so the bit is 0 as required.
3261    let template = evaluator.heap_allocate(2, 1)?;
3262    evaluator.write_memory(template, &[0xC0, 0x00])?;
3263    let arguments = evaluator.heap_allocate(ptr_size * 2, ptr_size)?;
3264    evaluator.write_memory(arguments, &template.to_bytes())?;
3265    evaluator.write_memory(arguments.offset(ptr_size), &argument.to_bytes())?;
3266    let Some(ValueNs::FunctionId(format_fn)) = resolver.resolve_path_in_value_ns_fully(
3267        db,
3268        &hir_def::expr_store::path::Path::from_known_path_with_no_generic(path![std::fmt::format]),
3269        HygieneId::ROOT,
3270    ) else {
3271        not_supported!("std::fmt::format not found");
3272    };
3273    let interval = evaluator.interpret_mir(
3274        db.mir_body(format_fn.into()).map_err(|e| MirEvalError::MirLowerError(format_fn, e))?,
3275        [IntervalOrOwned::Borrowed(Interval { addr: arguments, size: ptr_size * 2 })].into_iter(),
3276    )?;
3277    let message_string = interval.get(&evaluator)?;
3278    let words = [
3279        from_bytes!(usize, message_string[0..ptr_size]),
3280        from_bytes!(usize, message_string[ptr_size..2 * ptr_size]),
3281        from_bytes!(usize, message_string[2 * ptr_size..3 * ptr_size]),
3282    ];
3283    let Some(addr) = words.into_iter().map(Address::from_usize).find(|it| matches!(it, Heap(_)))
3284    else {
3285        // No heap buffer means the formatted string is empty.
3286        return Ok(String::new());
3287    };
3288    let size = words
3289        .into_iter()
3290        .filter(|&it| !matches!(Address::from_usize(it), Heap(_)))
3291        .min()
3292        .unwrap_or(0);
3293    Ok(std::string::String::from_utf8_lossy(evaluator.read_memory(addr, size)?).into_owned())
3294}
3295
3296#[derive(PartialEq, Eq)]
3297pub enum IsSigned {
3298    Yes,
3299    No,
3300}
3301
3302impl From<bool> for IsSigned {
3303    fn from(value: bool) -> Self {
3304        if value { Self::Yes } else { Self::No }
3305    }
3306}
3307
3308pub fn pad16(it: &[u8], is_signed: IsSigned) -> [u8; 16] {
3309    let is_negative = is_signed == IsSigned::Yes && it.last().unwrap_or(&0) > &127;
3310    let mut res = [if is_negative { 255 } else { 0 }; 16];
3311    res[..it.len()].copy_from_slice(it);
3312    res
3313}
3314
3315macro_rules! for_each_int_type {
3316    ($call_macro:path, $args:tt) => {
3317        $call_macro! {
3318            $args
3319            I8
3320            U8
3321            I16
3322            U16
3323            I32
3324            U32
3325            I64
3326            U64
3327            I128
3328            U128
3329        }
3330    };
3331}
3332
3333#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3334enum IntValue {
3335    I8(i8),
3336    U8(u8),
3337    I16(i16),
3338    U16(u16),
3339    I32(i32),
3340    U32(u32),
3341    I64(i64),
3342    U64(u64),
3343    I128(i128),
3344    U128(u128),
3345}
3346
3347macro_rules! checked_int_op {
3348    ( [ $op:ident ] $( $int_ty:ident )+ ) => {
3349        fn $op(self, other: Self) -> Option<Self> {
3350            match (self, other) {
3351                $( (Self::$int_ty(a), Self::$int_ty(b)) => a.$op(b).map(Self::$int_ty), )+
3352                _ => panic!("incompatible integer types"),
3353            }
3354        }
3355    };
3356}
3357
3358macro_rules! int_bit_shifts {
3359    ( [ $op:ident ] $( $int_ty:ident )+ ) => {
3360        fn $op(self, amount: u32) -> Option<Self> {
3361            match self {
3362                $( Self::$int_ty(this) => this.$op(amount).map(Self::$int_ty), )+
3363            }
3364        }
3365    };
3366}
3367
3368macro_rules! unchecked_int_op {
3369    ( [ $name:ident, $op:tt ]  $( $int_ty:ident )+ ) => {
3370        fn $name(self, other: Self) -> Self {
3371            match (self, other) {
3372                $( (Self::$int_ty(a), Self::$int_ty(b)) => Self::$int_ty(a $op b), )+
3373                _ => panic!("incompatible integer types"),
3374            }
3375        }
3376    };
3377}
3378
3379impl IntValue {
3380    fn from_bytes(bytes: &[u8], is_signed: bool) -> Self {
3381        match (bytes.len(), is_signed) {
3382            (1, false) => Self::U8(u8::from_le_bytes(bytes.try_into().unwrap())),
3383            (1, true) => Self::I8(i8::from_le_bytes(bytes.try_into().unwrap())),
3384            (2, false) => Self::U16(u16::from_le_bytes(bytes.try_into().unwrap())),
3385            (2, true) => Self::I16(i16::from_le_bytes(bytes.try_into().unwrap())),
3386            (4, false) => Self::U32(u32::from_le_bytes(bytes.try_into().unwrap())),
3387            (4, true) => Self::I32(i32::from_le_bytes(bytes.try_into().unwrap())),
3388            (8, false) => Self::U64(u64::from_le_bytes(bytes.try_into().unwrap())),
3389            (8, true) => Self::I64(i64::from_le_bytes(bytes.try_into().unwrap())),
3390            (16, false) => Self::U128(u128::from_le_bytes(bytes.try_into().unwrap())),
3391            (16, true) => Self::I128(i128::from_le_bytes(bytes.try_into().unwrap())),
3392            (len, is_signed) => {
3393                never!("invalid integer size: {len}, signed: {is_signed}");
3394                Self::I32(0)
3395            }
3396        }
3397    }
3398
3399    fn to_bytes(self) -> Vec<u8> {
3400        macro_rules! m {
3401            ( [] $( $int_ty:ident )+ ) => {
3402                match self {
3403                    $( Self::$int_ty(v) => v.to_le_bytes().to_vec() ),+
3404                }
3405            };
3406        }
3407        for_each_int_type! { m, [] }
3408    }
3409
3410    fn as_u32(self) -> Option<u32> {
3411        macro_rules! m {
3412            ( [] $( $int_ty:ident )+ ) => {
3413                match self {
3414                    $( Self::$int_ty(v) => v.try_into().ok() ),+
3415                }
3416            };
3417        }
3418        for_each_int_type! { m, [] }
3419    }
3420
3421    for_each_int_type!(checked_int_op, [checked_add]);
3422    for_each_int_type!(checked_int_op, [checked_sub]);
3423    for_each_int_type!(checked_int_op, [checked_div]);
3424    for_each_int_type!(checked_int_op, [checked_rem]);
3425    for_each_int_type!(checked_int_op, [checked_mul]);
3426
3427    for_each_int_type!(int_bit_shifts, [checked_shl]);
3428    for_each_int_type!(int_bit_shifts, [checked_shr]);
3429}
3430
3431impl std::ops::BitAnd for IntValue {
3432    type Output = Self;
3433    for_each_int_type!(unchecked_int_op, [bitand, &]);
3434}
3435impl std::ops::BitOr for IntValue {
3436    type Output = Self;
3437    for_each_int_type!(unchecked_int_op, [bitor, |]);
3438}
3439impl std::ops::BitXor for IntValue {
3440    type Output = Self;
3441    for_each_int_type!(unchecked_int_op, [bitxor, ^]);
3442}