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
impl Module
Sourcepub fn with_item(
iter: impl IntoIterator<Item: IntoComponent>,
) -> Result<Self, ContextError>
pub fn with_item( iter: impl IntoIterator<Item: IntoComponent>, ) -> Result<Self, ContextError>
Construct a new module for the given item.
Sourcepub fn with_crate(name: &str) -> Result<Self, ContextError>
pub fn with_crate(name: &str) -> Result<Self, ContextError>
Construct a new module for the given crate.
Sourcepub fn with_crate_item(
name: &str,
iter: impl IntoIterator<Item: IntoComponent>,
) -> Result<Self, ContextError>
pub fn with_crate_item( name: &str, iter: impl IntoIterator<Item: IntoComponent>, ) -> Result<Self, ContextError>
Construct a new module for the given crate.
Sourcepub fn from_meta(module_meta: ModuleMeta) -> Result<Self, ContextError>
pub fn from_meta(module_meta: ModuleMeta) -> Result<Self, ContextError>
Construct a new module from the given module meta.
Sourcepub fn ty<T>(&mut self) -> Result<TypeMut<'_, T>, ContextError>
pub fn ty<T>(&mut self) -> Result<TypeMut<'_, T>, ContextError>
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());
Sourcepub fn type_meta<T>(&mut self) -> Result<TypeMut<'_, T>, ContextError>
pub fn type_meta<T>(&mut self) -> Result<TypeMut<'_, T>, ContextError>
Accessor to modify type metadata such as documentaiton, fields, variants.
Sourcepub fn struct_meta<T>(
&mut self,
fields: &'static [&'static str],
) -> Result<(), ContextError>
👎Deprecated: Use type_meta::<T>().make_struct(fields) instead
pub fn struct_meta<T>( &mut self, fields: &'static [&'static str], ) -> Result<(), ContextError>
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.
Sourcepub fn variant_meta<T>(
&mut self,
index: usize,
) -> Result<VariantMut<'_, T>, ContextError>
pub fn variant_meta<T>( &mut self, index: usize, ) -> Result<VariantMut<'_, T>, ContextError>
Access variant metadata for the given type and the index of its variant.
Sourcepub fn variant_constructor<F, A>(
&mut self,
index: usize,
constructor: F,
) -> Result<(), ContextError>
👎Deprecated: Use variant_meta() instead
pub fn variant_constructor<F, A>( &mut self, index: usize, constructor: F, ) -> Result<(), ContextError>
Register a variant constructor for type T
.
Sourcepub fn constant<N, V>(
&mut self,
name: N,
value: V,
) -> ModuleConstantBuilder<'_, N, V>
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.
});
Sourcepub fn macro_meta(
&mut self,
meta: fn() -> Result<MacroMetaData>,
) -> Result<ItemMut<'_>, ContextError>
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>(())
Sourcepub 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,
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>(())
Sourcepub 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,
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>(())
Sourcepub fn function_meta(
&mut self,
meta: fn() -> Result<FunctionMetaData>,
) -> Result<ItemFnMut<'_>, ContextError>
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)?;
Sourcepub 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,
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.
});
Sourcepub 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
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,
Module::function
See Module::function
.
Sourcepub 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
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,
See Module::function
.
Sourcepub 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,
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)?;
Sourcepub 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
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,
Sourcepub 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
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,
Sourcepub 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,
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.
Sourcepub 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
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,
Sourcepub 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,
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.
Sourcepub 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
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,
Sourcepub fn raw_function<F, N>(
&mut self,
name: N,
f: F,
) -> ModuleRawFunctionBuilder<'_, N>
pub fn raw_function<F, N>( &mut self, name: N, f: F, ) -> ModuleRawFunctionBuilder<'_, N>
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.
})?;
Sourcepub 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
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,
raw_function
builder insteadSee Module::raw_function
.
Sourcepub fn define_trait(
&mut self,
item: impl IntoIterator<Item: IntoComponent>,
) -> Result<TraitMut<'_>, ContextError>
pub fn define_trait( &mut self, item: impl IntoIterator<Item: IntoComponent>, ) -> Result<TraitMut<'_>, ContextError>
Define a new trait.
Sourcepub fn implement_trait<T>(
&mut self,
trait_item: &Item,
) -> Result<(), ContextError>
pub fn implement_trait<T>( &mut self, trait_item: &Item, ) -> Result<(), ContextError>
Implement the trait trait_item
for the type T
.
Sourcepub fn reexport(
&mut self,
item: impl IntoIterator<Item: IntoComponent>,
to: &Item,
) -> Result<(), ContextError>
pub fn reexport( &mut self, item: impl IntoIterator<Item: IntoComponent>, to: &Item, ) -> Result<(), ContextError>
Define a re-export.