Skip to main content

rune/runtime/
vm.rs

1use core::cmp::Ordering;
2use core::fmt;
3use core::mem::replace;
4use core::ptr::NonNull;
5
6use crate::alloc::prelude::*;
7use crate::alloc::{self, String};
8use crate::hash::{Hash, IntoHash, ToTypeHash};
9use crate::modules::{cmp, option, result};
10use crate::runtime;
11use crate::sync::Arc;
12use crate::ItemBuf;
13
14mod ops;
15use self::ops::*;
16
17use super::{
18    budget, hint_capacity, inst, Address, AnySequence, Args, Awaited, BorrowMut, Bytes, Call,
19    ControlFlow, DynArgs, DynGuardedArgs, Format, FormatSpec, Formatter, FromValue, Function,
20    Future, Generator, GeneratorState, Globals, GuardedArgs, Inline, InstArithmeticOp,
21    InstBitwiseOp, InstOp, InstRange, InstShiftOp, InstTarget, InstValue, IntoOutput, Object,
22    Output, OwnedTuple, Pair, Panic, Protocol, ProtocolCaller, Range, RangeFrom, RangeFull,
23    RangeInclusive, RangeTo, RangeToInclusive, Repr, RttiKind, RuntimeContext, Select,
24    SelectFuture, Stack, StoreError, Stream, Type, TypeHash, TypeInfo, TypeOf, Unit,
25    UnitConstContext, UnitFn, UnitStorage, Value, Vec, VmDiagnostics, VmDiagnosticsObj, VmError,
26    VmErrorKind, VmExecution, VmHalt, VmIntegerRepr, VmOutcome, VmSendExecution, Worklist,
27};
28
29/// Helper to take a value, replacing the old one with empty.
30#[inline(always)]
31fn take(value: &mut Value) -> Value {
32    replace(value, Value::empty())
33}
34
35/// Indicating the kind of isolation that is present for a frame.
36#[derive(Debug, Clone, Copy)]
37pub enum Isolated {
38    /// The frame is isolated, once pop it will cause the execution to complete.
39    Isolated,
40    /// No isolation is present, the vm will continue executing.
41    None,
42}
43
44impl Isolated {
45    #[inline]
46    pub(crate) fn new(value: bool) -> Self {
47        if value {
48            Self::Isolated
49        } else {
50            Self::None
51        }
52    }
53
54    #[inline]
55    pub(crate) fn then_some<T>(self, value: T) -> Option<T> {
56        match self {
57            Self::Isolated => Some(value),
58            Self::None => None,
59        }
60    }
61}
62
63impl fmt::Display for Isolated {
64    #[inline]
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        match self {
67            Self::Isolated => write!(f, "isolated"),
68            Self::None => write!(f, "none"),
69        }
70    }
71}
72
73/// The result from a dynamic call. Indicates if the attempted operation is
74/// supported.
75#[derive(Debug)]
76pub(crate) enum CallResultOnly<T> {
77    /// Call successful. Return value is on the stack.
78    Ok(T),
79    /// Call failed because function was missing so the method is unsupported.
80    /// Contains target value.
81    Unsupported(Value),
82}
83
84/// The result from a dynamic call. Indicates if the attempted operation is
85/// supported.
86#[derive(Debug)]
87pub(crate) enum CallResult<T> {
88    /// Call successful. Return value is on the stack.
89    Ok(T),
90    /// A call frame was pushed onto the virtual machine, which needs to be
91    /// advanced to produce the result.
92    Frame,
93    /// Call failed because function was missing so the method is unsupported.
94    /// Contains target value.
95    Unsupported(Value),
96}
97
98/// A stack which references variables indirectly from a slab.
99#[derive(Debug)]
100pub struct Vm {
101    /// Context associated with virtual machine.
102    context: Arc<RuntimeContext>,
103    /// Unit associated with virtual machine.
104    unit: Arc<Unit>,
105    /// The current instruction pointer.
106    ip: usize,
107    /// The length of the last instruction pointer.
108    last_ip_len: u8,
109    /// The current stack.
110    stack: Stack,
111    /// Frames relative to the stack.
112    call_frames: alloc::Vec<CallFrame>,
113    /// Storage for static items declared by the unit.
114    globals: Globals,
115    /// The values which are waiting to be taken apart.
116    ///
117    /// The machine keeps this for as long as it lives, so that the memory it
118    /// grows to hold what it is handed is grown once rather than for every
119    /// value it takes apart - see [`Work::dismantle`].
120    worklist: Worklist,
121}
122
123impl Vm {
124    /// Construct a new virtual machine.
125    ///
126    /// Constructing a virtual machine is a cheap constant-time operation.
127    ///
128    /// See [`unit_mut`] and [`context_mut`] documentation for information on
129    /// how to re-use existing [`Vm`]'s.
130    ///
131    /// [`unit_mut`]: Vm::unit_mut
132    /// [`context_mut`]: Vm::context_mut
133    pub const fn new(context: Arc<RuntimeContext>, unit: Arc<Unit>) -> Self {
134        Self::with_stack(context, unit, Stack::new())
135    }
136
137    /// Construct a new virtual machine with a custom stack.
138    ///
139    /// The virtual machine starts out without any storage for static items. If
140    /// the unit declares any, use [`with_globals`] to configure it.
141    ///
142    /// [`with_globals`]: Vm::with_globals
143    pub const fn with_stack(context: Arc<RuntimeContext>, unit: Arc<Unit>, stack: Stack) -> Self {
144        Self {
145            context,
146            unit,
147            ip: 0,
148            last_ip_len: 0,
149            stack,
150            call_frames: alloc::Vec::new(),
151            globals: Globals::empty(),
152            worklist: Worklist::new(),
153        }
154    }
155
156    /// Write a value into the given output, taking the value which was there
157    /// apart over the machine's own worklist.
158    #[inline(always)]
159    pub(crate) fn store<O>(&mut self, out: Output, o: O) -> Result<(), StoreError<O::Error>>
160    where
161        O: IntoOutput,
162    {
163        self.stack.store_with(out, o, &mut self.worklist)
164    }
165
166    /// How much the machine's worklist has grown, which it keeps rather than
167    /// growing one for every value it takes apart.
168    #[cfg(all(test, not(miri)))]
169    pub(crate) fn worklist_capacity(&self) -> usize {
170        self.worklist.capacity()
171    }
172
173    /// Truncate the stack at the given address, taking the values which are
174    /// discarded apart over the machine's own worklist.
175    #[inline(always)]
176    pub(crate) fn dismantle_to(&mut self, addr: Address) {
177        self.stack.dismantle_to(addr, &mut self.worklist);
178    }
179
180    /// Clear the stack, taking the values it held apart over the machine's own
181    /// worklist.
182    #[inline(always)]
183    pub(crate) fn dismantle_clear(&mut self) {
184        self.stack.dismantle_clear(&mut self.worklist);
185    }
186
187    /// Configure the storage used for static items declared by the unit.
188    ///
189    /// The storage is a handle, so the caller can hold on to a clone of it in
190    /// order to read and write static items while this virtual machine runs.
191    ///
192    /// See [`Globals`] for an example.
193    #[inline]
194    pub fn with_globals(mut self, globals: Globals) -> Self {
195        self.globals = globals;
196        self
197    }
198
199    /// Construct a vm with a default empty [RuntimeContext]. This is useful
200    /// when the [Unit] was constructed with an empty
201    /// [Context][crate::compile::Context].
202    pub fn without_runtime(unit: Arc<Unit>) -> alloc::Result<Self> {
203        Ok(Self::new(Arc::try_new(RuntimeContext::default())?, unit))
204    }
205
206    /// Test if the virtual machine is the same context and unit as specified.
207    pub fn is_same(&self, context: &Arc<RuntimeContext>, unit: &Arc<Unit>) -> bool {
208        Arc::ptr_eq(&self.context, context) && Arc::ptr_eq(&self.unit, unit)
209    }
210
211    /// Test if the virtual machine is the same context.
212    pub fn is_same_context(&self, context: &Arc<RuntimeContext>) -> bool {
213        Arc::ptr_eq(&self.context, context)
214    }
215
216    /// Test if the virtual machine is the same context.
217    pub fn is_same_unit(&self, unit: &Arc<Unit>) -> bool {
218        Arc::ptr_eq(&self.unit, unit)
219    }
220
221    /// Test if the virtual machine uses the same static item storage.
222    pub fn is_same_globals(&self, globals: &Globals) -> bool {
223        self.globals.is_same(globals)
224    }
225
226    /// Access the storage for static items declared by the unit.
227    #[inline]
228    pub fn globals(&self) -> &Globals {
229        &self.globals
230    }
231
232    /// Access the storage for static items declared by the unit mutably.
233    ///
234    /// Note that this can be used to swap out the [`Globals`] of a running vm,
235    /// in the same way [`unit_mut`] swaps out the [`Unit`].
236    ///
237    /// [`unit_mut`]: Vm::unit_mut
238    #[inline]
239    pub fn globals_mut(&mut self) -> &mut Globals {
240        &mut self.globals
241    }
242
243    /// Set  the current instruction pointer.
244    #[inline]
245    pub fn set_ip(&mut self, ip: usize) {
246        self.ip = ip;
247    }
248
249    /// Get the stack.
250    #[inline]
251    pub fn call_frames(&self) -> &[CallFrame] {
252        &self.call_frames
253    }
254
255    /// Get the stack.
256    #[inline]
257    pub fn stack(&self) -> &Stack {
258        &self.stack
259    }
260
261    /// Get the stack mutably.
262    #[inline]
263    pub fn stack_mut(&mut self) -> &mut Stack {
264        &mut self.stack
265    }
266
267    /// Access the context related to the virtual machine mutably.
268    ///
269    /// Note that this can be used to swap out the [`RuntimeContext`] associated
270    /// with the running vm. Note that this is only necessary if the underlying
271    /// [`Context`] is different or has been modified. In contrast to
272    /// constructing a [`new`] vm, this allows for amortised re-use of any
273    /// allocations.
274    ///
275    /// After doing this, it's important to call [`clear`] to clean up any
276    /// residual state.
277    ///
278    /// [`clear`]: Vm::clear
279    /// [`Context`]: crate::Context
280    /// [`new`]: Vm::new
281    #[inline]
282    pub fn context_mut(&mut self) -> &mut Arc<RuntimeContext> {
283        &mut self.context
284    }
285
286    /// Access the context related to the virtual machine.
287    #[inline]
288    pub fn context(&self) -> &Arc<RuntimeContext> {
289        &self.context
290    }
291
292    /// Access the underlying unit of the virtual machine mutably.
293    ///
294    /// Note that this can be used to swap out the [`Unit`] of execution in the
295    /// running vm. In contrast to constructing a [`new`] vm, this allows for
296    /// amortised re-use of any allocations.
297    ///
298    /// After doing this, it's important to call [`clear`] to clean up any
299    /// residual state.
300    ///
301    /// [`clear`]: Vm::clear
302    /// [`new`]: Vm::new
303    #[inline]
304    pub fn unit_mut(&mut self) -> &mut Arc<Unit> {
305        &mut self.unit
306    }
307
308    /// Access the underlying unit of the virtual machine.
309    #[inline]
310    pub fn unit(&self) -> &Arc<Unit> {
311        &self.unit
312    }
313
314    /// Access the current instruction pointer.
315    #[inline]
316    pub fn ip(&self) -> usize {
317        self.ip
318    }
319
320    /// Access the last instruction that was executed.
321    #[inline]
322    pub fn last_ip(&self) -> usize {
323        self.ip.wrapping_sub(self.last_ip_len as usize)
324    }
325
326    /// Reset this virtual machine, freeing all memory used.
327    pub fn clear(&mut self) {
328        self.ip = 0;
329        self.stack.clear();
330        self.call_frames.clear();
331    }
332
333    /// Look up a function in the virtual machine by its name.
334    ///
335    /// # Examples
336    ///
337    /// ```no_run
338    /// use rune::sync::Arc;
339    /// use rune::{Context, Unit, Vm};
340    ///
341    /// let mut sources = rune::sources! {
342    ///     entry => {
343    ///         pub fn max(a, b) {
344    ///             if a > b {
345    ///                 a
346    ///             } else {
347    ///                 b
348    ///             }
349    ///         }
350    ///     }
351    /// };
352    ///
353    /// let context = Context::with_default_modules()?;
354    /// let runtime = Arc::try_new(context.runtime()?)?;
355    ///
356    /// let unit = rune::prepare(&mut sources).build()?;
357    /// let unit = Arc::try_new(unit)?;
358    ///
359    /// let vm = Vm::new(runtime, unit);
360    ///
361    /// // Looking up an item from the source.
362    /// let dynamic_max = vm.lookup_function(["max"])?;
363    ///
364    /// let value = dynamic_max.call::<i64>((10, 20))?;
365    /// assert_eq!(value, 20);
366    ///
367    /// // Building an item buffer to lookup an `::std` item.
368    /// let item = rune::item!(::std::i64::max);
369    /// let max = vm.lookup_function(item)?;
370    ///
371    /// let value = max.call::<i64>((10, 20))?;
372    /// assert_eq!(value, 20);
373    /// # Ok::<_, rune::support::Error>(())
374    /// ```
375    pub fn lookup_function<N>(&self, name: N) -> Result<Function, VmError>
376    where
377        N: ToTypeHash,
378    {
379        Ok(self.lookup_function_by_hash(name.to_type_hash())?)
380    }
381
382    /// Convert into an execution.
383    pub(crate) fn into_execution(self) -> VmExecution<Self> {
384        VmExecution::new(self)
385    }
386
387    /// Run the given vm to completion.
388    ///
389    /// # Errors
390    ///
391    /// If any non-completing outcomes like yielding or awaiting are
392    /// encountered, this will error.
393    pub fn complete(self) -> Result<Value, VmError> {
394        self.into_execution().complete()
395    }
396
397    /// Run the given vm to completion with support for async functions.
398    pub async fn async_complete(self) -> Result<Value, VmError> {
399        self.into_execution().resume().await?.into_complete()
400    }
401
402    /// Call the function identified by the given name.
403    ///
404    /// Computing the function hash from the name can be a bit costly, so it's
405    /// worth noting that it can be precalculated:
406    ///
407    /// ```
408    /// use rune::Hash;
409    ///
410    /// let name = Hash::type_hash(["main"]);
411    /// ```
412    ///
413    /// # Examples
414    ///
415    /// ```no_run
416    /// use rune::sync::Arc;
417    /// use rune::{Context, Unit, Vm};
418    ///
419    /// let unit = Arc::try_new(Unit::default())?;
420    /// let mut vm = Vm::without_runtime(unit)?;
421    ///
422    /// let output = vm.execute(["main"], (33i64,))?.complete()?;
423    /// let output: i64 = rune::from_value(output)?;
424    ///
425    /// println!("output: {}", output);
426    /// # Ok::<_, rune::support::Error>(())
427    /// ```
428    ///
429    /// You can use a `Vec<Value>` to provide a variadic collection of
430    /// arguments.
431    ///
432    /// ```no_run
433    /// use rune::sync::Arc;
434    /// use rune::{Context, Unit, Vm};
435    ///
436    /// // Normally the unit would be created by compiling some source,
437    /// // and since this one is empty it won't do anything.
438    /// let unit = Arc::try_new(Unit::default())?;
439    /// let mut vm = Vm::without_runtime(unit)?;
440    ///
441    /// let mut args = Vec::new();
442    /// args.push(rune::to_value(1u32)?);
443    /// args.push(rune::to_value(String::from("Hello World"))?);
444    ///
445    /// let output = vm.execute(["main"], args)?.complete()?;
446    /// let output: i64 = rune::from_value(output)?;
447    ///
448    /// println!("output: {}", output);
449    /// # Ok::<_, rune::support::Error>(())
450    /// ```
451    pub fn execute(
452        &mut self,
453        name: impl ToTypeHash,
454        args: impl Args,
455    ) -> Result<VmExecution<&mut Self>, VmError> {
456        self.set_entrypoint(name, args.count())?;
457        args.into_stack(&mut self.stack)?;
458        Ok(VmExecution::new(self))
459    }
460
461    /// An `execute` variant that returns an execution which implements
462    /// [`Send`], allowing it to be sent and executed on a different thread.
463    ///
464    /// This is accomplished by preventing values escaping from being
465    /// non-exclusively sent with the execution or escaping the execution. We
466    /// only support encoding arguments which themselves are `Send`.
467    pub fn send_execute(
468        mut self,
469        name: impl ToTypeHash,
470        args: impl Args + Send,
471    ) -> Result<VmSendExecution, VmError> {
472        // Safety: make sure the stack is clear, preventing any values from
473        // being sent along with the virtual machine.
474        self.dismantle_clear();
475
476        self.set_entrypoint(name, args.count())?;
477        args.into_stack(&mut self.stack)?;
478        Ok(VmSendExecution(VmExecution::new(self)))
479    }
480
481    /// Call the given function immediately, returning the produced value.
482    ///
483    /// This function permits for using references since it doesn't defer its
484    /// execution.
485    pub fn call(
486        &mut self,
487        name: impl ToTypeHash,
488        args: impl GuardedArgs,
489    ) -> Result<Value, VmError> {
490        self.set_entrypoint(name, args.count())?;
491
492        // Safety: We hold onto the guard until the vm has completed and
493        // `VmExecution` will clear the stack before this function returns.
494        // Erronously or not.
495        let guard = unsafe { args.guarded_into_stack(&mut self.stack)? };
496
497        let value = {
498            // Clearing the stack here on panics has safety implications - see
499            // above.
500            let vm = ClearStack(self);
501            VmExecution::new(&mut *vm.0).complete()?
502        };
503
504        // Note: this might panic if something in the vm is holding on to a
505        // reference of the value. We should prevent it from being possible to
506        // take any owned references to values held by this.
507        drop(guard);
508        Ok(value)
509    }
510
511    /// Call the given function immediately, returning the produced value.
512    ///
513    /// This function permits for using references since it doesn't defer its
514    /// execution.
515    pub fn call_with_diagnostics(
516        &mut self,
517        name: impl ToTypeHash,
518        args: impl GuardedArgs,
519        diagnostics: &mut dyn VmDiagnostics,
520    ) -> Result<Value, VmError> {
521        self.set_entrypoint(name, args.count())?;
522
523        // Safety: We hold onto the guard until the vm has completed and
524        // `VmExecution` will clear the stack before this function returns.
525        // Erronously or not.
526        let guard = unsafe { args.guarded_into_stack(&mut self.stack)? };
527
528        let value = {
529            // Clearing the stack here on panics has safety implications - see
530            // above.
531            let vm = ClearStack(self);
532            VmExecution::new(&mut *vm.0)
533                .resume()
534                .with_diagnostics(diagnostics)
535                .complete()
536                .and_then(VmOutcome::into_complete)
537        };
538
539        // Note: this might panic if something in the vm is holding on to a
540        // reference of the value. We should prevent it from being possible to
541        // take any owned references to values held by this.
542        drop(guard);
543        value
544    }
545
546    /// Call the given function immediately asynchronously, returning the
547    /// produced value.
548    ///
549    /// This function permits for using references since it doesn't defer its
550    /// execution.
551    pub async fn async_call<A, N>(&mut self, name: N, args: A) -> Result<Value, VmError>
552    where
553        N: ToTypeHash,
554        A: GuardedArgs,
555    {
556        self.set_entrypoint(name, args.count())?;
557
558        // Safety: We hold onto the guard until the vm has completed and
559        // `VmExecution` will clear the stack before this function returns.
560        // Erronously or not.
561        let guard = unsafe { args.guarded_into_stack(&mut self.stack)? };
562
563        let value = {
564            // Clearing the stack here on panics has safety implications - see
565            // above.
566            let vm = ClearStack(self);
567            VmExecution::new(&mut *vm.0)
568                .resume()
569                .await
570                .and_then(VmOutcome::into_complete)
571        };
572
573        // Note: this might panic if something in the vm is holding on to a
574        // reference of the value. We should prevent it from being possible to
575        // take any owned references to values held by this.
576        drop(guard);
577        value
578    }
579
580    /// Update the instruction pointer to match the function matching the given
581    /// name and check that the number of argument matches.
582    fn set_entrypoint<N>(&mut self, name: N, count: usize) -> Result<(), VmErrorKind>
583    where
584        N: ToTypeHash,
585    {
586        let hash = name.to_type_hash();
587
588        let Some(info) = self.unit.function(&hash) else {
589            return Err(if let Some(item) = name.to_item()? {
590                VmErrorKind::MissingEntry { hash, item }
591            } else {
592                VmErrorKind::MissingEntryHash { hash }
593            });
594        };
595
596        let offset = match info {
597            // NB: we ignore the calling convention.
598            // everything is just async when called externally.
599            UnitFn::Offset {
600                offset,
601                args: expected,
602                ..
603            } => {
604                check_args(count, *expected)?;
605                *offset
606            }
607            _ => {
608                return Err(VmErrorKind::MissingFunction { hash });
609            }
610        };
611
612        self.ip = offset;
613        self.dismantle_clear();
614        self.call_frames.clear();
615        Ok(())
616    }
617
618    /// Helper function to call an instance function.
619    #[inline]
620    pub(crate) fn call_instance_fn(
621        &mut self,
622        isolated: Isolated,
623        target: Value,
624        hash: impl ToTypeHash,
625        args: &mut dyn DynArgs,
626        out: Output,
627    ) -> Result<CallResult<()>, VmError> {
628        let count = args.count().wrapping_add(1);
629        let type_hash = target.type_hash();
630        let hash = Hash::associated_function(type_hash, hash.to_type_hash());
631        self.call_hash_with(isolated, hash, target, args, count, out)
632    }
633
634    /// Helper to call a field function.
635    #[inline]
636    fn call_field_fn(
637        &mut self,
638        protocol: impl IntoHash,
639        target: Value,
640        name: impl IntoHash,
641        args: &mut dyn DynArgs,
642        out: Output,
643    ) -> Result<CallResult<()>, VmError> {
644        let count = args.count().wrapping_add(1);
645        let hash = Hash::field_function(protocol, target.type_hash(), name);
646        self.call_hash_with(Isolated::None, hash, target, args, count, out)
647    }
648
649    /// Helper to call an index function.
650    #[inline]
651    fn call_index_fn(
652        &mut self,
653        protocol: impl IntoHash,
654        target: Value,
655        index: usize,
656        args: &mut dyn DynArgs,
657        out: Output,
658    ) -> Result<CallResult<()>, VmError> {
659        let count = args.count().wrapping_add(1);
660        let hash = Hash::index_function(protocol, target.type_hash(), Hash::index(index));
661        self.call_hash_with(Isolated::None, hash, target, args, count, out)
662    }
663
664    fn called_function_hook(&self, hash: Hash) -> Result<(), VmError> {
665        runtime::env::exclusive(|context, _, _, diagnostics| {
666            if let Some(diagnostics) = diagnostics {
667                diagnostics.function_used(context, hash, self.ip())?;
668            }
669
670            Ok(())
671        })
672    }
673
674    #[inline(never)]
675    fn call_hash_with(
676        &mut self,
677        isolated: Isolated,
678        hash: Hash,
679        target: Value,
680        args: &mut dyn DynArgs,
681        count: usize,
682        out: Output,
683    ) -> Result<CallResult<()>, VmError> {
684        if let Some(handler) = self.context.function(&hash) {
685            let addr = self.stack.addr();
686
687            self.called_function_hook(hash)?;
688            self.stack.push(target)?;
689            args.push_to_stack(&mut self.stack)?;
690
691            let result = handler.call(&mut self.stack, addr, count, out);
692            self.dismantle_to(addr);
693            result?;
694            return Ok(CallResult::Ok(()));
695        }
696
697        if let Some(UnitFn::Offset {
698            offset,
699            call,
700            args: expected,
701            ..
702        }) = self.unit.function(&hash)
703        {
704            check_args(count, *expected)?;
705
706            let addr = self.stack.addr();
707
708            self.called_function_hook(hash)?;
709            self.stack.push(target)?;
710            args.push_to_stack(&mut self.stack)?;
711
712            let result = self.call_offset_fn(*offset, *call, addr, count, isolated, out);
713
714            if result? {
715                self.dismantle_to(addr);
716                return Ok(CallResult::Frame);
717            } else {
718                return Ok(CallResult::Ok(()));
719            }
720        }
721
722        Ok(CallResult::Unsupported(target))
723    }
724
725    #[cfg_attr(feature = "bench", inline(never))]
726    fn internal_cmp(
727        &mut self,
728        match_ordering: fn(Ordering) -> bool,
729        lhs: Address,
730        rhs: Address,
731        out: Output,
732    ) -> Result<(), VmError> {
733        let rhs = self.stack.at(rhs);
734        let lhs = self.stack.at(lhs);
735
736        let ordering = match (lhs.as_inline_unchecked(), rhs.as_inline_unchecked()) {
737            (Some(lhs), Some(rhs)) => lhs.partial_cmp(rhs)?,
738            _ => {
739                let lhs = lhs.clone();
740                let rhs = rhs.clone();
741                Value::partial_cmp_with(&lhs, &rhs, self)?
742            }
743        };
744
745        self.store(out, || match ordering {
746            Some(ordering) => match_ordering(ordering),
747            None => false,
748        })?;
749
750        Ok(())
751    }
752
753    /// Push a new call frame.
754    ///
755    /// This will cause the `args` number of elements on the stack to be
756    /// associated and accessible to the new call frame.
757    #[tracing::instrument(skip(self), fields(call_frames = self.call_frames.len(), top = self.stack.top(), stack = self.stack.len(), self.ip))]
758    pub(crate) fn push_call_frame(
759        &mut self,
760        ip: usize,
761        addr: Address,
762        args: usize,
763        isolated: Isolated,
764        out: Output,
765    ) -> Result<(), VmErrorKind> {
766        tracing::trace!("pushing call frame");
767
768        let top = self.stack.swap_top(addr, args)?;
769        let ip = replace(&mut self.ip, ip);
770
771        let frame = CallFrame {
772            ip,
773            top,
774            isolated,
775            out,
776        };
777
778        self.call_frames.try_push(frame)?;
779        Ok(())
780    }
781
782    /// Take over an unstarted machine as a call frame of this one.
783    ///
784    /// The values it holds are the arguments of the call which produced it, so
785    /// moving them to the top of this stack and opening a frame over them is
786    /// exactly the ordinary call this machine would have made had the callee
787    /// not been async. This is what keeps awaiting an async call from needing a
788    /// nested machine, and therefore from recursing.
789    ///
790    /// The caller is responsible for having established that the machine shares
791    /// this one's unit, context and storage.
792    #[tracing::instrument(skip(self, vm), fields(call_frames = self.call_frames.len(), top = self.stack.top(), stack = self.stack.len(), self.ip))]
793    pub(crate) fn splice_call(&mut self, mut vm: Vm, out: Output) -> Result<(), VmErrorKind> {
794        tracing::trace!("splicing call frame");
795
796        let top = self.stack.push_frame_from(vm.stack_mut())?;
797        let ip = replace(&mut self.ip, vm.ip);
798
799        let frame = CallFrame {
800            ip,
801            top,
802            isolated: Isolated::None,
803            out,
804        };
805
806        self.call_frames.try_push(frame)?;
807        Ok(())
808    }
809
810    /// Pop a call frame from an internal call, which needs the current stack
811    /// pointer to be returned and does not check for context isolation through
812    /// [`CallFrame::isolated`].
813    #[tracing::instrument(skip(self), fields(call_frames = self.call_frames.len(), top = self.stack.top(), stack = self.stack.len(), self.ip))]
814    pub(crate) fn pop_call_frame_from_call(&mut self) -> Result<Option<usize>, VmError> {
815        tracing::trace!("popping call frame from call");
816
817        let Some(frame) = self.call_frames.pop() else {
818            return Ok(None);
819        };
820
821        tracing::trace!(?frame);
822        self.stack.pop_stack_top(frame.top, &mut self.worklist);
823        Ok(Some(replace(&mut self.ip, frame.ip)))
824    }
825
826    /// Pop a call frame and return it.
827    #[tracing::instrument(skip(self), fields(call_frames = self.call_frames.len(), top = self.stack.top(), stack = self.stack.len(), self.ip))]
828    pub(crate) fn pop_call_frame(&mut self) -> Result<(Isolated, Option<Output>), VmError> {
829        tracing::trace!("popping call frame");
830
831        let Some(frame) = self.call_frames.pop() else {
832            self.stack.pop_stack_top(0, &mut self.worklist);
833            return Ok((Isolated::Isolated, None));
834        };
835
836        tracing::trace!(?frame);
837        self.stack.pop_stack_top(frame.top, &mut self.worklist);
838        self.ip = frame.ip;
839        Ok((frame.isolated, Some(frame.out)))
840    }
841
842    /// Implementation of getting a string index on an object-like type.
843    fn try_object_like_index_get(target: &Value, field: &str) -> Result<Option<Value>, VmError> {
844        match target.as_ref() {
845            Repr::Dynamic(data) if matches!(data.rtti().kind, RttiKind::Struct) => {
846                let Some(value) = data.get_field_ref(field)? else {
847                    return Err(VmError::new(VmErrorKind::MissingField {
848                        target: data.type_info(),
849                        field: field.try_to_owned()?,
850                    }));
851                };
852
853                Ok(Some(value.clone()))
854            }
855            Repr::Any(value) => match value.type_hash() {
856                Object::HASH => {
857                    let target = value.borrow_ref::<Object>()?;
858
859                    let Some(value) = target.get(field) else {
860                        return Err(VmError::new(VmErrorKind::MissingField {
861                            target: TypeInfo::any::<Object>(),
862                            field: field.try_to_owned()?,
863                        }));
864                    };
865
866                    Ok(Some(value.clone()))
867                }
868                _ => Ok(None),
869            },
870            _ => Ok(None),
871        }
872    }
873
874    /// Implementation of getting a string index on an object-like type.
875    fn try_tuple_like_index_get(target: &Value, index: usize) -> Result<Option<Value>, VmError> {
876        let result = match target.as_ref() {
877            Repr::Inline(target) => match target {
878                Inline::Unit => Err(target.type_info()),
879                _ => return Ok(None),
880            },
881            Repr::Dynamic(data) if matches!(data.rtti().kind, RttiKind::Tuple) => {
882                match data.get_ref(index)? {
883                    Some(value) => Ok(value.clone()),
884                    None => Err(data.type_info()),
885                }
886            }
887            Repr::Dynamic(data) => Err(data.type_info()),
888            Repr::Any(target) => match target.type_hash() {
889                Result::<Value, Value>::HASH => {
890                    match (index, &*target.borrow_ref::<Result<Value, Value>>()?) {
891                        (0, Ok(value)) => Ok(value.clone()),
892                        (0, Err(value)) => Ok(value.clone()),
893                        _ => Err(target.type_info()),
894                    }
895                }
896                Option::<Value>::HASH => match (index, &*target.borrow_ref::<Option<Value>>()?) {
897                    (0, Some(value)) => Ok(value.clone()),
898                    _ => Err(target.type_info()),
899                },
900                GeneratorState::HASH => match (index, &*target.borrow_ref()?) {
901                    (0, GeneratorState::Yielded(value)) => Ok(value.clone()),
902                    (0, GeneratorState::Complete(value)) => Ok(value.clone()),
903                    _ => Err(target.type_info()),
904                },
905                runtime::Vec::HASH => {
906                    let vec = target.borrow_ref::<runtime::Vec>()?;
907
908                    match vec.get(index) {
909                        Some(value) => Ok(value.clone()),
910                        None => Err(target.type_info()),
911                    }
912                }
913                runtime::OwnedTuple::HASH => {
914                    let tuple = target.borrow_ref::<runtime::OwnedTuple>()?;
915
916                    match tuple.get(index) {
917                        Some(value) => Ok(value.clone()),
918                        None => Err(target.type_info()),
919                    }
920                }
921                _ => {
922                    return Ok(None);
923                }
924            },
925        };
926
927        match result {
928            Ok(value) => Ok(Some(value)),
929            Err(target) => Err(VmError::new(VmErrorKind::MissingIndexInteger {
930                target,
931                index: VmIntegerRepr::from(index),
932            })),
933        }
934    }
935
936    /// Implementation of getting a string index on an object-like type.
937    fn try_tuple_like_index_set(
938        target: &Value,
939        index: usize,
940        from: &Value,
941        worklist: &mut Worklist,
942    ) -> Result<bool, VmError> {
943        match target.as_ref() {
944            Repr::Inline(target) => match target {
945                Inline::Unit => Ok(false),
946                _ => Ok(false),
947            },
948            Repr::Dynamic(data) if matches!(data.rtti().kind, RttiKind::Tuple) => {
949                if let Some(target) = data.borrow_mut()?.get_mut(index) {
950                    worklist.replace(target, from.clone());
951                    return Ok(true);
952                }
953
954                Ok(false)
955            }
956            Repr::Dynamic(..) => Ok(false),
957            Repr::Any(value) => match value.type_hash() {
958                Result::<Value, Value>::HASH => {
959                    let mut result = value.borrow_mut::<Result<Value, Value>>()?;
960
961                    let target = match &mut *result {
962                        Ok(ok) if index == 0 => ok,
963                        Err(err) if index == 1 => err,
964                        _ => return Ok(false),
965                    };
966
967                    worklist.replace(target, from.clone());
968                    Ok(true)
969                }
970                Option::<Value>::HASH => {
971                    let mut option = value.borrow_mut::<Option<Value>>()?;
972
973                    let target = match &mut *option {
974                        Some(some) if index == 0 => some,
975                        _ => return Ok(false),
976                    };
977
978                    worklist.replace(target, from.clone());
979                    Ok(true)
980                }
981                runtime::Vec::HASH => {
982                    let mut vec = value.borrow_mut::<runtime::Vec>()?;
983
984                    if let Some(target) = vec.get_mut(index) {
985                        worklist.replace(target, from.clone());
986                        return Ok(true);
987                    }
988
989                    Ok(false)
990                }
991                runtime::OwnedTuple::HASH => {
992                    let mut tuple = value.borrow_mut::<runtime::OwnedTuple>()?;
993
994                    if let Some(target) = tuple.get_mut(index) {
995                        worklist.replace(target, from.clone());
996                        return Ok(true);
997                    }
998
999                    Ok(false)
1000                }
1001                _ => Ok(false),
1002            },
1003        }
1004    }
1005
1006    fn try_object_slot_index_set(
1007        target: &Value,
1008        field: &str,
1009        value: &Value,
1010        worklist: &mut Worklist,
1011    ) -> Result<bool, VmErrorKind> {
1012        match target.as_ref() {
1013            Repr::Dynamic(data) if matches!(data.rtti().kind, RttiKind::Struct) => {
1014                if let Some(mut v) = data.get_field_mut(field)? {
1015                    worklist.replace(&mut v, value.clone());
1016                    return Ok(true);
1017                }
1018
1019                Err(VmErrorKind::MissingField {
1020                    target: data.type_info(),
1021                    field: field.try_to_owned()?,
1022                })
1023            }
1024            Repr::Any(target) => match target.type_hash() {
1025                Object::HASH => {
1026                    let mut target = target.borrow_mut::<Object>()?;
1027
1028                    if let Some(target) = target.get_mut(field) {
1029                        worklist.replace(target, value.clone());
1030                    } else {
1031                        let key = field.try_to_owned()?;
1032
1033                        // Any value which was already there is taken apart
1034                        // rather than dropped.
1035                        if let Some(old) = target.insert(key, value.clone())? {
1036                            worklist.dismantle(old);
1037                        }
1038                    }
1039
1040                    Ok(true)
1041                }
1042                _ => Ok(false),
1043            },
1044            target => Err(VmErrorKind::MissingField {
1045                target: target.type_info(),
1046                field: field.try_to_owned()?,
1047            }),
1048        }
1049    }
1050
1051    /// Internal implementation of the instance check.
1052    fn as_op(&mut self, lhs: Address, rhs: Address) -> Result<Value, VmError> {
1053        let b = self.stack.at(rhs);
1054        let a = self.stack.at(lhs);
1055
1056        let Repr::Inline(Inline::Type(ty)) = b.as_ref() else {
1057            return Err(VmError::new(VmErrorKind::UnsupportedIs {
1058                value: a.type_info(),
1059                test_type: b.type_info(),
1060            }));
1061        };
1062
1063        macro_rules! convert {
1064            ($from:ty, $value:expr) => {
1065                match ty.into_hash() {
1066                    f64::HASH => Value::from($value as f64),
1067                    u64::HASH => Value::from($value as u64),
1068                    i64::HASH => Value::from($value as i64),
1069                    _ => {
1070                        return Err(VmError::new(VmErrorKind::UnsupportedAsTarget {
1071                            value: TypeInfo::from(<$from as TypeOf>::STATIC_TYPE_INFO),
1072                        }));
1073                    }
1074                }
1075            };
1076        }
1077
1078        let value = match a.as_ref() {
1079            Repr::Inline(Inline::Unsigned(a)) => convert!(u64, *a),
1080            Repr::Inline(Inline::Signed(a)) => convert!(i64, *a),
1081            Repr::Inline(Inline::Float(a)) => convert!(f64, *a),
1082            value => {
1083                return Err(VmError::new(VmErrorKind::UnsupportedAs {
1084                    value: value.type_info(),
1085                }));
1086            }
1087        };
1088
1089        Ok(value)
1090    }
1091
1092    /// Internal implementation of the instance check.
1093    fn test_is_instance(&mut self, lhs: Address, rhs: Address) -> Result<bool, VmError> {
1094        let b = self.stack.at(rhs);
1095        let a = self.stack.at(lhs);
1096
1097        let Some(Inline::Type(ty)) = b.as_inline() else {
1098            return Err(VmError::new(VmErrorKind::UnsupportedIs {
1099                value: a.type_info(),
1100                test_type: b.type_info(),
1101            }));
1102        };
1103
1104        Ok(a.type_hash() == ty.into_hash())
1105    }
1106
1107    fn internal_bool(
1108        &mut self,
1109        bool_op: impl FnOnce(bool, bool) -> bool,
1110        op: &'static str,
1111        lhs: Address,
1112        rhs: Address,
1113        out: Output,
1114    ) -> Result<(), VmError> {
1115        let rhs = self.stack.at(rhs);
1116        let lhs = self.stack.at(lhs);
1117
1118        let inline = match (lhs.as_ref(), rhs.as_ref()) {
1119            (Repr::Inline(Inline::Bool(lhs)), Repr::Inline(Inline::Bool(rhs))) => {
1120                let value = bool_op(*lhs, *rhs);
1121                Inline::Bool(value)
1122            }
1123            (lhs, rhs) => {
1124                return Err(VmError::new(VmErrorKind::UnsupportedBinaryOperation {
1125                    op,
1126                    lhs: lhs.type_info(),
1127                    rhs: rhs.type_info(),
1128                }));
1129            }
1130        };
1131
1132        self.store(out, inline)?;
1133        Ok(())
1134    }
1135
1136    /// Construct a future from calling an async function.
1137    fn call_generator_fn(
1138        &mut self,
1139        offset: usize,
1140        addr: Address,
1141        args: usize,
1142        out: Output,
1143    ) -> Result<(), VmErrorKind> {
1144        let values = self.stack.slice_at_mut(addr, args)?;
1145
1146        if let Some(at) = out.as_addr() {
1147            let stack = values.iter_mut().map(take).try_collect::<Stack>()?;
1148            let mut vm = Self::with_stack(self.context.clone(), self.unit.clone(), stack)
1149                .with_globals(self.globals.clone());
1150            vm.ip = offset;
1151            let value = Value::try_from(Generator::new(vm))?;
1152            self.worklist.replace(self.stack.at_mut(at)?, value);
1153        } else {
1154            for value in values.iter_mut() {
1155                self.worklist.take(value);
1156            }
1157        }
1158
1159        Ok(())
1160    }
1161
1162    /// Construct a stream from calling a function.
1163    fn call_stream_fn(
1164        &mut self,
1165        offset: usize,
1166        addr: Address,
1167        args: usize,
1168        out: Output,
1169    ) -> Result<(), VmErrorKind> {
1170        let values = self.stack.slice_at_mut(addr, args)?;
1171
1172        if let Some(at) = out.as_addr() {
1173            let stack = values.iter_mut().map(take).try_collect::<Stack>()?;
1174            let mut vm = Self::with_stack(self.context.clone(), self.unit.clone(), stack)
1175                .with_globals(self.globals.clone());
1176            vm.ip = offset;
1177            let value = Value::try_from(Stream::new(vm))?;
1178            self.worklist.replace(self.stack.at_mut(at)?, value);
1179        } else {
1180            for value in values.iter_mut() {
1181                self.worklist.take(value);
1182            }
1183        }
1184
1185        Ok(())
1186    }
1187
1188    /// Construct a future from calling a function.
1189    fn call_async_fn(
1190        &mut self,
1191        offset: usize,
1192        addr: Address,
1193        args: usize,
1194        out: Output,
1195    ) -> Result<(), VmErrorKind> {
1196        let values = self.stack.slice_at_mut(addr, args)?;
1197
1198        if let Some(at) = out.as_addr() {
1199            let stack = values.iter_mut().map(take).try_collect::<Stack>()?;
1200            let mut vm = Self::with_stack(self.context.clone(), self.unit.clone(), stack)
1201                .with_globals(self.globals.clone());
1202            vm.ip = offset;
1203            let future = Future::from_execution(vm.into_execution())?;
1204            let value = Value::try_from(future)?;
1205            self.worklist.replace(self.stack.at_mut(at)?, value);
1206        } else {
1207            for value in values.iter_mut() {
1208                self.worklist.take(value);
1209            }
1210        }
1211
1212        Ok(())
1213    }
1214
1215    /// Helper function to call the function at the given offset.
1216    #[cfg_attr(feature = "bench", inline(never))]
1217    fn call_offset_fn(
1218        &mut self,
1219        offset: usize,
1220        call: Call,
1221        addr: Address,
1222        args: usize,
1223        isolated: Isolated,
1224        out: Output,
1225    ) -> Result<bool, VmErrorKind> {
1226        let moved = match call {
1227            Call::Async => {
1228                self.call_async_fn(offset, addr, args, out)?;
1229                false
1230            }
1231            Call::Immediate => {
1232                self.push_call_frame(offset, addr, args, isolated, out)?;
1233                true
1234            }
1235            Call::Stream => {
1236                self.call_stream_fn(offset, addr, args, out)?;
1237                false
1238            }
1239            Call::Generator => {
1240                self.call_generator_fn(offset, addr, args, out)?;
1241                false
1242            }
1243        };
1244
1245        Ok(moved)
1246    }
1247
1248    /// Execute a fallback operation.
1249    #[cfg_attr(feature = "bench", inline(never))]
1250    fn target_fallback_assign(
1251        &mut self,
1252        fallback: TargetFallback,
1253        protocol: &Protocol,
1254    ) -> Result<(), VmError> {
1255        match fallback {
1256            TargetFallback::Value(lhs, rhs) => {
1257                let mut args = DynGuardedArgs::new((rhs.clone(),));
1258
1259                if let CallResult::Unsupported(lhs) = self.call_instance_fn(
1260                    Isolated::None,
1261                    lhs,
1262                    protocol.hash,
1263                    &mut args,
1264                    Output::discard(),
1265                )? {
1266                    return Err(VmError::new(VmErrorKind::UnsupportedBinaryOperation {
1267                        op: protocol.name,
1268                        lhs: lhs.type_info(),
1269                        rhs: rhs.type_info(),
1270                    }));
1271                };
1272            }
1273            TargetFallback::Field(lhs, hash, slot, rhs) => {
1274                let mut args = DynGuardedArgs::new((rhs,));
1275
1276                if let CallResult::Unsupported(lhs) =
1277                    self.call_field_fn(protocol, lhs.clone(), hash, &mut args, Output::discard())?
1278                {
1279                    let Some(field) = self.unit.lookup_string(slot) else {
1280                        return Err(VmError::new(VmErrorKind::MissingStaticString { slot }));
1281                    };
1282
1283                    return Err(VmError::new(VmErrorKind::UnsupportedObjectSlotIndexGet {
1284                        target: lhs.type_info(),
1285                        field: field.clone(),
1286                    }));
1287                }
1288            }
1289            TargetFallback::Index(lhs, index, rhs) => {
1290                let mut args = DynGuardedArgs::new((rhs,));
1291
1292                if let CallResult::Unsupported(lhs) = self.call_index_fn(
1293                    protocol.hash,
1294                    lhs.clone(),
1295                    index,
1296                    &mut args,
1297                    Output::discard(),
1298                )? {
1299                    return Err(VmError::new(VmErrorKind::UnsupportedTupleIndexGet {
1300                        target: lhs.type_info(),
1301                        index,
1302                    }));
1303                }
1304            }
1305        }
1306
1307        Ok(())
1308    }
1309
1310    /// Await the value at the given address.
1311    ///
1312    /// Returns `None` if the future was an async call which had yet to run, in
1313    /// which case it has been spliced into this machine as a call frame and
1314    /// there is nothing to suspend on - see [`Vm::splice_call`].
1315    #[cfg_attr(feature = "bench", inline(never))]
1316    fn op_await(&mut self, addr: Address, out: Output) -> Result<Option<Future>, VmError> {
1317        let mut future = self.stack.at(addr).clone().into_future()?;
1318
1319        let Some(vm) = future.take_unstarted_vm() else {
1320            return Ok(Some(future));
1321        };
1322
1323        // A machine which does not agree with this one on what it is running
1324        // has to stay a machine of its own, since a call frame carries none of
1325        // that with it.
1326        if !Arc::ptr_eq(vm.context(), &self.context)
1327            || !Arc::ptr_eq(vm.unit(), &self.unit)
1328            || !vm.globals().is_same(&self.globals)
1329        {
1330            return Ok(Some(Future::from_execution(vm.into_execution())?));
1331        }
1332
1333        self.splice_call(vm, out)?;
1334        Ok(None)
1335    }
1336
1337    #[cfg_attr(feature = "bench", inline(never))]
1338    fn op_select(
1339        &mut self,
1340        addr: Address,
1341        len: usize,
1342        value: Output,
1343    ) -> Result<Option<Select>, VmError> {
1344        let futures = futures_util::stream::FuturesUnordered::new();
1345
1346        for (branch, value) in self.stack.slice_at(addr, len)?.iter().enumerate() {
1347            let future = value.clone().into_mut::<Future>()?;
1348
1349            if !future.is_completed() {
1350                futures.push(SelectFuture::new(self.ip + branch, future));
1351            }
1352        }
1353
1354        if futures.is_empty() {
1355            self.store(value, ())?;
1356            self.ip = self.ip.wrapping_add(len);
1357            return Ok(None);
1358        }
1359
1360        Ok(Some(Select::new(futures)))
1361    }
1362
1363    #[cfg_attr(feature = "bench", inline(never))]
1364    fn op_store(&mut self, value: InstValue, out: Output) -> Result<(), VmError> {
1365        self.store(out, value.into_value())?;
1366        Ok(())
1367    }
1368
1369    /// Copy a value from a position relative to the top of the stack, to the
1370    /// top of the stack.
1371    #[cfg_attr(feature = "bench", inline(never))]
1372    fn op_copy(&mut self, addr: Address, out: Output) -> Result<(), VmError> {
1373        self.stack.copy(addr, out, &mut self.worklist)?;
1374        Ok(())
1375    }
1376
1377    /// Move a value from a position relative to the top of the stack, to the
1378    /// top of the stack.
1379    #[cfg_attr(feature = "bench", inline(never))]
1380    fn op_move(&mut self, addr: Address, out: Output) -> Result<(), VmError> {
1381        let value = self.stack.at(addr).clone();
1382        let value = value.move_()?;
1383        self.store(out, value)?;
1384        Ok(())
1385    }
1386
1387    #[cfg_attr(feature = "bench", inline(never))]
1388    fn op_drop(&mut self, set: usize) -> Result<(), VmError> {
1389        let Some(addresses) = self.unit.lookup_drop_set(set) else {
1390            return Err(VmError::new(VmErrorKind::MissingDropSet { set }));
1391        };
1392
1393        for &addr in addresses {
1394            // Taking the value apart over the worklist the machine keeps
1395            // rather than leaving it to its destructor, which would grow one of
1396            // its own for it.
1397            self.worklist.take(self.stack.at_mut(addr)?);
1398        }
1399
1400        Ok(())
1401    }
1402
1403    /// Swap two values on the stack.
1404    #[cfg_attr(feature = "bench", inline(never))]
1405    fn op_swap(&mut self, a: Address, b: Address) -> Result<(), VmError> {
1406        self.stack.swap(a, b)?;
1407        Ok(())
1408    }
1409
1410    /// Perform a jump operation.
1411    #[cfg_attr(feature = "bench", inline(never))]
1412    fn op_jump(&mut self, jump: usize) -> Result<(), VmError> {
1413        self.ip = self.unit.translate(jump)?;
1414        Ok(())
1415    }
1416
1417    /// Perform a conditional jump operation.
1418    #[cfg_attr(feature = "bench", inline(never))]
1419    #[cfg_attr(not(feature = "bench"), inline)]
1420    fn op_jump_if(&mut self, cond: Address, jump: usize) -> Result<(), VmErrorKind> {
1421        if matches!(
1422            self.stack.at(cond).as_ref(),
1423            Repr::Inline(Inline::Bool(true))
1424        ) {
1425            self.ip = self.unit.translate(jump)?;
1426        }
1427
1428        Ok(())
1429    }
1430
1431    /// pop-and-jump-if-not instruction.
1432    #[cfg_attr(feature = "bench", inline(never))]
1433    fn op_jump_if_not(&mut self, cond: Address, jump: usize) -> Result<(), VmErrorKind> {
1434        if matches!(
1435            self.stack.at(cond).as_ref(),
1436            Repr::Inline(Inline::Bool(false))
1437        ) {
1438            self.ip = self.unit.translate(jump)?;
1439        }
1440
1441        Ok(())
1442    }
1443
1444    /// Construct a new vec.
1445    #[cfg_attr(feature = "bench", inline(never))]
1446    fn op_vec(&mut self, addr: Address, count: usize, out: Output) -> Result<(), VmError> {
1447        let vec = self.stack.slice_at_mut(addr, count)?;
1448        let vec = vec
1449            .iter_mut()
1450            .map(take)
1451            .try_collect::<alloc::Vec<Value>>()?;
1452        self.store(out, Vec::from(vec))?;
1453        Ok(())
1454    }
1455
1456    /// Construct a new tuple.
1457    #[cfg_attr(feature = "bench", inline(never))]
1458    fn op_tuple(&mut self, addr: Address, count: usize, out: Output) -> Result<(), VmError> {
1459        let tuple = self.stack.slice_at_mut(addr, count)?;
1460
1461        let tuple = tuple
1462            .iter_mut()
1463            .map(take)
1464            .try_collect::<alloc::Vec<Value>>()?;
1465
1466        self.store(out, || OwnedTuple::try_from(tuple))?;
1467        Ok(())
1468    }
1469
1470    /// Construct a new tuple with a fixed number of arguments.
1471    #[cfg_attr(feature = "bench", inline(never))]
1472    fn op_tuple_n(&mut self, addr: &[Address], out: Output) -> Result<(), VmError> {
1473        let mut tuple = alloc::Vec::<Value>::try_with_capacity(addr.len())?;
1474
1475        for &arg in addr {
1476            let value = self.stack.at(arg).clone();
1477            tuple.try_push(value)?;
1478        }
1479
1480        self.store(out, || OwnedTuple::try_from(tuple))?;
1481        Ok(())
1482    }
1483
1484    /// Push the tuple that is on top of the stack.
1485    #[cfg_attr(feature = "bench", inline(never))]
1486    fn op_environment(&mut self, addr: Address, count: usize, out: Output) -> Result<(), VmError> {
1487        let tuple = self.stack.at(addr).clone();
1488        let tuple = tuple.borrow_tuple_ref()?;
1489
1490        if tuple.len() != count {
1491            return Err(VmError::new(VmErrorKind::BadEnvironmentCount {
1492                expected: count,
1493                actual: tuple.len(),
1494            }));
1495        }
1496
1497        if let Some(addr) = out.as_addr() {
1498            let out = self.stack.slice_at_mut(addr, count)?;
1499
1500            for (value, out) in tuple.iter().zip(out.iter_mut()) {
1501                self.worklist.replace(out, value.clone());
1502            }
1503        }
1504
1505        Ok(())
1506    }
1507
1508    #[cfg_attr(feature = "bench", inline(never))]
1509    fn op_allocate(&mut self, size: usize) -> Result<(), VmError> {
1510        self.stack.resize(size)?;
1511        Ok(())
1512    }
1513
1514    #[cfg_attr(feature = "bench", inline(never))]
1515    fn op_not(&mut self, addr: Address, out: Output) -> Result<(), VmError> {
1516        self.unary(addr, out, &Protocol::NOT, |inline| match *inline {
1517            Inline::Bool(value) => Ok(Some(Inline::Bool(!value))),
1518            Inline::Unsigned(value) => Ok(Some(Inline::Unsigned(!value))),
1519            Inline::Signed(value) => Ok(Some(Inline::Signed(!value))),
1520            _ => Ok(None),
1521        })
1522    }
1523
1524    #[cfg_attr(feature = "bench", inline(never))]
1525    fn op_neg(&mut self, addr: Address, out: Output) -> Result<(), VmError> {
1526        self.unary(addr, out, &Protocol::NEG, |inline| match *inline {
1527            Inline::Signed(value) => {
1528                let value = value.checked_neg().ok_or(VmErrorKind::Overflow)?;
1529                Ok(Some(Inline::Signed(value)))
1530            }
1531            Inline::Float(value) => Ok(Some(Inline::Float(-value))),
1532            _ => Ok(None),
1533        })
1534    }
1535
1536    fn unary(
1537        &mut self,
1538        operand: Address,
1539        out: Output,
1540        protocol: &'static Protocol,
1541        op: impl FnOnce(&Inline) -> Result<Option<Inline>, VmErrorKind>,
1542    ) -> Result<(), VmError> {
1543        let operand = self.stack.at(operand);
1544
1545        'fallback: {
1546            let store = match operand.as_ref() {
1547                Repr::Inline(inline) => op(inline).map_err(VmError::new)?,
1548                Repr::Any(..) => break 'fallback,
1549                _ => None,
1550            };
1551
1552            let Some(store) = store else {
1553                return Err(VmError::new(VmErrorKind::UnsupportedUnaryOperation {
1554                    op: protocol.name,
1555                    operand: operand.type_info(),
1556                }));
1557            };
1558
1559            self.store(out, store)?;
1560            return Ok(());
1561        };
1562
1563        let operand = operand.clone();
1564
1565        if let CallResult::Unsupported(operand) =
1566            self.call_instance_fn(Isolated::None, operand, protocol, &mut (), out)?
1567        {
1568            return Err(VmError::new(VmErrorKind::UnsupportedUnaryOperation {
1569                op: protocol.name,
1570                operand: operand.type_info(),
1571            }));
1572        }
1573
1574        Ok(())
1575    }
1576
1577    #[cfg_attr(feature = "bench", inline(never))]
1578    fn op_op(
1579        &mut self,
1580        op: InstOp,
1581        lhs: Address,
1582        rhs: Address,
1583        out: Output,
1584    ) -> Result<(), VmError> {
1585        match op {
1586            InstOp::Lt => {
1587                self.internal_cmp(|o| matches!(o, Ordering::Less), lhs, rhs, out)?;
1588            }
1589            InstOp::Le => {
1590                self.internal_cmp(
1591                    |o| matches!(o, Ordering::Less | Ordering::Equal),
1592                    lhs,
1593                    rhs,
1594                    out,
1595                )?;
1596            }
1597            InstOp::Gt => {
1598                self.internal_cmp(|o| matches!(o, Ordering::Greater), lhs, rhs, out)?;
1599            }
1600            InstOp::Ge => {
1601                self.internal_cmp(
1602                    |o| matches!(o, Ordering::Greater | Ordering::Equal),
1603                    lhs,
1604                    rhs,
1605                    out,
1606                )?;
1607            }
1608            InstOp::Eq => {
1609                let rhs = self.stack.at(rhs);
1610                let lhs = self.stack.at(lhs);
1611
1612                let test = if let (Some(lhs), Some(rhs)) = (lhs.as_inline(), rhs.as_inline()) {
1613                    lhs.partial_eq(rhs)?
1614                } else {
1615                    let lhs = lhs.clone();
1616                    let rhs = rhs.clone();
1617                    Value::partial_eq_with(&lhs, &rhs, self)?
1618                };
1619
1620                self.store(out, test)?;
1621            }
1622            InstOp::Neq => {
1623                let rhs = self.stack.at(rhs);
1624                let lhs = self.stack.at(lhs);
1625
1626                let test = if let (Some(lhs), Some(rhs)) = (lhs.as_inline(), rhs.as_inline()) {
1627                    lhs.partial_eq(rhs)?
1628                } else {
1629                    let lhs = lhs.clone();
1630                    let rhs = rhs.clone();
1631                    Value::partial_eq_with(&lhs, &rhs, self)?
1632                };
1633
1634                self.store(out, !test)?;
1635            }
1636            InstOp::And => {
1637                self.internal_bool(|a, b| a && b, "&&", lhs, rhs, out)?;
1638            }
1639            InstOp::Or => {
1640                self.internal_bool(|a, b| a || b, "||", lhs, rhs, out)?;
1641            }
1642            InstOp::As => {
1643                let value = self.as_op(lhs, rhs)?;
1644                self.store(out, value)?;
1645            }
1646            InstOp::Is => {
1647                let is_instance = self.test_is_instance(lhs, rhs)?;
1648                self.store(out, is_instance)?;
1649            }
1650            InstOp::IsNot => {
1651                let is_instance = self.test_is_instance(lhs, rhs)?;
1652                self.store(out, !is_instance)?;
1653            }
1654        }
1655
1656        Ok(())
1657    }
1658
1659    #[cfg_attr(feature = "bench", inline(never))]
1660    fn op_arithmetic(
1661        &mut self,
1662        op: InstArithmeticOp,
1663        lhs: Address,
1664        rhs: Address,
1665        out: Output,
1666    ) -> Result<(), VmError> {
1667        let ops = ArithmeticOps::from_op(op);
1668
1669        let lhs = self.stack.at(lhs);
1670        let rhs = self.stack.at(rhs);
1671
1672        'fallback: {
1673            let inline = match (lhs.as_ref(), rhs.as_ref()) {
1674                (Repr::Inline(lhs), Repr::Inline(rhs)) => match (lhs, rhs) {
1675                    (Inline::Unsigned(lhs), rhs) => {
1676                        let rhs = rhs.as_integer()?;
1677                        let value =
1678                            (ops.u64)(*lhs, rhs).ok_or_else(|| (ops.error)(i128::from(rhs)))?;
1679                        Inline::Unsigned(value)
1680                    }
1681                    (Inline::Signed(lhs), rhs) => {
1682                        let rhs = rhs.as_integer()?;
1683                        let value =
1684                            (ops.i64)(*lhs, rhs).ok_or_else(|| (ops.error)(i128::from(rhs)))?;
1685                        Inline::Signed(value)
1686                    }
1687                    (Inline::Float(lhs), Inline::Float(rhs)) => {
1688                        let value = (ops.f64)(*lhs, *rhs);
1689                        Inline::Float(value)
1690                    }
1691                    (lhs, rhs) => {
1692                        return Err(VmError::new(VmErrorKind::UnsupportedBinaryOperation {
1693                            op: ops.protocol.name,
1694                            lhs: lhs.type_info(),
1695                            rhs: rhs.type_info(),
1696                        }));
1697                    }
1698                },
1699                (Repr::Any(..), ..) => {
1700                    break 'fallback;
1701                }
1702                (lhs, rhs) => {
1703                    return Err(VmError::new(VmErrorKind::UnsupportedBinaryOperation {
1704                        op: ops.protocol.name,
1705                        lhs: lhs.type_info(),
1706                        rhs: rhs.type_info(),
1707                    }));
1708                }
1709            };
1710
1711            self.store(out, inline)?;
1712            return Ok(());
1713        }
1714
1715        let lhs = lhs.clone();
1716        let rhs = rhs.clone();
1717
1718        let mut args = DynGuardedArgs::new((rhs.clone(),));
1719
1720        if let CallResult::Unsupported(lhs) =
1721            self.call_instance_fn(Isolated::None, lhs, &ops.protocol, &mut args, out)?
1722        {
1723            return Err(VmError::new(VmErrorKind::UnsupportedBinaryOperation {
1724                op: ops.protocol.name,
1725                lhs: lhs.type_info(),
1726                rhs: rhs.type_info(),
1727            }));
1728        }
1729
1730        Ok(())
1731    }
1732
1733    #[cfg_attr(feature = "bench", inline(never))]
1734    fn op_bitwise(
1735        &mut self,
1736        op: InstBitwiseOp,
1737        lhs: Address,
1738        rhs: Address,
1739        out: Output,
1740    ) -> Result<(), VmError> {
1741        let ops = BitwiseOps::from_op(op);
1742
1743        let lhs = self.stack.at(lhs);
1744        let rhs = self.stack.at(rhs);
1745
1746        'fallback: {
1747            let inline = match (lhs.as_ref(), rhs.as_ref()) {
1748                (Repr::Inline(Inline::Unsigned(lhs)), Repr::Inline(rhs)) => {
1749                    let rhs = rhs.as_integer()?;
1750                    let value = (ops.u64)(*lhs, rhs);
1751                    Inline::Unsigned(value)
1752                }
1753                (Repr::Inline(Inline::Signed(lhs)), Repr::Inline(rhs)) => {
1754                    let rhs = rhs.as_integer()?;
1755                    let value = (ops.i64)(*lhs, rhs);
1756                    Inline::Signed(value)
1757                }
1758                (Repr::Inline(Inline::Bool(lhs)), Repr::Inline(Inline::Bool(rhs))) => {
1759                    let value = (ops.bool)(*lhs, *rhs);
1760                    Inline::Bool(value)
1761                }
1762                (Repr::Any(_), _) => {
1763                    break 'fallback;
1764                }
1765                (lhs, rhs) => {
1766                    return Err(VmError::new(VmErrorKind::UnsupportedBinaryOperation {
1767                        op: ops.protocol.name,
1768                        lhs: lhs.type_info(),
1769                        rhs: rhs.type_info(),
1770                    }));
1771                }
1772            };
1773
1774            self.store(out, inline)?;
1775            return Ok(());
1776        };
1777
1778        let lhs = lhs.clone();
1779        let rhs = rhs.clone();
1780
1781        let mut args = DynGuardedArgs::new((&rhs,));
1782
1783        if let CallResult::Unsupported(lhs) =
1784            self.call_instance_fn(Isolated::None, lhs, &ops.protocol, &mut args, out)?
1785        {
1786            return Err(VmError::new(VmErrorKind::UnsupportedBinaryOperation {
1787                op: ops.protocol.name,
1788                lhs: lhs.type_info(),
1789                rhs: rhs.type_info(),
1790            }));
1791        }
1792
1793        Ok(())
1794    }
1795
1796    #[cfg_attr(feature = "bench", inline(never))]
1797    fn op_shift(
1798        &mut self,
1799        op: InstShiftOp,
1800        lhs: Address,
1801        rhs: Address,
1802        out: Output,
1803    ) -> Result<(), VmError> {
1804        let ops = ShiftOps::from_op(op);
1805
1806        let (lhs, rhs) = 'fallback: {
1807            let inline = {
1808                match self.stack.pair(lhs, rhs)? {
1809                    Pair::Same(value) => match value.as_mut() {
1810                        Repr::Inline(Inline::Unsigned(value)) => {
1811                            let shift = u32::try_from(*value).ok().ok_or_else(ops.error)?;
1812                            let value = (ops.u64)(*value, shift).ok_or_else(ops.error)?;
1813                            Inline::Unsigned(value)
1814                        }
1815                        Repr::Inline(Inline::Signed(value)) => {
1816                            let shift = u32::try_from(*value).ok().ok_or_else(ops.error)?;
1817                            let value = (ops.i64)(*value, shift).ok_or_else(ops.error)?;
1818                            Inline::Signed(value)
1819                        }
1820                        Repr::Any(..) => break 'fallback (value.clone(), value.clone()),
1821                        value => {
1822                            return Err(VmError::new(VmErrorKind::UnsupportedBinaryOperation {
1823                                op: ops.protocol.name,
1824                                lhs: value.type_info(),
1825                                rhs: value.type_info(),
1826                            }));
1827                        }
1828                    },
1829                    Pair::Pair(lhs, rhs) => match (lhs.as_mut(), rhs.as_ref()) {
1830                        (Repr::Inline(Inline::Unsigned(lhs)), Repr::Inline(rhs)) => {
1831                            let rhs = rhs.as_integer()?;
1832                            let value = (ops.u64)(*lhs, rhs).ok_or_else(ops.error)?;
1833                            Inline::Unsigned(value)
1834                        }
1835                        (Repr::Inline(Inline::Signed(lhs)), Repr::Inline(rhs)) => {
1836                            let rhs = rhs.as_integer()?;
1837                            let value = (ops.i64)(*lhs, rhs).ok_or_else(ops.error)?;
1838                            Inline::Signed(value)
1839                        }
1840                        (Repr::Any(..), _) => {
1841                            break 'fallback (lhs.clone(), rhs.clone());
1842                        }
1843                        (lhs, rhs) => {
1844                            return Err(VmError::new(VmErrorKind::UnsupportedBinaryOperation {
1845                                op: ops.protocol.name,
1846                                lhs: lhs.type_info(),
1847                                rhs: rhs.type_info(),
1848                            }));
1849                        }
1850                    },
1851                }
1852            };
1853
1854            self.store(out, inline)?;
1855            return Ok(());
1856        };
1857
1858        let mut args = DynGuardedArgs::new((rhs.clone(),));
1859
1860        if let CallResult::Unsupported(lhs) =
1861            self.call_instance_fn(Isolated::None, lhs, &ops.protocol, &mut args, out)?
1862        {
1863            return Err(VmError::new(VmErrorKind::UnsupportedBinaryOperation {
1864                op: ops.protocol.name,
1865                lhs: lhs.type_info(),
1866                rhs: rhs.type_info(),
1867            }));
1868        }
1869
1870        Ok(())
1871    }
1872
1873    #[cfg_attr(feature = "bench", inline(never))]
1874    fn op_assign_arithmetic(
1875        &mut self,
1876        op: InstArithmeticOp,
1877        target: InstTarget,
1878        rhs: Address,
1879    ) -> Result<(), VmError> {
1880        let ops = AssignArithmeticOps::from_op(op);
1881
1882        let fallback = match target_value(&mut self.stack, &self.unit, target, rhs)? {
1883            TargetValue::Same(value) => match value.as_mut() {
1884                Repr::Inline(Inline::Signed(value)) => {
1885                    let out =
1886                        (ops.i64)(*value, *value).ok_or_else(|| (ops.error)(i128::from(*value)))?;
1887                    *value = out;
1888                    return Ok(());
1889                }
1890                Repr::Inline(Inline::Unsigned(value)) => {
1891                    let out =
1892                        (ops.u64)(*value, *value).ok_or_else(|| (ops.error)(i128::from(*value)))?;
1893                    *value = out;
1894                    return Ok(());
1895                }
1896                Repr::Inline(Inline::Float(value)) => {
1897                    let out = (ops.f64)(*value, *value);
1898                    *value = out;
1899                    return Ok(());
1900                }
1901                Repr::Any(..) => TargetFallback::Value(value.clone(), value.clone()),
1902                value => {
1903                    return Err(VmError::new(VmErrorKind::UnsupportedBinaryOperation {
1904                        op: ops.protocol.name,
1905                        lhs: value.type_info(),
1906                        rhs: value.type_info(),
1907                    }));
1908                }
1909            },
1910            TargetValue::Pair(mut lhs, rhs) => match (lhs.as_mut(), rhs.as_ref()) {
1911                (Repr::Inline(Inline::Signed(lhs)), Repr::Inline(rhs)) => {
1912                    let rhs = rhs.as_integer()?;
1913                    let out = (ops.i64)(*lhs, rhs).ok_or_else(|| (ops.error)(i128::from(rhs)))?;
1914                    *lhs = out;
1915                    return Ok(());
1916                }
1917                (Repr::Inline(Inline::Unsigned(lhs)), Repr::Inline(rhs)) => {
1918                    let rhs = rhs.as_integer()?;
1919                    let out = (ops.u64)(*lhs, rhs).ok_or_else(|| (ops.error)(i128::from(rhs)))?;
1920                    *lhs = out;
1921                    return Ok(());
1922                }
1923                (Repr::Inline(Inline::Float(lhs)), Repr::Inline(Inline::Float(rhs))) => {
1924                    let out = (ops.f64)(*lhs, *rhs);
1925                    *lhs = out;
1926                    return Ok(());
1927                }
1928                (Repr::Any(..), _) => TargetFallback::Value(lhs.clone(), rhs.clone()),
1929                (lhs, rhs) => {
1930                    return Err(VmError::new(VmErrorKind::UnsupportedBinaryOperation {
1931                        op: ops.protocol.name,
1932                        lhs: lhs.type_info(),
1933                        rhs: rhs.type_info(),
1934                    }));
1935                }
1936            },
1937            TargetValue::Fallback(fallback) => fallback,
1938        };
1939
1940        self.target_fallback_assign(fallback, &ops.protocol)
1941    }
1942
1943    #[cfg_attr(feature = "bench", inline(never))]
1944    fn op_assign_bitwise(
1945        &mut self,
1946        op: InstBitwiseOp,
1947        target: InstTarget,
1948        rhs: Address,
1949    ) -> Result<(), VmError> {
1950        let ops = AssignBitwiseOps::from_ops(op);
1951
1952        let fallback = match target_value(&mut self.stack, &self.unit, target, rhs)? {
1953            TargetValue::Same(value) => match value.as_mut() {
1954                Repr::Inline(Inline::Unsigned(value)) => {
1955                    let rhs = *value;
1956                    (ops.u64)(value, rhs);
1957                    return Ok(());
1958                }
1959                Repr::Inline(Inline::Signed(value)) => {
1960                    let rhs = *value;
1961                    (ops.i64)(value, rhs);
1962                    return Ok(());
1963                }
1964                Repr::Inline(Inline::Bool(value)) => {
1965                    let rhs = *value;
1966                    (ops.bool)(value, rhs);
1967                    return Ok(());
1968                }
1969                Repr::Any(..) => TargetFallback::Value(value.clone(), value.clone()),
1970                value => {
1971                    return Err(VmError::new(VmErrorKind::UnsupportedBinaryOperation {
1972                        op: ops.protocol.name,
1973                        lhs: value.type_info(),
1974                        rhs: value.type_info(),
1975                    }));
1976                }
1977            },
1978            TargetValue::Pair(mut lhs, rhs) => match (lhs.as_mut(), rhs.as_ref()) {
1979                (Repr::Inline(Inline::Unsigned(lhs)), Repr::Inline(rhs)) => {
1980                    let rhs = rhs.as_integer()?;
1981                    (ops.u64)(lhs, rhs);
1982                    return Ok(());
1983                }
1984                (Repr::Inline(Inline::Signed(lhs)), Repr::Inline(rhs)) => {
1985                    let rhs = rhs.as_integer()?;
1986                    (ops.i64)(lhs, rhs);
1987                    return Ok(());
1988                }
1989                (Repr::Inline(Inline::Bool(lhs)), Repr::Inline(Inline::Bool(rhs))) => {
1990                    (ops.bool)(lhs, *rhs);
1991                    return Ok(());
1992                }
1993                (Repr::Any(..), ..) => TargetFallback::Value(lhs.clone(), rhs.clone()),
1994                (lhs, rhs) => {
1995                    return Err(VmError::new(VmErrorKind::UnsupportedBinaryOperation {
1996                        op: ops.protocol.name,
1997                        lhs: lhs.type_info(),
1998                        rhs: rhs.type_info(),
1999                    }));
2000                }
2001            },
2002            TargetValue::Fallback(fallback) => fallback,
2003        };
2004
2005        self.target_fallback_assign(fallback, &ops.protocol)
2006    }
2007
2008    #[cfg_attr(feature = "bench", inline(never))]
2009    fn op_assign_shift(
2010        &mut self,
2011        op: InstShiftOp,
2012        target: InstTarget,
2013        rhs: Address,
2014    ) -> Result<(), VmError> {
2015        let ops = AssignShiftOps::from_op(op);
2016
2017        let fallback = match target_value(&mut self.stack, &self.unit, target, rhs)? {
2018            TargetValue::Same(value) => match value.as_mut() {
2019                Repr::Inline(Inline::Unsigned(value)) => {
2020                    let shift = u32::try_from(*value).ok().ok_or_else(ops.error)?;
2021                    let out = (ops.u64)(*value, shift).ok_or_else(ops.error)?;
2022                    *value = out;
2023                    return Ok(());
2024                }
2025                Repr::Inline(Inline::Signed(value)) => {
2026                    let shift = u32::try_from(*value).ok().ok_or_else(ops.error)?;
2027                    let out = (ops.i64)(*value, shift).ok_or_else(ops.error)?;
2028                    *value = out;
2029                    return Ok(());
2030                }
2031                Repr::Any(..) => TargetFallback::Value(value.clone(), value.clone()),
2032                value => {
2033                    return Err(VmError::new(VmErrorKind::UnsupportedBinaryOperation {
2034                        op: ops.protocol.name,
2035                        lhs: value.type_info(),
2036                        rhs: value.type_info(),
2037                    }));
2038                }
2039            },
2040            TargetValue::Pair(mut lhs, rhs) => match (lhs.as_mut(), rhs.as_ref()) {
2041                (Repr::Inline(Inline::Unsigned(lhs)), Repr::Inline(rhs)) => {
2042                    let rhs = rhs.as_integer()?;
2043                    let out = (ops.u64)(*lhs, rhs).ok_or_else(ops.error)?;
2044                    *lhs = out;
2045                    return Ok(());
2046                }
2047                (Repr::Inline(Inline::Signed(lhs)), Repr::Inline(rhs)) => {
2048                    let rhs = rhs.as_integer()?;
2049                    let out = (ops.i64)(*lhs, rhs).ok_or_else(ops.error)?;
2050                    *lhs = out;
2051                    return Ok(());
2052                }
2053                (Repr::Any(..), _) => TargetFallback::Value(lhs.clone(), rhs.clone()),
2054                (lhs, rhs) => {
2055                    return Err(VmError::new(VmErrorKind::UnsupportedBinaryOperation {
2056                        op: ops.protocol.name,
2057                        lhs: lhs.type_info(),
2058                        rhs: rhs.type_info(),
2059                    }));
2060                }
2061            },
2062            TargetValue::Fallback(fallback) => fallback,
2063        };
2064
2065        self.target_fallback_assign(fallback, &ops.protocol)
2066    }
2067
2068    /// Perform an index set operation.
2069    #[cfg_attr(feature = "bench", inline(never))]
2070    fn op_index_set(
2071        &mut self,
2072        target: Address,
2073        index: Address,
2074        value: Address,
2075    ) -> Result<(), VmError> {
2076        let target = self.stack.at(target);
2077        let index = self.stack.at(index);
2078        let value = self.stack.at(value);
2079
2080        if let Some(field) = index.try_borrow_ref::<String>()? {
2081            if Self::try_object_slot_index_set(target, &field, value, &mut self.worklist)? {
2082                return Ok(());
2083            }
2084        }
2085
2086        let target = target.clone();
2087        let index = index.clone();
2088        let value = value.clone();
2089
2090        let mut args = DynGuardedArgs::new((&index, &value));
2091
2092        if let CallResult::Unsupported(target) = self.call_instance_fn(
2093            Isolated::None,
2094            target,
2095            &Protocol::INDEX_SET,
2096            &mut args,
2097            Output::discard(),
2098        )? {
2099            return Err(VmError::new(VmErrorKind::UnsupportedIndexSet {
2100                target: target.type_info(),
2101                index: index.type_info(),
2102                value: value.type_info(),
2103            }));
2104        }
2105
2106        Ok(())
2107    }
2108
2109    #[inline]
2110    #[tracing::instrument(skip(self, return_value))]
2111    fn op_return_internal(&mut self, return_value: Value) -> Result<Option<Output>, VmError> {
2112        let (exit, out) = self.pop_call_frame()?;
2113
2114        let out = if let Some(out) = out {
2115            self.store(out, return_value)?;
2116            out
2117        } else {
2118            let addr = self.stack.addr();
2119            self.stack.push(return_value)?;
2120            addr.output()
2121        };
2122
2123        Ok(exit.then_some(out))
2124    }
2125
2126    /// The error for calling a function which neither the unit nor the
2127    /// context has, naming it when a declaration source declared it.
2128    #[cold]
2129    fn missing_function(&self, hash: Hash) -> VmError {
2130        let Some(item) = self.unit.debug_info().and_then(|d| d.declared(hash)) else {
2131            return VmError::new(VmErrorKind::MissingFunction { hash });
2132        };
2133
2134        match item.try_clone() {
2135            Ok(item) => VmError::new(VmErrorKind::MissingDeclaredFunction { item, hash }),
2136            Err(error) => VmError::from(error),
2137        }
2138    }
2139
2140    fn lookup_function_by_hash(&self, hash: Hash) -> Result<Function, VmErrorKind> {
2141        let Some(info) = self.unit.function(&hash) else {
2142            let Some(handler) = self.context.function(&hash) else {
2143                if let Some(item) = self.unit.debug_info().and_then(|d| d.declared(hash)) {
2144                    return Err(VmErrorKind::MissingDeclaredFunction {
2145                        item: item.try_clone()?,
2146                        hash,
2147                    });
2148                }
2149
2150                return Err(VmErrorKind::MissingContextFunction { hash });
2151            };
2152
2153            return Ok(Function::from_handler(handler.clone(), hash));
2154        };
2155
2156        let f = match info {
2157            UnitFn::Offset {
2158                offset, call, args, ..
2159            } => Function::from_vm_offset(
2160                self.context.clone(),
2161                self.unit.clone(),
2162                self.globals.clone(),
2163                *offset,
2164                *call,
2165                *args,
2166                hash,
2167            ),
2168            UnitFn::EmptyStruct { hash } => {
2169                let Some(rtti) = self.unit.lookup_rtti(hash) else {
2170                    return Err(VmErrorKind::MissingRtti { hash: *hash });
2171                };
2172
2173                Function::from_unit_struct(rtti.clone())
2174            }
2175            UnitFn::TupleStruct { hash, args } => {
2176                let Some(rtti) = self.unit.lookup_rtti(hash) else {
2177                    return Err(VmErrorKind::MissingRtti { hash: *hash });
2178                };
2179
2180                Function::from_tuple_struct(rtti.clone(), *args)
2181            }
2182        };
2183
2184        Ok(f)
2185    }
2186
2187    #[cfg_attr(feature = "bench", inline(never))]
2188    fn op_return(&mut self, addr: Address) -> Result<Option<Output>, VmError> {
2189        let return_value = self.stack.at(addr).clone();
2190        self.op_return_internal(return_value)
2191    }
2192
2193    #[cfg_attr(feature = "bench", inline(never))]
2194    #[tracing::instrument(skip(self))]
2195    fn op_return_unit(&mut self) -> Result<Option<Output>, VmError> {
2196        let (exit, out) = self.pop_call_frame()?;
2197
2198        let out = if let Some(out) = out {
2199            self.store(out, ())?;
2200            out
2201        } else {
2202            let addr = self.stack.addr();
2203            self.stack.push(())?;
2204            addr.output()
2205        };
2206
2207        Ok(exit.then_some(out))
2208    }
2209
2210    #[cfg_attr(feature = "bench", inline(never))]
2211    fn op_load_instance_fn(
2212        &mut self,
2213        addr: Address,
2214        hash: Hash,
2215        out: Output,
2216    ) -> Result<(), VmError> {
2217        let instance = self.stack.at(addr);
2218        let ty = instance.type_hash();
2219        let hash = Hash::associated_function(ty, hash);
2220        self.store(out, || Type::new(hash))?;
2221        Ok(())
2222    }
2223
2224    /// Perform an index get operation.
2225    #[cfg_attr(feature = "bench", inline(never))]
2226    fn op_index_get(
2227        &mut self,
2228        target: Address,
2229        index: Address,
2230        out: Output,
2231    ) -> Result<(), VmError> {
2232        let value = 'store: {
2233            let index = self.stack.at(index);
2234            let target = self.stack.at(target);
2235
2236            match index.as_ref() {
2237                Repr::Inline(inline) => {
2238                    let index = inline.as_integer::<usize>()?;
2239
2240                    if let Some(value) = Self::try_tuple_like_index_get(target, index)? {
2241                        break 'store value;
2242                    }
2243                }
2244                Repr::Any(value) => {
2245                    if let Some(index) = value.try_borrow_ref::<String>()? {
2246                        if let Some(value) =
2247                            Self::try_object_like_index_get(target, index.as_str())?
2248                        {
2249                            break 'store value;
2250                        }
2251                    }
2252                }
2253                _ => {}
2254            }
2255
2256            let target = target.clone();
2257            let index = index.clone();
2258
2259            let mut args = DynGuardedArgs::new((&index,));
2260
2261            if let CallResult::Unsupported(target) =
2262                self.call_instance_fn(Isolated::None, target, &Protocol::INDEX_GET, &mut args, out)?
2263            {
2264                return Err(VmError::new(VmErrorKind::UnsupportedIndexGet {
2265                    target: target.type_info(),
2266                    index: index.type_info(),
2267                }));
2268            }
2269
2270            return Ok(());
2271        };
2272
2273        self.store(out, value)?;
2274        Ok(())
2275    }
2276
2277    /// Perform an index get operation specialized for tuples.
2278    #[cfg_attr(feature = "bench", inline(never))]
2279    fn op_tuple_index_set(
2280        &mut self,
2281        target: Address,
2282        index: usize,
2283        value: Address,
2284    ) -> Result<(), VmError> {
2285        let value = self.stack.at(value);
2286        let target = self.stack.at(target);
2287
2288        if Self::try_tuple_like_index_set(target, index, value, &mut self.worklist)? {
2289            return Ok(());
2290        }
2291
2292        Err(VmError::new(VmErrorKind::UnsupportedTupleIndexSet {
2293            target: target.type_info(),
2294        }))
2295    }
2296
2297    /// Perform an index get operation specialized for tuples.
2298    #[cfg_attr(feature = "bench", inline(never))]
2299    fn op_tuple_index_get_at(
2300        &mut self,
2301        addr: Address,
2302        index: usize,
2303        out: Output,
2304    ) -> Result<(), VmError> {
2305        let value = self.stack.at(addr);
2306
2307        if let Some(value) = Self::try_tuple_like_index_get(value, index)? {
2308            self.store(out, value)?;
2309            return Ok(());
2310        }
2311
2312        let value = value.clone();
2313
2314        if let CallResult::Unsupported(value) =
2315            self.call_index_fn(&Protocol::GET, value, index, &mut (), out)?
2316        {
2317            return Err(VmError::new(VmErrorKind::UnsupportedTupleIndexGet {
2318                target: value.type_info(),
2319                index,
2320            }));
2321        }
2322
2323        Ok(())
2324    }
2325
2326    /// Perform a specialized index set operation on an object.
2327    #[cfg_attr(feature = "bench", inline(never))]
2328    fn op_object_index_set(
2329        &mut self,
2330        target: Address,
2331        slot: usize,
2332        value: Address,
2333    ) -> Result<(), VmError> {
2334        let target = self.stack.at(target);
2335        let value = self.stack.at(value);
2336
2337        let Some(field) = self.unit.lookup_string(slot) else {
2338            return Err(VmError::new(VmErrorKind::MissingStaticString { slot }));
2339        };
2340
2341        if Self::try_object_slot_index_set(target, field, value, &mut self.worklist)? {
2342            return Ok(());
2343        }
2344
2345        let target = target.clone();
2346        let value = value.clone();
2347
2348        let hash = field.hash();
2349
2350        let mut args = DynGuardedArgs::new((value,));
2351
2352        let result =
2353            self.call_field_fn(&Protocol::SET, target, hash, &mut args, Output::discard())?;
2354
2355        if let CallResult::Unsupported(target) = result {
2356            let Some(field) = self.unit.lookup_string(slot) else {
2357                return Err(VmError::new(VmErrorKind::MissingStaticString { slot }));
2358            };
2359
2360            return Err(VmError::new(VmErrorKind::UnsupportedObjectSlotIndexSet {
2361                target: target.type_info(),
2362                field: field.clone(),
2363            }));
2364        };
2365
2366        Ok(())
2367    }
2368
2369    /// Perform a specialized index get operation on an object.
2370    #[cfg_attr(feature = "bench", inline(never))]
2371    fn op_object_index_get_at(
2372        &mut self,
2373        addr: Address,
2374        slot: usize,
2375        out: Output,
2376    ) -> Result<(), VmError> {
2377        let target = self.stack.at(addr);
2378
2379        let Some(index) = self.unit.lookup_string(slot) else {
2380            return Err(VmError::new(VmErrorKind::MissingStaticString { slot }));
2381        };
2382
2383        match target.as_ref() {
2384            Repr::Dynamic(data) if matches!(data.rtti().kind, RttiKind::Struct) => {
2385                let Some(value) = data.get_field_ref(index.as_str())? else {
2386                    return Err(VmError::new(VmErrorKind::ObjectIndexMissing { slot }));
2387                };
2388
2389                let value = value.clone();
2390                self.store(out, value)?;
2391                return Ok(());
2392            }
2393            Repr::Any(value) if value.type_hash() == Object::HASH => {
2394                let object = value.borrow_ref::<Object>()?;
2395
2396                let Some(value) = object.get(index.as_str()) else {
2397                    return Err(VmError::new(VmErrorKind::ObjectIndexMissing { slot }));
2398                };
2399
2400                let value = value.clone();
2401                self.store(out, value)?;
2402                return Ok(());
2403            }
2404            Repr::Any(..) => {}
2405            target => {
2406                return Err(VmError::new(VmErrorKind::UnsupportedObjectSlotIndexGet {
2407                    target: target.type_info(),
2408                    field: index.clone(),
2409                }));
2410            }
2411        }
2412
2413        let target = target.clone();
2414
2415        if let CallResult::Unsupported(target) =
2416            self.call_field_fn(&Protocol::GET, target, index.hash(), &mut (), out)?
2417        {
2418            let Some(field) = self.unit.lookup_string(slot) else {
2419                return Err(VmError::new(VmErrorKind::MissingStaticString { slot }));
2420            };
2421
2422            return Err(VmError::new(VmErrorKind::UnsupportedObjectSlotIndexGet {
2423                target: target.type_info(),
2424                field: field.clone(),
2425            }));
2426        }
2427
2428        Ok(())
2429    }
2430
2431    /// Operation to allocate an object.
2432    #[cfg_attr(feature = "bench", inline(never))]
2433    fn op_object(&mut self, addr: Address, slot: usize, out: Output) -> Result<(), VmError> {
2434        let Some(keys) = self.unit.lookup_object_keys(slot) else {
2435            return Err(VmError::new(VmErrorKind::MissingStaticObjectKeys { slot }));
2436        };
2437
2438        let mut object = Object::with_capacity(keys.len())?;
2439        let values = self.stack.slice_at_mut(addr, keys.len())?;
2440
2441        for (key, value) in keys.iter().zip(values) {
2442            let key = String::try_from(key.as_str())?;
2443            object.insert(key, take(value))?;
2444        }
2445
2446        self.store(out, object)?;
2447        Ok(())
2448    }
2449
2450    /// Operation to allocate an object.
2451    #[cfg_attr(feature = "bench", inline(never))]
2452    fn op_range(&mut self, range: InstRange, out: Output) -> Result<(), VmError> {
2453        let value = match range {
2454            InstRange::RangeFrom { start } => {
2455                let s = self.stack.at(start).clone();
2456                Value::new(RangeFrom::new(s.clone()))?
2457            }
2458            InstRange::RangeFull => Value::new(RangeFull::new())?,
2459            InstRange::RangeInclusive { start, end } => {
2460                let s = self.stack.at(start).clone();
2461                let e = self.stack.at(end).clone();
2462                Value::new(RangeInclusive::new(s.clone(), e.clone()))?
2463            }
2464            InstRange::RangeToInclusive { end } => {
2465                let e = self.stack.at(end).clone();
2466                Value::new(RangeToInclusive::new(e.clone()))?
2467            }
2468            InstRange::RangeTo { end } => {
2469                let e = self.stack.at(end).clone();
2470                Value::new(RangeTo::new(e.clone()))?
2471            }
2472            InstRange::Range { start, end } => {
2473                let s = self.stack.at(start).clone();
2474                let e = self.stack.at(end).clone();
2475                Value::new(Range::new(s.clone(), e.clone()))?
2476            }
2477        };
2478
2479        self.store(out, value)?;
2480        Ok(())
2481    }
2482
2483    /// Operation to allocate an object struct.
2484    #[cfg_attr(feature = "bench", inline(never))]
2485    fn op_struct(&mut self, addr: Address, hash: Hash, out: Output) -> Result<(), VmError> {
2486        let Some(rtti) = self.unit.lookup_rtti(&hash) else {
2487            return Err(VmError::new(VmErrorKind::MissingRtti { hash }));
2488        };
2489
2490        let values = self.stack.slice_at_mut(addr, rtti.fields.len())?;
2491        let value = AnySequence::new(rtti.clone(), values.iter_mut().map(take))?;
2492        self.store(out, value)?;
2493        Ok(())
2494    }
2495
2496    /// Operation to allocate a constant value from an array of values.
2497    #[cfg_attr(feature = "bench", inline(never))]
2498    fn op_const_construct(
2499        &mut self,
2500        addr: Address,
2501        hash: Hash,
2502        count: usize,
2503        out: Output,
2504    ) -> Result<(), VmError> {
2505        let values = self.stack.slice_at_mut(addr, count)?;
2506
2507        let Some(construct) = self.context.construct(&hash) else {
2508            return Err(VmError::new(VmErrorKind::MissingConstantConstructor {
2509                hash,
2510            }));
2511        };
2512
2513        let value = construct.runtime_construct(values)?;
2514        self.store(out, value)?;
2515        Ok(())
2516    }
2517
2518    #[cfg_attr(feature = "bench", inline(never))]
2519    fn op_string(&mut self, slot: usize, out: Output) -> Result<(), VmError> {
2520        let Some(string) = self.unit.lookup_string(slot) else {
2521            return Err(VmError::new(VmErrorKind::MissingStaticString { slot }));
2522        };
2523
2524        // The string is borrowed from the unit, so the stack and the worklist
2525        // are reached as the separate fields they are.
2526        self.stack
2527            .store_with(out, string.as_str(), &mut self.worklist)?;
2528        Ok(())
2529    }
2530
2531    /// Resolve the name of a static slot from debug information, if it's
2532    /// available, so that diagnostics can refer to it by name.
2533    fn global_name(&self, slot: usize) -> Option<ItemBuf> {
2534        let debug = self.unit.debug_info()?;
2535        debug.global(slot)?.path.try_clone().ok()
2536    }
2537
2538    #[cfg_attr(feature = "bench", inline(never))]
2539    fn op_global_get(&mut self, slot: usize, out: Output) -> Result<(), VmError> {
2540        let value = match self.globals.try_get_at(slot) {
2541            Ok(Some(value)) => value,
2542            Ok(None) => {
2543                // The slot exists but has never been assigned, so evaluate the
2544                // initializer declared for it, if it has one.
2545                let Some(init) = self.unit.global_init(slot) else {
2546                    return Err(VmError::new(VmErrorKind::UninitializedGlobal {
2547                        slot,
2548                        name: self.global_name(slot),
2549                    }));
2550                };
2551
2552                let cx = UnitConstContext {
2553                    context: &*self.context,
2554                    unit: &*self.unit,
2555                };
2556
2557                let value = init.to_value_with(&cx)?;
2558                self.globals.set_at(slot, value.clone()).map_err(|_| {
2559                    VmError::new(VmErrorKind::BadGlobalSlot {
2560                        slot,
2561                        name: self.global_name(slot),
2562                    })
2563                })?;
2564                value
2565            }
2566            Err(..) => {
2567                let name = self.global_name(slot);
2568
2569                return Err(VmError::new(if self.globals.is_configured() {
2570                    VmErrorKind::BadGlobalSlot { slot, name }
2571                } else {
2572                    VmErrorKind::MissingGlobals { slot, name }
2573                }));
2574            }
2575        };
2576
2577        self.store(out, value)?;
2578        Ok(())
2579    }
2580
2581    #[cfg_attr(feature = "bench", inline(never))]
2582    fn op_global_set(&mut self, slot: usize, value: Address) -> Result<(), VmError> {
2583        let value = self.stack.at(value).clone();
2584
2585        self.globals.set_at(slot, value).map_err(|_| {
2586            let name = self.global_name(slot);
2587
2588            VmError::new(if self.globals.is_configured() {
2589                VmErrorKind::BadGlobalSlot { slot, name }
2590            } else {
2591                VmErrorKind::MissingGlobals { slot, name }
2592            })
2593        })?;
2594
2595        Ok(())
2596    }
2597
2598    #[cfg_attr(feature = "bench", inline(never))]
2599    fn op_bytes(&mut self, slot: usize, out: Output) -> Result<(), VmError> {
2600        let Some(bytes) = self.unit.lookup_bytes(slot) else {
2601            return Err(VmError::new(VmErrorKind::MissingStaticBytes { slot }));
2602        };
2603
2604        // As above, the bytes are borrowed from the unit.
2605        self.stack.store_with(out, bytes, &mut self.worklist)?;
2606        Ok(())
2607    }
2608
2609    /// Optimize operation to perform string concatenation.
2610    #[cfg_attr(feature = "bench", inline(never))]
2611    fn op_string_concat(
2612        &mut self,
2613        addr: Address,
2614        len: usize,
2615        size_hint: usize,
2616        out: Output,
2617    ) -> Result<(), VmError> {
2618        let values = self.stack.slice_at(addr, len)?;
2619        let values = values.iter().cloned().try_collect::<alloc::Vec<_>>()?;
2620
2621        // The hint is read from the unit, which is not always this
2622        // compiler's own estimate - a `.rnc` is loaded from disk.
2623        let mut s = String::try_with_capacity(hint_capacity(size_hint))?;
2624
2625        Formatter::format_with(&mut s, |f| {
2626            for value in values {
2627                value.display_fmt_with(f, &mut *self)?;
2628            }
2629
2630            Ok::<_, VmError>(())
2631        })?;
2632
2633        self.store(out, s)?;
2634        Ok(())
2635    }
2636
2637    /// Push a format specification onto the stack.
2638    #[cfg_attr(feature = "bench", inline(never))]
2639    fn op_format(&mut self, addr: Address, spec: FormatSpec, out: Output) -> Result<(), VmError> {
2640        let value = self.stack.at(addr).clone();
2641        self.store(out, || Format { value, spec })?;
2642        Ok(())
2643    }
2644
2645    /// Perform the try operation on the given stack location.
2646    #[cfg_attr(feature = "bench", inline(never))]
2647    fn op_try(&mut self, addr: Address, out: Output) -> Result<Option<Output>, VmError> {
2648        let result = 'out: {
2649            let value = {
2650                let value = self.stack.at(addr);
2651
2652                if let Repr::Any(value) = value.as_ref() {
2653                    match value.type_hash() {
2654                        Result::<Value, Value>::HASH => {
2655                            let result = value.borrow_ref::<Result<Value, Value>>()?;
2656                            break 'out result::result_try(&result)?;
2657                        }
2658                        Option::<Value>::HASH => {
2659                            let option = value.borrow_ref::<Option<Value>>()?;
2660                            break 'out option::option_try(&option)?;
2661                        }
2662                        _ => {}
2663                    }
2664                }
2665
2666                value.clone()
2667            };
2668
2669            match self.try_call_protocol_fn(&Protocol::TRY, value, &mut ())? {
2670                CallResultOnly::Ok(value) => ControlFlow::from_value(value)?,
2671                CallResultOnly::Unsupported(target) => {
2672                    return Err(VmError::new(VmErrorKind::UnsupportedTryOperand {
2673                        actual: target.type_info(),
2674                    }));
2675                }
2676            }
2677        };
2678
2679        match result {
2680            ControlFlow::Continue(value) => {
2681                self.store(out, value)?;
2682                Ok(None)
2683            }
2684            ControlFlow::Break(error) => Ok(self.op_return_internal(error)?),
2685        }
2686    }
2687
2688    #[cfg_attr(feature = "bench", inline(never))]
2689    fn op_eq_character(&mut self, addr: Address, value: char, out: Output) -> Result<(), VmError> {
2690        let v = self.stack.at(addr);
2691
2692        let is_match = match v.as_inline() {
2693            Some(Inline::Char(actual)) => *actual == value,
2694            _ => false,
2695        };
2696
2697        self.store(out, is_match)?;
2698        Ok(())
2699    }
2700
2701    #[cfg_attr(feature = "bench", inline(never))]
2702    fn op_eq_unsigned(&mut self, addr: Address, value: u64, out: Output) -> Result<(), VmError> {
2703        let v = self.stack.at(addr);
2704
2705        let is_match = match v.as_inline() {
2706            Some(Inline::Unsigned(actual)) => *actual == value,
2707            _ => false,
2708        };
2709
2710        self.store(out, is_match)?;
2711        Ok(())
2712    }
2713
2714    #[cfg_attr(feature = "bench", inline(never))]
2715    fn op_eq_signed(&mut self, addr: Address, value: i64, out: Output) -> Result<(), VmError> {
2716        let is_match = match self.stack.at(addr).as_inline() {
2717            Some(Inline::Signed(actual)) => *actual == value,
2718            _ => false,
2719        };
2720
2721        self.store(out, is_match)?;
2722        Ok(())
2723    }
2724
2725    #[cfg_attr(feature = "bench", inline(never))]
2726    fn op_eq_bool(&mut self, addr: Address, value: bool, out: Output) -> Result<(), VmError> {
2727        let v = self.stack.at(addr);
2728
2729        let is_match = match v.as_inline() {
2730            Some(Inline::Bool(actual)) => *actual == value,
2731            _ => false,
2732        };
2733
2734        self.store(out, is_match)?;
2735        Ok(())
2736    }
2737
2738    /// Test if the top of stack is equal to the string at the given static
2739    /// string slot.
2740    #[cfg_attr(feature = "bench", inline(never))]
2741    fn op_eq_string(&mut self, addr: Address, slot: usize, out: Output) -> Result<(), VmError> {
2742        let v = self.stack.at(addr);
2743
2744        let is_match = 'out: {
2745            let Some(actual) = v.try_borrow_ref::<String>()? else {
2746                break 'out false;
2747            };
2748
2749            let Some(string) = self.unit.lookup_string(slot) else {
2750                return Err(VmError::new(VmErrorKind::MissingStaticString { slot }));
2751            };
2752
2753            actual.as_str() == string.as_str()
2754        };
2755
2756        self.store(out, is_match)?;
2757        Ok(())
2758    }
2759
2760    /// Test if the top of stack is equal to the string at the given static
2761    /// bytes slot.
2762    #[cfg_attr(feature = "bench", inline(never))]
2763    fn op_eq_bytes(&mut self, addr: Address, slot: usize, out: Output) -> Result<(), VmError> {
2764        let v = self.stack.at(addr);
2765
2766        let is_match = 'out: {
2767            let Some(value) = v.try_borrow_ref::<Bytes>()? else {
2768                break 'out false;
2769            };
2770
2771            let Some(bytes) = self.unit.lookup_bytes(slot) else {
2772                return Err(VmError::new(VmErrorKind::MissingStaticBytes { slot }));
2773            };
2774
2775            value.as_slice() == bytes
2776        };
2777
2778        self.store(out, is_match)?;
2779        Ok(())
2780    }
2781
2782    #[cfg_attr(feature = "bench", inline(never))]
2783    fn op_match_type(
2784        &mut self,
2785        hash: Hash,
2786        variant_hash: Hash,
2787        addr: Address,
2788        out: Output,
2789    ) -> Result<(), VmError> {
2790        let value = self.stack.at(addr);
2791
2792        let type_hash = value.type_hash();
2793
2794        let is_match = 'out: {
2795            if type_hash != hash {
2796                break 'out false;
2797            }
2798
2799            // No variant to check.
2800            if variant_hash == Hash::EMPTY {
2801                break 'out true;
2802            }
2803
2804            match value.as_ref() {
2805                Repr::Inline(Inline::Ordering(ordering)) => {
2806                    break 'out cmp::ordering_is_variant(*ordering, variant_hash);
2807                }
2808                Repr::Dynamic(value) => {
2809                    break 'out value.rtti().is(hash, variant_hash);
2810                }
2811                Repr::Any(any) => match hash {
2812                    Result::<Value, Value>::HASH => {
2813                        let result = any.borrow_ref::<Result<Value, Value>>()?;
2814                        break 'out result::is_variant(&result, variant_hash);
2815                    }
2816                    Option::<Value>::HASH => {
2817                        let option = any.borrow_ref::<Option<Value>>()?;
2818                        break 'out option::is_variant(&option, variant_hash);
2819                    }
2820                    _ => {}
2821                },
2822                _ => break 'out true,
2823            }
2824
2825            let value = value.clone();
2826
2827            match self.try_call_protocol_fn(
2828                &Protocol::IS_VARIANT,
2829                value,
2830                &mut Some((variant_hash,)),
2831            )? {
2832                CallResultOnly::Ok(value) => bool::from_value(value)?,
2833                CallResultOnly::Unsupported(..) => false,
2834            }
2835        };
2836
2837        self.store(out, is_match)?;
2838        Ok(())
2839    }
2840
2841    #[cfg_attr(feature = "bench", inline(never))]
2842    fn op_match_sequence(
2843        &mut self,
2844        hash: Hash,
2845        len: usize,
2846        exact: bool,
2847        addr: Address,
2848        out: Output,
2849    ) -> Result<(), VmError> {
2850        let value = self.stack.at(addr);
2851
2852        let type_hash = value.type_hash();
2853
2854        let is_match = 'out: {
2855            if type_hash != hash {
2856                break 'out false;
2857            }
2858
2859            let actual = match value.as_ref() {
2860                Repr::Inline(Inline::Unit) => 0,
2861                Repr::Any(any) => match type_hash {
2862                    runtime::Vec::HASH => any.borrow_ref::<runtime::Vec>()?.len(),
2863                    runtime::OwnedTuple::HASH => any.borrow_ref::<runtime::OwnedTuple>()?.len(),
2864                    _ => break 'out false,
2865                },
2866                _ => break 'out false,
2867            };
2868
2869            actual >= len && (!exact || actual == len)
2870        };
2871
2872        self.store(out, is_match)?;
2873        Ok(())
2874    }
2875
2876    #[cfg_attr(feature = "bench", inline(never))]
2877    fn op_match_object(
2878        &mut self,
2879        slot: usize,
2880        exact: bool,
2881        addr: Address,
2882        out: Output,
2883    ) -> Result<(), VmError> {
2884        let is_match = 'is_match: {
2885            let Some(object) = self.stack.at(addr).try_borrow_ref::<Object>()? else {
2886                break 'is_match false;
2887            };
2888
2889            let Some(keys) = self.unit.lookup_object_keys(slot) else {
2890                return Err(VmError::new(VmErrorKind::MissingStaticObjectKeys { slot }));
2891            };
2892
2893            if object.len() < keys.len() || (exact && object.len() != keys.len()) {
2894                break 'is_match false;
2895            }
2896
2897            for key in keys {
2898                if !object.contains_key(key.as_str()) {
2899                    break 'is_match false;
2900                }
2901            }
2902
2903            true
2904        };
2905
2906        self.store(out, is_match)?;
2907        Ok(())
2908    }
2909
2910    /// Load a function as a value onto the stack.
2911    #[cfg_attr(feature = "bench", inline(never))]
2912    fn op_load_fn(&mut self, hash: Hash, out: Output) -> Result<(), VmError> {
2913        let function = self.lookup_function_by_hash(hash)?;
2914        self.store(out, function)?;
2915        Ok(())
2916    }
2917
2918    /// Construct a closure on the top of the stack.
2919    #[cfg_attr(feature = "bench", inline(never))]
2920    fn op_closure(
2921        &mut self,
2922        hash: Hash,
2923        addr: Address,
2924        count: usize,
2925        out: Output,
2926    ) -> Result<(), VmError> {
2927        let Some(UnitFn::Offset {
2928            offset,
2929            call,
2930            args,
2931            captures: Some(captures),
2932        }) = self.unit.function(&hash)
2933        else {
2934            return Err(VmError::new(VmErrorKind::MissingFunction { hash }));
2935        };
2936
2937        if *captures != count {
2938            return Err(VmError::new(VmErrorKind::BadEnvironmentCount {
2939                expected: *captures,
2940                actual: count,
2941            }));
2942        }
2943
2944        let environment = self.stack.slice_at(addr, count)?;
2945        let environment = environment
2946            .iter()
2947            .cloned()
2948            .try_collect::<alloc::Vec<Value>>()?;
2949        let environment = environment.try_into_boxed_slice()?;
2950
2951        let function = Function::from_vm_closure(
2952            self.context.clone(),
2953            self.unit.clone(),
2954            self.globals.clone(),
2955            *offset,
2956            *call,
2957            *args,
2958            environment,
2959            hash,
2960        );
2961
2962        self.store(out, function)?;
2963        Ok(())
2964    }
2965
2966    /// Implementation of a function call.
2967    #[cfg_attr(feature = "bench", inline(never))]
2968    fn op_call(
2969        &mut self,
2970        hash: Hash,
2971        addr: Address,
2972        args: usize,
2973        out: Output,
2974    ) -> Result<(), VmError> {
2975        let Some(info) = self.unit.function(&hash) else {
2976            let Some(handler) = self.context.function(&hash) else {
2977                return Err(self.missing_function(hash));
2978            };
2979
2980            handler.call(&mut self.stack, addr, args, out)?;
2981            return Ok(());
2982        };
2983
2984        match info {
2985            UnitFn::Offset {
2986                offset,
2987                call,
2988                args: expected,
2989                ..
2990            } => {
2991                check_args(args, *expected)?;
2992                self.call_offset_fn(*offset, *call, addr, args, Isolated::None, out)?;
2993            }
2994            UnitFn::EmptyStruct { hash } => {
2995                check_args(args, 0)?;
2996
2997                let Some(rtti) = self.unit.lookup_rtti(hash) else {
2998                    return Err(VmError::new(VmErrorKind::MissingRtti { hash: *hash }));
2999                };
3000
3001                // As above, the type information is borrowed from the unit.
3002                self.stack.store_with(
3003                    out,
3004                    || Value::empty_struct(rtti.clone()),
3005                    &mut self.worklist,
3006                )?;
3007            }
3008            UnitFn::TupleStruct {
3009                hash,
3010                args: expected,
3011            } => {
3012                check_args(args, *expected)?;
3013
3014                let Some(rtti) = self.unit.lookup_rtti(hash) else {
3015                    return Err(VmError::new(VmErrorKind::MissingRtti { hash: *hash }));
3016                };
3017
3018                let tuple = self.stack.slice_at_mut(addr, args)?;
3019                let data = tuple.iter_mut().map(take);
3020                let value = AnySequence::new(rtti.clone(), data)?;
3021                self.store(out, value)?;
3022            }
3023        }
3024
3025        Ok(())
3026    }
3027
3028    /// Call a function at the given offset with the given number of arguments.
3029    #[cfg_attr(feature = "bench", inline(never))]
3030    fn op_call_offset(
3031        &mut self,
3032        offset: usize,
3033        call: Call,
3034        addr: Address,
3035        args: usize,
3036        out: Output,
3037    ) -> Result<(), VmError> {
3038        self.call_offset_fn(offset, call, addr, args, Isolated::None, out)?;
3039        Ok(())
3040    }
3041
3042    #[cfg_attr(feature = "bench", inline(never))]
3043    fn op_call_associated(
3044        &mut self,
3045        hash: Hash,
3046        addr: Address,
3047        args: usize,
3048        out: Output,
3049    ) -> Result<(), VmError> {
3050        let instance = self.stack.at(addr);
3051        let type_hash = instance.type_hash();
3052        let hash = Hash::associated_function(type_hash, hash);
3053
3054        if let Some(handler) = self.context.function(&hash) {
3055            self.called_function_hook(hash)?;
3056            handler.call(&mut self.stack, addr, args, out)?;
3057            return Ok(());
3058        }
3059
3060        if let Some(UnitFn::Offset {
3061            offset,
3062            call,
3063            args: expected,
3064            ..
3065        }) = self.unit.function(&hash)
3066        {
3067            self.called_function_hook(hash)?;
3068            check_args(args, *expected)?;
3069            self.call_offset_fn(*offset, *call, addr, args, Isolated::None, out)?;
3070            return Ok(());
3071        }
3072
3073        Err(VmError::new(VmErrorKind::MissingInstanceFunction {
3074            instance: instance.type_info(),
3075            hash,
3076        }))
3077    }
3078
3079    #[cfg_attr(feature = "bench", inline(never))]
3080    #[tracing::instrument(skip(self))]
3081    fn op_call_fn(
3082        &mut self,
3083        function: Address,
3084        addr: Address,
3085        args: usize,
3086        out: Output,
3087    ) -> Result<Option<VmHalt>, VmError> {
3088        let function = self.stack.at(function);
3089
3090        match function.as_ref() {
3091            Repr::Inline(Inline::Type(ty)) => {
3092                self.op_call(ty.into_hash(), addr, args, out)?;
3093                Ok(None)
3094            }
3095            Repr::Any(value) if value.type_hash() == Function::HASH => {
3096                let value = value.clone();
3097                let f = value.borrow_ref::<Function>()?;
3098                f.call_with_vm(self, addr, args, out)
3099            }
3100            value => Err(VmError::new(VmErrorKind::UnsupportedCallFn {
3101                actual: value.type_info(),
3102            })),
3103        }
3104    }
3105
3106    #[cfg_attr(feature = "bench", inline(never))]
3107    fn op_iter_next(&mut self, addr: Address, jump: usize, out: Output) -> Result<(), VmError> {
3108        let value = self.stack.at(addr);
3109
3110        let some = match value.as_ref() {
3111            Repr::Any(value) => match value.type_hash() {
3112                Option::<Value>::HASH => {
3113                    let option = value.borrow_ref::<Option<Value>>()?;
3114
3115                    let Some(some) = &*option else {
3116                        self.ip = self.unit.translate(jump)?;
3117                        return Ok(());
3118                    };
3119
3120                    some.clone()
3121                }
3122                _ => {
3123                    return Err(VmError::new(VmErrorKind::UnsupportedIterNextOperand {
3124                        actual: value.type_info(),
3125                    }));
3126                }
3127            },
3128            actual => {
3129                return Err(VmError::new(VmErrorKind::UnsupportedIterNextOperand {
3130                    actual: actual.type_info(),
3131                }));
3132            }
3133        };
3134
3135        self.store(out, some)?;
3136        Ok(())
3137    }
3138
3139    /// Call the provided closure within the context of this virtual machine.
3140    ///
3141    /// This allows for calling protocol function helpers like
3142    /// [Value::display_fmt] which requires access to a virtual machine.
3143    ///
3144    /// ```no_run
3145    /// use rune::{Value, Vm};
3146    /// use rune::runtime::{Formatter, VmError};
3147    ///
3148    /// fn use_with(vm: &Vm, output: &Value, f: &mut Formatter) -> Result<(), VmError> {
3149    ///     vm.with(|| output.display_fmt(f))?;
3150    ///     Ok(())
3151    /// }
3152    /// ```
3153    pub fn with<F, T>(&self, f: F) -> T
3154    where
3155        F: FnOnce() -> T,
3156    {
3157        let _guard = runtime::env::Guard::new(
3158            self.context.clone(),
3159            self.unit.clone(),
3160            self.globals.clone(),
3161            None,
3162        );
3163        f()
3164    }
3165
3166    /// Evaluate a single instruction.
3167    pub(crate) fn run(
3168        &mut self,
3169        diagnostics: Option<&mut dyn VmDiagnostics>,
3170    ) -> Result<VmHalt, VmError> {
3171        let mut vm_diagnostics_obj;
3172
3173        let diagnostics = match diagnostics {
3174            Some(diagnostics) => {
3175                vm_diagnostics_obj = VmDiagnosticsObj::new(diagnostics);
3176                Some(NonNull::from(&mut vm_diagnostics_obj))
3177            }
3178            None => None,
3179        };
3180
3181        // NB: set up environment so that native function can access context and
3182        // unit.
3183        let _guard = runtime::env::Guard::new(
3184            self.context.clone(),
3185            self.unit.clone(),
3186            self.globals.clone(),
3187            diagnostics,
3188        );
3189
3190        loop {
3191            if !budget::take() {
3192                return Ok(VmHalt::Limited);
3193            }
3194
3195            let Some((inst, inst_len)) = self.unit.instruction_at(self.ip)? else {
3196                return Err(VmError::new(VmErrorKind::IpOutOfBounds {
3197                    ip: self.ip,
3198                    length: self.unit.instructions().end(),
3199                }));
3200            };
3201
3202            tracing::trace!(ip = ?self.ip, ?inst);
3203
3204            self.ip = self.ip.wrapping_add(inst_len);
3205            self.last_ip_len = inst_len as u8;
3206
3207            match inst.kind {
3208                inst::Kind::Allocate { size } => {
3209                    self.op_allocate(size)?;
3210                }
3211                inst::Kind::Not { addr, out } => {
3212                    self.op_not(addr, out)?;
3213                }
3214                inst::Kind::Neg { addr, out } => {
3215                    self.op_neg(addr, out)?;
3216                }
3217                inst::Kind::Closure {
3218                    hash,
3219                    addr,
3220                    count,
3221                    out,
3222                } => {
3223                    self.op_closure(hash, addr, count, out)?;
3224                }
3225                inst::Kind::Call {
3226                    hash,
3227                    addr,
3228                    args,
3229                    out,
3230                } => {
3231                    self.op_call(hash, addr, args, out)?;
3232                }
3233                inst::Kind::CallOffset {
3234                    offset,
3235                    call,
3236                    addr,
3237                    args,
3238                    out,
3239                } => {
3240                    self.op_call_offset(offset, call, addr, args, out)?;
3241                }
3242                inst::Kind::CallAssociated {
3243                    hash,
3244                    addr,
3245                    args,
3246                    out,
3247                } => {
3248                    self.op_call_associated(hash, addr, args, out)?;
3249                }
3250                inst::Kind::CallFn {
3251                    function,
3252                    addr,
3253                    args,
3254                    out,
3255                } => {
3256                    if let Some(reason) = self.op_call_fn(function, addr, args, out)? {
3257                        return Ok(reason);
3258                    }
3259                }
3260                inst::Kind::LoadInstanceFn { addr, hash, out } => {
3261                    self.op_load_instance_fn(addr, hash, out)?;
3262                }
3263                inst::Kind::IndexGet { target, index, out } => {
3264                    self.op_index_get(target, index, out)?;
3265                }
3266                inst::Kind::TupleIndexSet {
3267                    target,
3268                    index,
3269                    value,
3270                } => {
3271                    self.op_tuple_index_set(target, index, value)?;
3272                }
3273                inst::Kind::TupleIndexGetAt { addr, index, out } => {
3274                    self.op_tuple_index_get_at(addr, index, out)?;
3275                }
3276                inst::Kind::ObjectIndexSet {
3277                    target,
3278                    slot,
3279                    value,
3280                } => {
3281                    self.op_object_index_set(target, slot, value)?;
3282                }
3283                inst::Kind::ObjectIndexGetAt { addr, slot, out } => {
3284                    self.op_object_index_get_at(addr, slot, out)?;
3285                }
3286                inst::Kind::IndexSet {
3287                    target,
3288                    index,
3289                    value,
3290                } => {
3291                    self.op_index_set(target, index, value)?;
3292                }
3293                inst::Kind::Return { addr } => {
3294                    if let Some(out) = self.op_return(addr)? {
3295                        return Ok(VmHalt::Exited(out.as_addr()));
3296                    }
3297                }
3298                inst::Kind::ReturnUnit => {
3299                    if let Some(out) = self.op_return_unit()? {
3300                        return Ok(VmHalt::Exited(out.as_addr()));
3301                    }
3302                }
3303                inst::Kind::Await { addr, out } => {
3304                    if let Some(future) = self.op_await(addr, out)? {
3305                        return Ok(VmHalt::Awaited(Awaited::Future(future, out)));
3306                    }
3307                }
3308                inst::Kind::Select { addr, len, value } => {
3309                    if let Some(select) = self.op_select(addr, len, value)? {
3310                        return Ok(VmHalt::Awaited(Awaited::Select(select, value)));
3311                    }
3312                }
3313                inst::Kind::LoadFn { hash, out } => {
3314                    self.op_load_fn(hash, out)?;
3315                }
3316                inst::Kind::Store { value, out } => {
3317                    self.op_store(value, out)?;
3318                }
3319                inst::Kind::Copy { addr, out } => {
3320                    self.op_copy(addr, out)?;
3321                }
3322                inst::Kind::Move { addr, out } => {
3323                    self.op_move(addr, out)?;
3324                }
3325                inst::Kind::Drop { set } => {
3326                    self.op_drop(set)?;
3327                }
3328                inst::Kind::Swap { a, b } => {
3329                    self.op_swap(a, b)?;
3330                }
3331                inst::Kind::Jump { jump } => {
3332                    self.op_jump(jump)?;
3333                }
3334                inst::Kind::JumpIf { cond, jump } => {
3335                    self.op_jump_if(cond, jump)?;
3336                }
3337                inst::Kind::JumpIfNot { cond, jump } => {
3338                    self.op_jump_if_not(cond, jump)?;
3339                }
3340                inst::Kind::Vec { addr, count, out } => {
3341                    self.op_vec(addr, count, out)?;
3342                }
3343                inst::Kind::Tuple { addr, count, out } => {
3344                    self.op_tuple(addr, count, out)?;
3345                }
3346                inst::Kind::Tuple1 { addr, out } => {
3347                    self.op_tuple_n(&addr[..], out)?;
3348                }
3349                inst::Kind::Tuple2 { addr, out } => {
3350                    self.op_tuple_n(&addr[..], out)?;
3351                }
3352                inst::Kind::Tuple3 { addr, out } => {
3353                    self.op_tuple_n(&addr[..], out)?;
3354                }
3355                inst::Kind::Tuple4 { addr, out } => {
3356                    self.op_tuple_n(&addr[..], out)?;
3357                }
3358                inst::Kind::Environment { addr, count, out } => {
3359                    self.op_environment(addr, count, out)?;
3360                }
3361                inst::Kind::Object { addr, slot, out } => {
3362                    self.op_object(addr, slot, out)?;
3363                }
3364                inst::Kind::Range { range, out } => {
3365                    self.op_range(range, out)?;
3366                }
3367                inst::Kind::Struct { addr, hash, out } => {
3368                    self.op_struct(addr, hash, out)?;
3369                }
3370                inst::Kind::ConstConstruct {
3371                    addr,
3372                    hash,
3373                    count,
3374                    out,
3375                } => {
3376                    self.op_const_construct(addr, hash, count, out)?;
3377                }
3378                inst::Kind::String { slot, out } => {
3379                    self.op_string(slot, out)?;
3380                }
3381                inst::Kind::GlobalGet { slot, out } => {
3382                    self.op_global_get(slot, out)?;
3383                }
3384                inst::Kind::GlobalSet { slot, value } => {
3385                    self.op_global_set(slot, value)?;
3386                }
3387                inst::Kind::Bytes { slot, out } => {
3388                    self.op_bytes(slot, out)?;
3389                }
3390                inst::Kind::StringConcat {
3391                    addr,
3392                    len,
3393                    size_hint,
3394                    out,
3395                } => {
3396                    self.op_string_concat(addr, len, size_hint, out)?;
3397                }
3398                inst::Kind::Format { addr, spec, out } => {
3399                    self.op_format(addr, spec, out)?;
3400                }
3401                inst::Kind::Try { addr, out } => {
3402                    if let Some(out) = self.op_try(addr, out)? {
3403                        return Ok(VmHalt::Exited(out.as_addr()));
3404                    }
3405                }
3406                inst::Kind::EqChar { addr, value, out } => {
3407                    self.op_eq_character(addr, value, out)?;
3408                }
3409                inst::Kind::EqUnsigned { addr, value, out } => {
3410                    self.op_eq_unsigned(addr, value, out)?;
3411                }
3412                inst::Kind::EqSigned { addr, value, out } => {
3413                    self.op_eq_signed(addr, value, out)?;
3414                }
3415                inst::Kind::EqBool {
3416                    addr,
3417                    value: boolean,
3418                    out,
3419                } => {
3420                    self.op_eq_bool(addr, boolean, out)?;
3421                }
3422                inst::Kind::EqString { addr, slot, out } => {
3423                    self.op_eq_string(addr, slot, out)?;
3424                }
3425                inst::Kind::EqBytes { addr, slot, out } => {
3426                    self.op_eq_bytes(addr, slot, out)?;
3427                }
3428                inst::Kind::MatchType {
3429                    hash,
3430                    variant_hash,
3431                    addr,
3432                    out,
3433                } => {
3434                    self.op_match_type(hash, variant_hash, addr, out)?;
3435                }
3436                inst::Kind::MatchSequence {
3437                    hash,
3438                    len,
3439                    exact,
3440                    addr,
3441                    out,
3442                } => {
3443                    self.op_match_sequence(hash, len, exact, addr, out)?;
3444                }
3445                inst::Kind::MatchObject {
3446                    slot,
3447                    exact,
3448                    addr,
3449                    out,
3450                } => {
3451                    self.op_match_object(slot, exact, addr, out)?;
3452                }
3453                inst::Kind::Yield { addr, out } => {
3454                    return Ok(VmHalt::Yielded(Some(addr), out));
3455                }
3456                inst::Kind::YieldUnit { out } => {
3457                    return Ok(VmHalt::Yielded(None, out));
3458                }
3459                inst::Kind::Op { op, a, b, out } => {
3460                    self.op_op(op, a, b, out)?;
3461                }
3462                inst::Kind::Arithmetic { op, a, b, out } => {
3463                    self.op_arithmetic(op, a, b, out)?;
3464                }
3465                inst::Kind::Bitwise { op, a, b, out } => {
3466                    self.op_bitwise(op, a, b, out)?;
3467                }
3468                inst::Kind::Shift { op, a, b, out } => {
3469                    self.op_shift(op, a, b, out)?;
3470                }
3471                inst::Kind::AssignArithmetic { op, target, rhs } => {
3472                    self.op_assign_arithmetic(op, target, rhs)?;
3473                }
3474                inst::Kind::AssignBitwise { op, target, rhs } => {
3475                    self.op_assign_bitwise(op, target, rhs)?;
3476                }
3477                inst::Kind::AssignShift { op, target, rhs } => {
3478                    self.op_assign_shift(op, target, rhs)?;
3479                }
3480                inst::Kind::IterNext { addr, jump, out } => {
3481                    self.op_iter_next(addr, jump, out)?;
3482                }
3483                inst::Kind::Panic { reason } => {
3484                    return Err(VmError::new(VmErrorKind::Panic {
3485                        reason: Panic::from(reason),
3486                    }));
3487                }
3488            }
3489        }
3490    }
3491}
3492
3493impl TryClone for Vm {
3494    fn try_clone(&self) -> alloc::Result<Self> {
3495        Ok(Self {
3496            context: self.context.clone(),
3497            unit: self.unit.clone(),
3498            ip: self.ip,
3499            last_ip_len: self.last_ip_len,
3500            stack: self.stack.try_clone()?,
3501            call_frames: self.call_frames.try_clone()?,
3502            globals: self.globals.clone(),
3503            // What is waiting to be taken apart belongs to the machine which
3504            // was taking it apart, not to a copy of it.
3505            worklist: Worklist::new(),
3506        })
3507    }
3508}
3509
3510impl AsMut<Vm> for Vm {
3511    #[inline]
3512    fn as_mut(&mut self) -> &mut Vm {
3513        self
3514    }
3515}
3516
3517impl AsRef<Vm> for Vm {
3518    #[inline]
3519    fn as_ref(&self) -> &Vm {
3520        self
3521    }
3522}
3523
3524/// A call frame.
3525///
3526/// This is used to store the return point after an instruction has been run.
3527#[derive(Debug, Clone, Copy)]
3528#[non_exhaustive]
3529pub struct CallFrame {
3530    /// The stored instruction pointer.
3531    pub ip: usize,
3532    /// The top of the stack at the time of the call to ensure stack isolation
3533    /// across function calls.
3534    ///
3535    /// I.e. a function should not be able to manipulate the size of any other
3536    /// stack than its own.
3537    pub top: usize,
3538    /// Indicates that the call frame is isolated and should force an exit into
3539    /// the vm execution context.
3540    pub isolated: Isolated,
3541    /// Keep the value produced from the call frame.
3542    pub out: Output,
3543}
3544
3545impl TryClone for CallFrame {
3546    #[inline]
3547    fn try_clone(&self) -> alloc::Result<Self> {
3548        Ok(*self)
3549    }
3550}
3551
3552/// Clear stack on drop.
3553struct ClearStack<'a>(&'a mut Vm);
3554
3555impl Drop for ClearStack<'_> {
3556    fn drop(&mut self) {
3557        self.0.stack.clear();
3558    }
3559}
3560
3561/// Check that arguments matches expected or raise the appropriate error.
3562#[inline(always)]
3563fn check_args(args: usize, expected: usize) -> Result<(), VmErrorKind> {
3564    if args != expected {
3565        return Err(VmErrorKind::BadArgumentCount {
3566            actual: args,
3567            expected,
3568        });
3569    }
3570
3571    Ok(())
3572}
3573
3574enum TargetFallback {
3575    Value(Value, Value),
3576    Field(Value, Hash, usize, Value),
3577    Index(Value, usize, Value),
3578}
3579
3580enum TargetValue<'a> {
3581    /// Resolved internal target to mutable value.
3582    Same(&'a mut Value),
3583    /// Resolved internal target to mutable value.
3584    Pair(BorrowMut<'a, Value>, &'a Value),
3585    /// Fallback to a different kind of operation.
3586    Fallback(TargetFallback),
3587}
3588
3589#[inline]
3590fn target_value<'a>(
3591    stack: &'a mut Stack,
3592    unit: &Unit,
3593    target: InstTarget,
3594    rhs: Address,
3595) -> Result<TargetValue<'a>, VmErrorKind> {
3596    match target {
3597        InstTarget::Address(addr) => match stack.pair(addr, rhs)? {
3598            Pair::Same(value) => Ok(TargetValue::Same(value)),
3599            Pair::Pair(lhs, rhs) => Ok(TargetValue::Pair(BorrowMut::from_ref(lhs), rhs)),
3600        },
3601        InstTarget::TupleField(lhs, index) => {
3602            let lhs = stack.at(lhs);
3603            let rhs = stack.at(rhs);
3604
3605            if let Some(value) = try_tuple_like_index_get_mut(lhs, index)? {
3606                Ok(TargetValue::Pair(value, rhs))
3607            } else {
3608                Ok(TargetValue::Fallback(TargetFallback::Index(
3609                    lhs.clone(),
3610                    index,
3611                    rhs.clone(),
3612                )))
3613            }
3614        }
3615        InstTarget::Field(lhs, slot) => {
3616            let rhs = stack.at(rhs);
3617
3618            let Some(field) = unit.lookup_string(slot) else {
3619                return Err(VmErrorKind::MissingStaticString { slot });
3620            };
3621
3622            let lhs = stack.at(lhs);
3623
3624            if let Some(value) = try_object_like_index_get_mut(lhs, field)? {
3625                Ok(TargetValue::Pair(value, rhs))
3626            } else {
3627                Ok(TargetValue::Fallback(TargetFallback::Field(
3628                    lhs.clone(),
3629                    field.hash(),
3630                    slot,
3631                    rhs.clone(),
3632                )))
3633            }
3634        }
3635    }
3636}
3637
3638/// Implementation of getting a mutable value out of a tuple-like value.
3639fn try_tuple_like_index_get_mut(
3640    target: &Value,
3641    index: usize,
3642) -> Result<Option<BorrowMut<'_, Value>>, VmErrorKind> {
3643    match target.as_ref() {
3644        Repr::Dynamic(data) if matches!(data.rtti().kind, RttiKind::Tuple) => {
3645            let Some(value) = data.get_mut(index)? else {
3646                return Err(VmErrorKind::MissingIndexInteger {
3647                    target: data.type_info(),
3648                    index: VmIntegerRepr::from(index),
3649                });
3650            };
3651
3652            Ok(Some(value))
3653        }
3654        Repr::Dynamic(data) => Err(VmErrorKind::MissingIndexInteger {
3655            target: data.type_info(),
3656            index: VmIntegerRepr::from(index),
3657        }),
3658        Repr::Any(value) => match value.type_hash() {
3659            Result::<Value, Value>::HASH => {
3660                let result = BorrowMut::try_map(
3661                    value.borrow_mut::<Result<Value, Value>>()?,
3662                    |value| match (index, value) {
3663                        (0, Ok(value)) => Some(value),
3664                        (0, Err(value)) => Some(value),
3665                        _ => None,
3666                    },
3667                );
3668
3669                if let Ok(value) = result {
3670                    return Ok(Some(value));
3671                }
3672
3673                Err(VmErrorKind::MissingIndexInteger {
3674                    target: TypeInfo::any::<Result<Value, Value>>(),
3675                    index: VmIntegerRepr::from(index),
3676                })
3677            }
3678            Option::<Value>::HASH => {
3679                let result =
3680                    BorrowMut::try_map(value.borrow_mut::<Option<Value>>()?, |value| {
3681                        match (index, value) {
3682                            (0, Some(value)) => Some(value),
3683                            _ => None,
3684                        }
3685                    });
3686
3687                if let Ok(value) = result {
3688                    return Ok(Some(value));
3689                }
3690
3691                Err(VmErrorKind::MissingIndexInteger {
3692                    target: TypeInfo::any::<Option<Value>>(),
3693                    index: VmIntegerRepr::from(index),
3694                })
3695            }
3696            GeneratorState::HASH => {
3697                let result = BorrowMut::try_map(value.borrow_mut::<GeneratorState>()?, |value| {
3698                    match (index, value) {
3699                        (0, GeneratorState::Yielded(value)) => Some(value),
3700                        (0, GeneratorState::Complete(value)) => Some(value),
3701                        _ => None,
3702                    }
3703                });
3704
3705                if let Ok(value) = result {
3706                    return Ok(Some(value));
3707                }
3708
3709                Err(VmErrorKind::MissingIndexInteger {
3710                    target: TypeInfo::any::<GeneratorState>(),
3711                    index: VmIntegerRepr::from(index),
3712                })
3713            }
3714            runtime::Vec::HASH => {
3715                let vec = value.borrow_mut::<runtime::Vec>()?;
3716                let result = BorrowMut::try_map(vec, |vec| vec.get_mut(index));
3717
3718                if let Ok(value) = result {
3719                    return Ok(Some(value));
3720                }
3721
3722                Err(VmErrorKind::MissingIndexInteger {
3723                    target: TypeInfo::any::<runtime::Vec>(),
3724                    index: VmIntegerRepr::from(index),
3725                })
3726            }
3727            runtime::OwnedTuple::HASH => {
3728                let tuple = value.borrow_mut::<runtime::OwnedTuple>()?;
3729                let result = BorrowMut::try_map(tuple, |tuple| tuple.get_mut(index));
3730
3731                if let Ok(value) = result {
3732                    return Ok(Some(value));
3733                }
3734
3735                Err(VmErrorKind::MissingIndexInteger {
3736                    target: TypeInfo::any::<runtime::OwnedTuple>(),
3737                    index: VmIntegerRepr::from(index),
3738                })
3739            }
3740            _ => Ok(None),
3741        },
3742        _ => Ok(None),
3743    }
3744}
3745
3746/// Implementation of getting a mutable string index on an object-like type.
3747fn try_object_like_index_get_mut<'a>(
3748    target: &'a Value,
3749    field: &str,
3750) -> Result<Option<BorrowMut<'a, Value>>, VmErrorKind> {
3751    match target.as_ref() {
3752        Repr::Inline(value) => Err(VmErrorKind::MissingField {
3753            target: value.type_info(),
3754            field: field.try_to_owned()?,
3755        }),
3756        Repr::Dynamic(data) if matches!(data.rtti().kind, RttiKind::Struct) => {
3757            Ok(data.get_field_mut(field)?)
3758        }
3759        Repr::Dynamic(data) => Err(VmErrorKind::MissingField {
3760            target: data.type_info(),
3761            field: field.try_to_owned()?,
3762        }),
3763        Repr::Any(value) => match value.type_hash() {
3764            Object::HASH => {
3765                let object = value.borrow_mut::<Object>()?;
3766
3767                let Ok(value) = BorrowMut::try_map(object, |object| object.get_mut(field)) else {
3768                    return Err(VmErrorKind::MissingField {
3769                        target: value.type_info(),
3770                        field: field.try_to_owned()?,
3771                    });
3772                };
3773
3774                Ok(Some(value))
3775            }
3776            _ => Ok(None),
3777        },
3778    }
3779}