rune::module

Struct 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( iter: impl IntoIterator<Item: IntoComponent>, ) -> 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( name: &str, iter: impl IntoIterator<Item: IntoComponent>, ) -> 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 constant<N, V>( &mut self, name: N, value: V, ) -> ModuleConstantBuilder<'_, N, V>

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

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

let mut module = Module::default();

#[derive(Any)]
struct MyType;

module.constant("TEN", 10)
    .build()?
    .docs(docstring! {
        /// A global ten value.
    });

module.constant("TEN", 10)
    .build_associated::<MyType>()?
    .docs(docstring! {
        /// 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::{ContextError, Module, 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> {
}

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, 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<()> {
    }
}

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::{docstring, Module};

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

let mut module = Module::default();

module.function("add_ten", add_ten)
    .build()?
    .docs(docstring! {
        /// Adds 10 to any integer passed in.
    });

Asynchronous function:

use rune::{docstring, 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(docstring! {
        /// 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 = DISPLAY_FMT)]
fn display_fmt(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, 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: &'static 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: &'static 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: &'static 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: &'static 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 dyn Memory, InstAddress, usize, Output) -> 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::{Output, Memory, ToValue, VmResult, InstAddress};
use rune::{docstring, vm_try};

fn sum(stack: &mut dyn Memory, addr: InstAddress, args: usize, out: Output) -> VmResult<()> {
    let mut number = 0;

    for value in vm_try!(stack.slice_at(addr, args)) {
        number += vm_try!(value.as_integer::<i64>());
    }

    out.store(stack, number);
    VmResult::Ok(())
}

let mut module = Module::default();

module.raw_function("sum", sum)
    .build()?
    .docs(docstring! {
        /// 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 dyn Memory, InstAddress, usize, Output) -> VmResult<()> + Send + Sync, N: IntoComponent,

👎Deprecated: Use raw_function builder instead
Source

pub fn define_trait( &mut self, item: impl IntoIterator<Item: IntoComponent>, ) -> Result<TraitMut<'_>, ContextError>

Define a new trait.

Source

pub fn implement_trait<T>( &mut self, trait_item: &Item, ) -> Result<(), ContextError>
where T: ?Sized + TypeOf + Named,

Implement the trait trait_item for the type T.

Source

pub fn reexport( &mut self, item: impl IntoIterator<Item: IntoComponent>, to: &Item, ) -> Result<(), ContextError>

Define a re-export.

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 Freeze for Module

§

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

Source§

type Output = T

Should always be Self
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<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