rune::runtime

Struct Function

Source
pub struct Function(/* private fields */);
Expand description

The type of a function in Rune.

Functions can be called using call expression syntax, such as <expr>().

There are multiple different kind of things which can be coerced into a function in Rune:

  • Regular functions.
  • Closures (which might or might not capture their environment).
  • Built-in constructors for tuple types (tuple structs, tuple variants).

§Examples

// Captures the constructor for the `Some(<value>)` tuple variant.
let build_some = Some;
assert_eq!(build_some(42), Some(42));

fn build(value) {
    Some(value)
}

// Captures the function previously defined.
let build_some = build;
assert_eq!(build_some(42), Some(42));

Implementations§

Source§

impl Function

Source

pub fn new<F, A, K>(f: F) -> Self
where F: Function<A, K>, K: FunctionKind,

Construct a Function from a Rust closure.

§Examples
use rune::{Hash, Vm};
use rune::runtime::Function;
use std::sync::Arc;

let mut sources = rune::sources! {
    entry => {
        pub fn main(function) {
            function(41)
        }
    }
};

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

let function = Function::new(|value: u32| value + 1);

assert_eq!(function.type_hash(), Hash::EMPTY);

let value = vm.call(["main"], (function,))?;
let value: u32 = rune::from_value(value)?;
assert_eq!(value, 42);

Asynchronous functions:

use rune::{Hash, Vm};
use rune::runtime::Function;
use std::sync::Arc;

let mut sources = rune::sources! {
    entry => {
        pub async fn main(function) {
            function(41).await
        }
    }
};

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

let function = Function::new(|value: u32| async move { value + 1 });

assert_eq!(function.type_hash(), Hash::EMPTY);

let value = vm.async_call(["main"], (function,)).await?;
let value: u32 = rune::from_value(value)?;
assert_eq!(value, 42);
Source

pub fn function<F, A, K>(f: F) -> Self
where F: Function<A, K>, K: FunctionKind,

👎Deprecated: Use Function::new() instead
Source

pub fn async_function<F, A>(f: F) -> Self
where F: Function<A, Async>,

👎Deprecated: Use Function::new() instead
Source

pub async fn async_send_call<A, T>(&self, args: A) -> VmResult<T>
where A: Send + GuardedArgs, T: Send + FromValue,

Perform an asynchronous call over the function which also implements Send.

Source

pub fn call<T>(&self, args: impl GuardedArgs) -> VmResult<T>
where T: FromValue,

Perform a call over the function represented by this function pointer.

§Examples
use rune::{Hash, Vm};
use rune::runtime::Function;
use std::sync::Arc;

let mut sources = rune::sources! {
    entry => {
        fn add(a, b) {
            a + b
        }

        pub fn main() { add }
    }
};

let unit = rune::prepare(&mut sources).build()?;
let mut vm = Vm::without_runtime(Arc::new(unit));
let value = vm.call(["main"], ())?;

let value: Function = rune::from_value(value)?;
assert_eq!(value.call::<u32>((1, 2)).into_result()?, 3);
Source

pub fn type_hash(&self) -> Hash

Type Hash of the underlying function.

§Examples

The type hash of a top-level function matches what you get out of Hash::type_hash.

use rune::{Hash, Vm};
use rune::runtime::Function;
use std::sync::Arc;

let mut sources = rune::sources! {
    entry => {
        fn pony() { }

        pub fn main() { pony }
    }
};

let unit = rune::prepare(&mut sources).build()?;
let mut vm = Vm::without_runtime(Arc::new(unit));
let pony = vm.call(["main"], ())?;
let pony: Function = rune::from_value(pony)?;

assert_eq!(pony.type_hash(), Hash::type_hash(["pony"]));
Source

pub fn into_sync(self) -> Result<SyncFunction, RuntimeError>

Try to convert into a SyncFunction. This might not be possible if this function is something which is not Sync, like a closure capturing context which is not thread-safe.

§Examples
use rune::{Hash, Vm};
use rune::runtime::Function;
use std::sync::Arc;

let mut sources = rune::sources! {
    entry => {
        fn pony() { }

        pub fn main() { pony }
    }
};

let unit = rune::prepare(&mut sources).build()?;
let mut vm = Vm::without_runtime(Arc::new(unit));
let pony = vm.call(["main"], ())?;
let pony: Function = rune::from_value(pony)?;

// This is fine, since `pony` is a free function.
let pony = pony.into_sync()?;

