Struct rune::runtime::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 + Args, T: Send + FromValue,

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

source

pub fn call<A, T>(&self, args: A) -> VmResult<T>
where A: Args, 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) -> VmResult<SyncFunction>

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().into_result()?;

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 Debug for Function

source§

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

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

impl FromValue for Function

source§

fn from_value(value: Value) -> VmResult<Self>

Try to convert to the given type, from the given value.
source§

impl InstallWith for Function

source§

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

Hook to install more things into the module.
source§

impl MaybeTypeOf for Function

source§

fn maybe_type_of() -> Option<FullTypeOf>

Type information for the given type.
source§

impl Named for Function

source§

const BASE_NAME: RawStr = _

The generic name of the named thing.
source§

fn full_name() -> Box<str>

The exact type name
source§

impl ToValue for Function

source§

fn to_value(self) -> VmResult<Value>

Convert into a value.
source§

impl TryFrom<Function> for Value

§

type Error = Error

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

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

Performs the conversion.
source§

impl TypeOf for Function

source§

fn type_hash() -> Hash

Get full type hash, including type parameters.
source§

fn type_info() -> TypeInfo

Access diagnostical information on the value type.
source§

fn type_of() -> FullTypeOf

Type information for the given type.
source§

fn type_parameters() -> Hash

Hash of type parameters.
source§

impl UnsafeToMut for Function

§

type Guard = RawMut

The raw guard returned. Read more
source§

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

Safety Read more
source§

impl UnsafeToRef for Function

§

type Guard = RawRef

The raw guard returned. Read more
source§

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

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

§

type Guard = ()

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

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

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