Struct rune::runtime::Vm

source ·
pub struct Vm { /* private fields */ }
Expand description

A stack which references variables indirectly from a slab.

Implementations§

source§

impl Vm

source

pub const fn new(context: Arc<RuntimeContext>, unit: Arc<Unit>) -> Self

Construct a new virtual machine.

source

pub const fn with_stack( context: Arc<RuntimeContext>, unit: Arc<Unit>, stack: Stack ) -> Self

Construct a new virtual machine with a custom stack.

source

pub fn without_runtime(unit: Arc<Unit>) -> Self

Construct a vm with a default empty RuntimeContext. This is useful when the Unit was constructed with an empty Context.

source

pub fn is_same(&self, context: &Arc<RuntimeContext>, unit: &Arc<Unit>) -> bool

Test if the virtual machine is the same context and unit as specified.

source

pub fn is_same_context(&self, context: &Arc<RuntimeContext>) -> bool

Test if the virtual machine is the same context.

source

pub fn is_same_unit(&self, unit: &Arc<Unit>) -> bool

Test if the virtual machine is the same context.

source

pub fn set_ip(&mut self, ip: usize)

Set the current instruction pointer.

source

pub fn call_frames(&self) -> &[CallFrame]

Get the stack.

source

pub fn stack(&self) -> &Stack

Get the stack.

source

pub fn stack_mut(&mut self) -> &mut Stack

Get the stack mutably.

source

pub fn context_mut(&mut self) -> &mut Arc<RuntimeContext>

Access the context related to the virtual machine mutably.

source

pub fn context(&self) -> &Arc<RuntimeContext>

Access the context related to the virtual machine.

source

pub fn unit_mut(&mut self) -> &mut Arc<Unit>

Access the underlying unit of the virtual machine mutablys.

source

pub fn unit(&self) -> &Arc<Unit>

Access the underlying unit of the virtual machine.

source

pub fn ip(&self) -> usize

Access the current instruction pointer.

source

pub fn last_ip(&self) -> usize

Access the last instruction that was executed.

source

pub fn clear(&mut self)

Reset this virtual machine, freeing all memory used.

source

pub fn lookup_function<N>(&self, name: N) -> Result<Function, VmError>
where N: ToTypeHash,

Look up a function in the virtual machine by its name.

§Examples
use rune::{Context, Vm, Unit};
use rune::compile::ItemBuf;

use std::sync::Arc;

let context = Context::with_default_modules()?;
let context = Arc::new(context.runtime()?);

let mut sources = rune::sources! {
    entry => {
        pub fn max(a, b) {
            if a > b {
                a
            } else {
                b
            }
        }
    }
};

let unit = rune::prepare(&mut sources).build()?;
let unit = Arc::new(unit);

let vm = Vm::new(context, unit);

// Looking up an item from the source.
let dynamic_max = vm.lookup_function(["max"])?;

let value: i64 = rune::from_value(dynamic_max.call((10, 20)).into_result()?)?;
assert_eq!(value, 20);

// Building an item buffer to lookup an `::std` item.
let mut item = ItemBuf::with_crate("std")?;
item.push("i64")?;
item.push("max")?;

let max = vm.lookup_function(&item)?;

let value: i64 = rune::from_value(max.call((10, 20)).into_result()?)?;
assert_eq!(value, 20);
source

pub fn complete(self) -> Result<Value, VmError>

Run the given vm to completion.

If any async instructions are encountered, this will error.

source

pub async fn async_complete(self) -> Result<Value, VmError>

Run the given vm to completion with support for async functions.

source

pub fn execute<A, N>( &mut self, name: N, args: A ) -> Result<VmExecution<&mut Self>, VmError>
where N: ToTypeHash, A: Args,

Call the function identified by the given name.

Computing the function hash from the name can be a bit costly, so it’s worth noting that it can be precalculated:

use rune::Hash;

let name = Hash::type_hash(["main"]);
§Examples
use rune::{Context, Unit};
use std::sync::Arc;

let context = Context::with_default_modules()?;
let context = Arc::new(context.runtime()?);