assert_eq!(pony.type_hash(), Hash::type_hash(["pony"]));

The following does not work, because we return a closure which tries to make use of a Generator which is not a constant value.

use rune::{Hash, Vm};
use rune::runtime::Function;
use std::sync::Arc;

let mut sources = rune::sources! {
    entry => {
        fn generator() {
            yield 42;
        }

        pub fn main() {
            let g = generator();

            move || {
                g.next()
            }
        }
    }
};

let unit = rune::prepare(&mut sources).build()?;
let mut vm = Vm::without_runtime(Arc::new(unit));
let closure = vm.call(["main"], ())?;
let closure: Function = rune::from_value(closure)?;

// This is *not* fine since the returned closure has captured a
// generator which is not a constant value.
assert!(closure.into_sync().is_err());

Trait Implementations§

Source§

impl Any for Function

Source§

const ANY_TYPE_INFO: AnyTypeInfo = _

The compile-time type information know for the type.
Source§

impl Debug for Function

Source§

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

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

impl InstallWith for Function

Source§

fn install_with(module: &mut Module) -> Result<(), ContextError>

Hook to install more things into the module.
Source§

impl IntoOutput for Function

Source§

fn into_output(self) -> Result<Value, RuntimeError>

Coerce the current value into an output.
Source§

impl MaybeTypeOf for Function

Source§

fn maybe_type_of() -> Result<DocType>

Type information for the given type.
Source§

impl Named for Function

Source§

const ITEM: &'static Item = _

The name item.
Source§

fn full_name(f: &mut Formatter<'_>) -> Result

The exact type name
Source§

fn display() -> impl Display

Return a display wrapper for the named type.
Source§

impl TryClone for Function

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
Source§

impl TryFrom<Function> for Value

Source§

type Error = Error

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

fn try_from(value: Function) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TypeHash for Function

Source§

const HASH: Hash = _

The complete type hash of the type including type parameters which uniquely identifiers a given type. Read more
Source§

impl TypeOf for Function

Source§

const PARAMETERS: Hash = _

Type parameters for the type. Read more
Source§

const STATIC_TYPE_INFO: AnyTypeInfo = <Self as rune::Any>::ANY_TYPE_INFO

Access diagnostical type information for the current type. Read more
Source§

fn type_info() -> TypeInfo

Get type info associated with the current type.
Source§

impl UnsafeToMut for Function

Source§

type Guard = RawValueGuard

The raw guard returned. Read more
Source§

unsafe fn unsafe_to_mut<'a>( value: Value, ) -> Result<(&'a mut Self, Self::Guard), RuntimeError>

Safety Read more
Source§

impl UnsafeToRef for Function

Source§

type Guard = RawValueGuard

The raw guard returned. Read more
Source§

unsafe fn unsafe_to_ref<'a>( value: Value, ) -> Result<(&'a Self, Self::Guard), RuntimeError>

Safety Read more
Source§

impl UnsafeToValue for &Function

Source§

type Guard = ValueRefGuard

The type used to guard the unsafe value conversion.
Source§

unsafe fn unsafe_to_value(self) -> Result<(Value, Self::Guard), RuntimeError>

Convert into a value. Read more
Source§

impl UnsafeToValue for &mut Function

Source§

type Guard = ValueMutGuard

The type used to guard the unsafe value conversion.
Source§

unsafe fn unsafe_to_value(self) -> Result<(Value, Self::Guard), RuntimeError>

Convert into a value. Read more

Auto Trait Implementations§

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> FromValue for T
where T: AnyMarker,

Source§

fn from_value(value: Value) -> Result<T, RuntimeError>

Try to convert to the given type, from the given value.
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

Source§

type Output = T

Should always be Self
Source§

impl<T> ToReturn for T
where T: ToValue,

Source§

fn to_return(self) -> VmResult<Value>

Convert something into a return value.
Source§

impl<T> ToValue for T
where T: AnyMarker,

Source§

fn to_value(self) -> Result<Value, RuntimeError>

Convert into a value.
Source§

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

Source§

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>,

Source§

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,

Source§

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<T> UnsafeToValue for T
where T: ToValue,

Source§

type Guard = ()

The type used to guard the unsafe value conversion.
Source§

unsafe fn unsafe_to_value( self, ) -> Result<(Value, <T as UnsafeToValue>::Guard), RuntimeError>

Convert into a value. 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
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T