Struct rune::compile::Module

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

A Module that is a collection of native functions and types.

Needs to be installed into a Context using Context::install.

Implementations§

source§

impl Module

source

pub fn new() -> Self

Create an empty module for the root path.

source

pub fn with_item<I>(iter: I) -> Selfwhere I: IntoIterator, I::Item: IntoComponent,

Construct a new module for the given item.

source

pub fn with_crate(name: &str) -> Self

Construct a new module for the given crate.

source

pub fn with_crate_item<I>(name: &str, iter: I) -> Selfwhere I: IntoIterator, I::Item: IntoComponent,

Construct a new module for the given crate.

source

pub fn ty<T>(&mut self) -> Result<(), ContextError>where T: Named + TypeOf + InstallWith,

Register a type. Registering a type is mandatory in order to register instance functions using that type.

This will allow the type to be used within scripts, using the item named here.

Examples
use rune::Any;

#[derive(Any)]
struct MyBytes {
    queue: Vec<String>,
}

impl MyBytes {
    fn len(&self) -> usize {
        self.queue.len()
    }
}

// Register `len` without registering a type.
let mut module = rune::Module::default();
// Note: cannot do this until we have registered a type.
module.inst_fn("len", MyBytes::len)?;

let mut context = rune::Context::new();
assert!(context.install(module).is_err());

// Register `len` properly.
let mut module = rune::Module::default();

module.ty::<MyBytes>()?;
module.inst_fn("len", MyBytes::len)?;

let mut context = rune::Context::new();
assert!(context.install(module).is_ok());
source