// Normally the unit would be created by compiling some source,
// and since this one is empty it won't do anything.
let unit = Arc::new(Unit::default());

let mut vm = rune::Vm::new(context, unit);

let output = vm.execute(["main"], (33i64,))?.complete().into_result()?;
let output: i64 = rune::from_value(output)?;

println!("output: {}", output);

You can use a Vec<Value> to provide a variadic collection of arguments.

use rune::{Context, Unit};
use std::sync::Arc;

let context = Context::with_default_modules()?;
let context = Arc::new(context.runtime()?);

// Normally the unit would be created by compiling some source,
// and since this one is empty it won't do anything.
let unit = Arc::new(Unit::default());

let mut vm = rune::Vm::new(context, unit);

let mut args = Vec::new();
args.push(rune::to_value(1u32)?);
args.push(rune::to_value(String::from("Hello World"))?);

let output = vm.execute(["main"], args)?.complete().into_result()?;
let output: i64 = rune::from_value(output)?;

println!("output: {}", output);
source

pub fn send_execute<A, N>( self, name: N, args: A ) -> Result<VmSendExecution, VmError>
where N: ToTypeHash, A: Send + Args,

An execute variant that returns an execution which implements Send, allowing it to be sent and executed on a different thread.

This is accomplished by preventing values escaping from being non-exclusively sent with the execution or escaping the execution. We only support encoding arguments which themselves are Send.

source

pub fn call<A, N>(&mut self, name: N, args: A) -> Result<Value, VmError>
where N: ToTypeHash, A: GuardedArgs,

Call the given function immediately, returning the produced value.

This function permits for using references since it doesn’t defer its execution.

§Panics

If any of the arguments passed in are references, and that references is captured somewhere in the call as Mut<T> or Ref<T> this call will panic as we are trying to free the metadata relatedc to the reference.

source

pub async fn async_call<A, N>( &mut self, name: N, args: A ) -> Result<Value, VmError>
where N: ToTypeHash, A: GuardedArgs,

Call the given function immediately asynchronously, returning the produced value.

This function permits for using references since it doesn’t defer its execution.

§Panics

If any of the arguments passed in are references, and that references is captured somewhere in the call as Mut<T> or Ref<T> this call will panic as we are trying to free the metadata relatedc to the reference.

source

pub fn with<F, T>(&mut self, f: F) -> T
where F: FnOnce() -> T,

Call the provided closure within the context of this virtual machine.

This allows for calling protocol function helpers like Value::string_display which requires access to a virtual machine.

use rune::{Context, Unit};
use rune::runtime::Formatter;
use std::sync::Arc;

let context = Context::with_default_modules()?;
let context = Arc::new(context.runtime()?);

// Normally the unit would be created by compiling some source,
// and since this one is empty it'll just error.
let unit = Arc::new(Unit::default());

let mut vm = rune::Vm::new(context, unit);

let output = vm.call(["main"], ())?;

// Call the string_display protocol on `output`. This requires
// access to a virtual machine since it might use functions
// registered in the unit associated with it.
let mut f = Formatter::new();

// Note: We do an extra unwrap because the return value is
// `fmt::Result`.
vm.with(|| output.string_display(&mut f)).into_result()?;

Trait Implementations§

source§

impl AsMut<Vm> for Vm

source§

fn as_mut(&mut self) -> &mut Vm

Converts this type into a mutable reference of the (usually inferred) input type.
source§

impl AsRef<Vm> for Vm

source§

fn as_ref(&self) -> &Vm

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl Debug for Vm

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl TryClone for Vm

source§

fn try_clone(&self) -> Result<Self>

Try to clone the current value, raising an allocation error if it’s unsuccessful.
source§

fn try_clone_from(&mut self, source: &Self) -> Result<(), Error>

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Vm

§

impl !Send for Vm

§

impl !Sync for Vm

§

impl Unpin for Vm

§

impl !UnwindSafe for Vm

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> TryToOwned for T
where T: TryClone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn try_to_owned(&self) -> Result<T, Error>

Creates owned data from borrowed data, usually by cloning. Read more
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more