Struct rune::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) -> Result<Self, ContextError>

Construct a new module for the given item.

source

pub fn with_crate(name: &str) -> Result<Self, ContextError>

Construct a new module for the given crate.

source

pub fn with_crate_item<I>(name: &str, iter: I) -> Result<Self, ContextError>

Construct a new module for the given crate.

source

pub fn from_meta(module_meta: ModuleMeta) -> Result<Self, ContextError>

Construct a new module from the given module meta.

source

pub fn item_mut(&mut self) -> ItemMut<'_>

Mutate item-level properties for this module.

source

pub fn ty<T>(&mut self) -> Result<TypeMut<'_, T>, ContextError>
where T: ?Sized + TypeOf + Named + 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, Context, Module};

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

impl MyBytes {
    #[rune::function]
    fn len(&self) -> usize {
        self.queue.len()
    }
}

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

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

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

m.ty::<MyBytes>()?;
m.function_meta(MyBytes::len)?;

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

pub fn type_meta<T>(&mut self) -> Result<TypeMut<'_, T>, ContextError>
where T: ?Sized + TypeOf + Named,

Accessor to modify type metadata such as documentaiton, fields, variants.

source

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

👎Deprecated: Use type_meta::<T>().make_struct(fields) instead

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 variant_meta<T>( &mut self, index: usize ) -> Result<VariantMut<'_, T>, ContextError>
where T: ?Sized + TypeOf + Named,

Access variant metadata for the given type and the index of its variant.

source

pub fn variant_constructor<F, A>( &mut self, index: usize, constructor: F ) -> Result<(), ContextError>
where F: Function<A, Plain>, F::Return: TypeOf + Named,

👎Deprecated: Use variant_meta() instead

Register a variant constructor for type T.

source

pub fn generator_state<N>( &mut self, name: N ) -> Result<InternalEnumMut<'_, GeneratorState>, ContextError>
where N: 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::ops::GeneratorState.

use rune::Module;

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

Ok::<_, rune::support::Error>(())
source

pub fn option<N>( &mut self, name: N ) -> Result<InternalEnumMut<'_, Option<Value>>, ContextError>
where N: 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"])?;

Ok::<_, rune::support::Error>(())
source

pub fn result<N>( &mut self, name: N ) -> Result<InternalEnumMut<'_, Result<Value, Value>>, ContextError>
where N: 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"])?;

Ok::<_, rune::support::Error>(())
source

pub fn constant<N, V>( &mut self, name: N, value: V ) -> ModuleConstantBuilder<'_, N, V>
where V: ToValue,

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

§Examples
use rune::{Any, Module};

let mut module = Module::default();

#[derive(Any)]
struct MyType;

module.constant("TEN", 10).build()?.docs(["A global ten value."]);
module.constant("TEN", 10).build_associated::<MyType>()?.docs(["Ten which looks like an associated constant."]);
source

pub fn macro_meta( &mut self, meta: fn() -> Result<MacroMetaData> ) -> Result<ItemMut<'_>, ContextError>

Register a native macro handler through its meta.

The metadata must be provided by annotating the function with #[rune::macro_].

This has the benefit that it captures documentation comments which can be used when generating documentation or referencing the function through code sense systems.

§Examples
use rune::Module;
use rune::ast;
use rune::compile;
use rune::macros::{quote, MacroContext, TokenStream};
use rune::parse::Parser;
use rune::alloc::prelude::*;