pub fn struct_meta<T, const N: usize>( &mut self, fields: [&'static str; N] ) -> Result<(), ContextError>where T: Named + TypeOf,

Register that the given type is a struct, and that it has the given compile-time metadata. This implies that each field has a Protocol::GET field function.

This is typically not used directly, but is used automatically with the Any derive.

source

pub fn enum_meta<T, const N: usize>( &mut self, variants: [(&'static str, Variant); N] ) -> Result<(), ContextError>where T: Named + TypeOf,

Register enum metadata for the given type T. This allows an enum to be used in limited ways in Rune.

source

pub fn variant_constructor<Func, Args, T>( &mut self, index: usize, constructor: Func ) -> Result<(), ContextError>where T: Named + TypeOf, Func: Function<Args, Return = T>,

Register a variant constructor for type T.

source

pub fn unit<N>(&mut self, name: N) -> Result<(), ContextError>where N: AsRef<str>,

Construct type information for the unit type.

Registering this allows the given type to be used in Rune scripts when referring to the unit type.

Examples

This shows how to register the unit type () as nonstd::unit.

use rune::Module;

let mut module = Module::with_item(["nonstd"]);
module.unit("unit")?;
source

pub fn generator_state<N>(&mut self, name: N) -> Result<(), ContextError>where N: IntoIterator, N::Item: IntoComponent,

Construct the type information for the GeneratorState type.

Registering this allows the given type to be used in Rune scripts when referring to the GeneratorState type.

Examples

This shows how to register the GeneratorState as nonstd::generator::GeneratorState.

use rune::Module;

let mut module = Module::with_crate_item("nonstd", ["generator"]);
module.generator_state(["GeneratorState"])?;
source

pub fn option<N>(&mut self, name: N) -> Result<(), ContextError>where N: IntoIterator, N::Item: IntoComponent,

Construct type information for the Option type.

Registering this allows the given type to be used in Rune scripts when referring to the Option type.

Examples

This shows how to register the Option as nonstd::option::Option.

use rune::Module;

let mut module = Module::with_crate_item("nonstd", ["option"]);
module.option(["Option"])?;
source

pub fn result<N>(&mut self, name: N) -> Result<(), ContextError>where N: IntoIterator, N::Item: IntoComponent,

Construct type information for the internal Result type.

Registering this allows the given type to be used in Rune scripts when referring to the Result type.

Examples

This shows how to register the Result as nonstd::result::Result.

use rune::Module;

let mut module = Module::with_crate_item("nonstd", ["result"]);
module.result(["Result"])?;
source

pub fn function<Func, Args, N>( &mut self, name: N, f: Func ) -> Result<(), ContextError>where Func: Function<Args>, N: IntoIterator, N::Item: IntoComponent,

Register a function that cannot error internally.

Examples
fn add_ten(value: i64) -> i64 {
    value + 10
}

let mut module = rune::Module::default();

module.function(["add_ten"], add_ten)?;
module.function(["empty"], || Ok::<_, rune::Error>(()))?;
module.function(["string"], |a: String| Ok::<_, rune::Error>(()))?;
module.function(["optional"], |a: Option<String>| Ok::<_, rune::Error>(()))?;
source

pub fn constant<N, V>(&mut self, name: N, value: V) -> Result<(), ContextError>where N: IntoIterator, N::Item: IntoComponent, V: ToValue,

Register a constant value, at a crate, module or associated level.

Examples

let mut module = rune::Module::default();

module.constant(["TEN"], 10)?; // a global TEN value
module.constant(["MyType", "TEN"], 10)?; // looks like an associated value
source

pub fn macro_<N, M>(&mut self, name: N, f: M) -> Result<(), ContextError>where M: 'static + Send + Sync + Fn(&mut MacroContext<'_>, &TokenStream) -> Result<TokenStream>, N: IntoIterator, N::Item: IntoComponent,

Register a native macro handler.

source

pub fn async_function<Func, Args, N>( &mut self, name: N, f: Func ) -> Result<(), ContextError>where Func: AsyncFunction<Args>, N: IntoIterator, N::Item: IntoComponent,

Register a function.

Examples
let mut module = rune::Module::default();

module.async_function(["empty"], || async { () })?;
module.async_function(["empty_fallible"], || async { Ok::<_, rune::Error>(()) })?;
module.async_function(["string"], |a: String| async { Ok::<_, rune::Error>(()) })?;
module.async_function(["optional"], |a: Option<String>| async { Ok::<_, rune::Error>(()) })?;
source

pub fn raw_fn<F, N>(&mut self, name: N, f: F) -> Result<(), ContextError>where F: 'static + Fn(&mut Stack, usize) -> Result<(), VmError> + Send + Sync, N: IntoIterator, N::Item: IntoComponent,

Register a raw function which interacts directly with the virtual machine.

source

pub fn inst_fn<N, Func, Args>( &mut self, name: N, f: Func ) -> Result<(), ContextError>where N: InstFnName, Func: InstFn<Args>,

Register an instance function.

Examples
use rune::Any;

#[derive(Any)]
struct MyBytes {
    queue: Vec<String>,
}

impl MyBytes {
    fn new() -> Self {
        Self {
            queue: Vec::new(),
        }
    }

    fn len(&self) -> usize {
        self.queue.len()
    }
}

let mut module = rune::Module::default();

module.ty::<MyBytes>()?;
module.function(["MyBytes", "new"], MyBytes::new)?;
module.inst_fn("len", MyBytes::len)?;

let mut context = rune::Context::new();
context.install(module)?;
source

pub fn field_fn<N, Func, Args>( &mut self, protocol: Protocol, name: N, f: Func ) -> Result<(), ContextError>where N: InstFnName, Func: InstFn<Args>,

Install a protocol function that interacts with the given field.

source

pub fn index_fn<Func, Args>( &mut self, protocol: Protocol, index: usize, f: Func ) -> Result<(), ContextError>where Func: InstFn<Args>,

Install a protocol function that interacts with the given index.

An index can either be a field inside a tuple, or a variant inside of an enum as configured with Module::enum_meta.

source

pub fn async_inst_fn<N, Func, Args>( &mut self, name: N, f: Func ) -> Result<(), ContextError>where N: InstFnName, Func: AsyncInstFn<Args>,

Register an instance function.

Examples
use std::sync::atomic::AtomicU32;
use std::sync::Arc;
use rune::Any;

#[derive(Clone, Debug, Any)]
struct MyType {
    value: Arc<AtomicU32>,
}

impl MyType {
    async fn test(&self) -> rune::Result<()> {
        Ok(())
    }
}

let mut module = rune::Module::default();

module.ty::<MyType>()?;
module.async_inst_fn("test", MyType::test)?;

Trait Implementations§

source§

impl AsRef<Module> for Module

source§

fn as_ref(&self) -> &Module

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

impl Default for Module

source§

fn default() -> Module

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Module

§

impl Send for Module

§

impl Sync for Module

§

impl Unpin for Module

§

impl !UnwindSafe for Module

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere 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 Twhere 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, U> TryFrom<U> for Twhere 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 Twhere 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> 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