/// Takes an identifier and converts it into a string.
///
/// # Examples
///
/// ```rune
/// assert_eq!(ident_to_string!(Hello), "Hello");
/// ```
#[rune::macro_]
fn ident_to_string(cx: &mut MacroContext<'_, '_, '_>, stream: &TokenStream) -> compile::Result<TokenStream> {
    let mut p = Parser::from_token_stream(stream, cx.input_span());
    let ident = p.parse_all::<ast::Ident>()?;
    let ident = cx.resolve(ident)?.try_to_owned()?;
    let string = cx.lit(&ident)?;
    Ok(quote!(#string).into_token_stream(cx)?)
}

let mut m = Module::new();
m.macro_meta(ident_to_string)?;

Ok::<_, rune::support::Error>(())
source

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

Register a native macro handler.

If possible, Module::macro_meta should be used since it includes more useful information about the macro.

§Examples
use rune::Module;
use rune::ast;
use rune::compile;
use rune::macros::{quote, MacroContext, TokenStream};
use rune::parse::Parser;
use rune::alloc::prelude::*;

fn ident_to_string(cx: &mut MacroContext<'_, '_, '_>, stream: &TokenStream) -> compile::Result<TokenStream> {
    let mut p = Parser::from_token_stream(stream, cx.input_span());
    let ident = p.parse_all::<ast::Ident>()?;
    let ident = cx.resolve(ident)?.try_to_owned()?;
    let string = cx.lit(&ident)?;
    Ok(quote!(#string).into_token_stream(cx)?)
}

let mut m = Module::new();
m.macro_(["ident_to_string"], ident_to_string)?;

Ok::<_, rune::support::Error>(())
source

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

Register a native attribute macro handler.

If possible, Module::macro_meta should be used since it includes more useful information about the function.

§Examples
use rune::Module;
use rune::ast;
use rune::compile;
use rune::macros::{quote, MacroContext, TokenStream, ToTokens};
use rune::parse::Parser;

fn rename_fn(cx: &mut MacroContext<'_, '_, '_>, input: &TokenStream, item: &TokenStream) -> compile::Result<TokenStream> {
    let mut item = Parser::from_token_stream(item, cx.macro_span());
    let mut fun = item.parse_all::<ast::ItemFn>()?;

    let mut input = Parser::from_token_stream(input, cx.input_span());
    fun.name = input.parse_all::<ast::EqValue<_>>()?.value;
    Ok(quote!(#fun).into_token_stream(cx)?)
}

let mut m = Module::new();
m.attribute_macro(["rename_fn"], rename_fn)?;

Ok::<_, rune::support::Error>(())
source

pub fn function_meta( &mut self, meta: fn() -> Result<FunctionMetaData> ) -> Result<ItemFnMut<'_>, ContextError>

Register a function handler through its meta.

The metadata must be provided by annotating the function with #[rune::function].

This has the benefit that it captures documentation comments which can be used when generating documentation or referencing the function through code sense systems.

§Examples
use rune::{Module, ContextError};
use rune::runtime::Ref;

/// This is a pretty neat function.
#[rune::function]
fn to_string(string: &str) -> String {
    string.to_string()
}

/// This is a pretty neat download function
#[rune::function]
async fn download(url: Ref<str>) -> rune::support::Result<String> {
    todo!()
}

fn module() -> Result<Module, ContextError> {
    let mut m = Module::new();
    m.function_meta(to_string)?;
    m.function_meta(download)?;
    Ok(m)
}

Registering instance functions:

use rune::{Any, Module};
use rune::runtime::Ref;

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

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

    #[rune::function]
    fn len(&self) -> usize {
        self.queue.len()
    }

    #[rune::function(instance, path = Self::download)]
    async fn download(this: Ref<Self>, url: Ref<str>) -> rune::support::Result<()> {
        todo!()
    }
}

let mut m = Module::default();

m.ty::<MyBytes>()?;
m.function_meta(MyBytes::len)?;
m.function_meta(MyBytes::download)?;
source

pub fn function<F, A, N, K>( &mut self, name: N, f: F ) -> ModuleFunctionBuilder<'_, F, A, N, K>
where F: Function<A, K>, F::Return: MaybeTypeOf, A: FunctionArgs, K: FunctionKind,

Register a function.

If possible, Module::function_meta should be used since it includes more useful information about the function.

§Examples
use rune::Module;

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

let mut module = Module::default();

module.function("add_ten", add_ten)
    .build()?
    .docs(["Adds 10 to any integer passed in."])?;

Asynchronous function:

use rune::{Any, Module};

#[derive(Any)]
struct DownloadError {
    /* .. */
}

async fn download_quote() -> Result<String, DownloadError> {
    download("https://api.quotable.io/random").await
}

let mut module = Module::default();

module.function("download_quote", download_quote).build()?
    .docs(["Download a random quote from the internet."]);
source

pub fn function2<F, A, N, K>( &mut self, name: N, f: F ) -> Result<ModuleFunctionBuilder<'_, F, A, N, K>, ContextError>
where F: Function<A, K>, F::Return: MaybeTypeOf, A: FunctionArgs, K: FunctionKind,

👎Deprecated: Use Module::function
source

pub fn async_function<F, A, N>( &mut self, name: N, f: F ) -> Result<ItemFnMut<'_>, ContextError>
where F: Function<A, Async>, F::Return: MaybeTypeOf, N: IntoComponent, A: FunctionArgs,

👎Deprecated: Use Module::function() instead
source

pub fn associated_function<N, F, A, K>( &mut self, name: N, f: F ) -> Result<ItemFnMut<'_>, ContextError>
where N: ToInstance, F: InstanceFunction<A, K>, F::Return: MaybeTypeOf, A: FunctionArgs, K: FunctionKind,

Register an instance function.

If possible, Module::function_meta should be used since it includes more useful information about the function.

This returns a ItemMut, which is a handle that can be used to associate more metadata with the inserted item.

§Replacing this with function_meta and #[rune::function]

This is how you declare an instance function which takes &self or &mut self:

#[derive(Any)]
struct Struct {
    /* .. */
}

impl Struct {
    /// Get the length of the `Struct`.
    #[rune::function]
    fn len(&self) -> usize {
        /* .. */
    }
}

If a function does not take &self or &mut self, you must specify that it’s an instance function using #[rune::function(instance)]. The first argument is then considered the instance the function gets associated with:

#[derive(Any)]
struct Struct {
    /* .. */
}

/// Get the length of the `Struct`.
#[rune::function(instance)]
fn len(this: &Struct) -> usize {
    /* .. */
}

To declare an associated function which does not receive the type we must specify the path to the function using #[rune::function(path = Self::<name>)]:

#[derive(Any)]
struct Struct {
    /* .. */
}

impl Struct {
    /// Construct a new [`Struct`].
    #[rune::function(path = Self::new)]
    fn new() -> Struct {
        Struct {
           /* .. */
        }
    }
}

Or externally like this:

#[derive(Any)]
struct Struct {
    /* .. */
}

/// Construct a new [`Struct`].
#[rune::function(free, path = Struct::new)]
fn new() -> Struct {
    Struct {
       /* .. */
    }
}

The first part Struct in Struct::new is used to determine the type the function is associated with.

Protocol functions can either be defined in an impl block or externally. To define a protocol externally, you can simply do this:

#[derive(Any)]
struct Struct {
    /* .. */
}

#[rune::function(instance, protocol = STRING_DISPLAY)]
fn string_display(this: &Struct, f: &mut Formatter) -> std::fmt::Result {
    /* .. */
}
§Examples
use rune::{Any, Module};

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

impl MyBytes {
    /// Construct a new empty bytes container.
    #[rune::function(path = Self::new)]
    fn new() -> Self {
        Self {
            queue: Vec::new(),
        }
    }

    /// Get the number of bytes.
    #[rune::function]
    fn len(&self) -> usize {
        self.queue.len()
    }
}

let mut m = Module::default();

m.ty::<MyBytes>()?;
m.function_meta(MyBytes::new)?;
m.function_meta(MyBytes::len)?;

Asynchronous function:

use std::sync::atomic::AtomicU32;
use std::sync::Arc;

use rune::{Any, Module};
use rune::runtime::Ref;

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

#[derive(Any)]
struct DownloadError {
    /* .. */
}

impl Client {
    /// Download a thing.
    #[rune::function(instance, path = Self::download)]
    async fn download(this: Ref<Self>) -> Result<(), DownloadError> {
        /* .. */
    }
}

let mut module = Module::default();

module.ty::<Client>()?;
module.function_meta(Client::download)?;
source

pub fn inst_fn<N, F, A, K>( &mut self, name: N, f: F ) -> Result<ItemFnMut<'_>, ContextError>
where N: ToInstance, F: InstanceFunction<A, K>, F::Return: MaybeTypeOf, A: FunctionArgs, K: FunctionKind,

👎Deprecated: Use Module::associated_function() instead
source

pub fn async_inst_fn<N, F, A>( &mut self, name: N, f: F ) -> Result<ItemFnMut<'_>, ContextError>
where N: ToInstance, F: InstanceFunction<A, Async>, F::Return: MaybeTypeOf, A: FunctionArgs,

👎Deprecated: Use Module::associated_function() instead
source

pub fn field_function<N, F, A>( &mut self, protocol: Protocol, name: N, f: F ) -> Result<ItemFnMut<'_>, ContextError>
where N: ToFieldFunction, F: InstanceFunction<A, Plain>, F::Return: MaybeTypeOf, A: FunctionArgs,

Install a protocol function that interacts with the given field.

This returns a ItemMut, which is a handle that can be used to associate more metadata with the inserted item.

source

pub fn field_fn<N, F, A>( &mut self, protocol: Protocol, name: N, f: F ) -> Result<ItemFnMut<'_>, ContextError>
where N: ToFieldFunction, F: InstanceFunction<A, Plain>, F::Return: MaybeTypeOf, A: FunctionArgs,

👎Deprecated: Use Module::field_function() instead
source

pub fn index_function<F, A>( &mut self, protocol: Protocol, index: usize, f: F ) -> Result<ItemFnMut<'_>, ContextError>
where F: InstanceFunction<A, Plain>, F::Return: MaybeTypeOf, A: FunctionArgs,

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 index_fn<F, A>( &mut self, protocol: Protocol, index: usize, f: F ) -> Result<ItemFnMut<'_>, ContextError>
where F: InstanceFunction<A, Plain>, F::Return: MaybeTypeOf, A: FunctionArgs,

👎Deprecated: Use Module::index_function() instead
source

pub fn raw_function<F, N>( &mut self, name: N, f: F ) -> ModuleRawFunctionBuilder<'_, N>
where F: 'static + Fn(&mut Stack, usize) -> VmResult<()> + Send + Sync,

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

This returns a ItemMut, which is a handle that can be used to associate more metadata with the inserted item.

§Examples
use rune::Module;
use rune::runtime::{Stack, VmResult, ToValue};
use rune::vm_try;

fn sum(stack: &mut Stack, args: usize) -> VmResult<()> {
    let mut number = 0;

    for _ in 0..args {
        number += vm_try!(vm_try!(stack.pop()).into_integer());
    }

    stack.push(vm_try!(number.to_value()));
    VmResult::Ok(())
}

let mut module = Module::default();

module.raw_function("sum", sum)
    .build()?
    .docs([
        "Sum all numbers provided to the function."
    ])?;
source

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

👎Deprecated: Use raw_function builder instead

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