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<I>(iter: I) -> Result<Self, ContextError>
pub fn with_item<I>(iter: I) -> 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<I>(name: &str, iter: I) -> Result<Self, ContextError>
pub fn with_crate_item<I>(name: &str, iter: I) -> 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 generator_state<N>(
&mut self,
name: N,
) -> Result<InternalEnumMut<'_, GeneratorState>, ContextError>where
N: IntoComponent,
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>(())
Sourcepub fn option<N>(
&mut self,
name: N,
) -> Result<InternalEnumMut<'_, Option<Value>>, ContextError>where
N: IntoComponent,
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>(())
Sourcepub fn result<N>(
&mut self,
name: N,
) -> Result<InternalEnumMut<'_, Result<Value, Value>>, ContextError>where
N: IntoComponent,
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>(())
Sourcepub fn constant<N, V>(
&mut self,
name: N,
value: V,
) -> ModuleConstantBuilder<'_, N, V>where
V: ToValue,
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."]);
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::{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)?;
Sourcepub fn function<F, A, N, K>(
&mut self,
name: N,
f: F,
) -> ModuleFunctionBuilder<'_, F, A, N, K>
pub fn function<F, A, N, K>( &mut self, name: N, f: F, ) -> ModuleFunctionBuilder<'_, F, A, N, K>
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."]);
Sourcepub fn function2<F, A, N, K>(
&mut self,
name: N,
f: F,
) -> Result<ModuleFunctionBuilder<'_, F, A, N, K>, ContextError>
👎Deprecated: Use Module::function
pub fn function2<F, A, N, K>( &mut self, name: N, f: F, ) -> Result<ModuleFunctionBuilder<'_, F, A, N, K>, ContextError>
Module::function
See Module::function
.
Sourcepub fn async_function<F, A, N>(
&mut self,
name: N,
f: F,
) -> Result<ItemFnMut<'_>, ContextError>
👎Deprecated: Use Module::function() instead
pub fn async_function<F, A, N>( &mut self, name: N, f: F, ) -> Result<ItemFnMut<'_>, ContextError>
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 = 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)?;
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>
👎Deprecated: Use Module::associated_function() instead
pub fn async_inst_fn<N, F, A>( &mut self, name: N, f: F, ) -> Result<ItemFnMut<'_>, ContextError>
Sourcepub fn field_function<N, F, A>(
&mut self,
protocol: Protocol,
name: N,
f: F,
) -> Result<ItemFnMut<'_>, ContextError>
pub fn field_function<N, F, A>( &mut self, protocol: Protocol, name: N, f: F, ) -> Result<ItemFnMut<'_>, ContextError>
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: Protocol,
name: N,
f: F,
) -> Result<ItemFnMut<'_>, ContextError>
👎Deprecated: Use Module::field_function() instead
pub fn field_fn<N, F, A>( &mut self, protocol: Protocol, name: N, f: F, ) -> Result<ItemFnMut<'_>, ContextError>
Sourcepub fn index_function<F, A>(
&mut self,
protocol: Protocol,
index: usize,
f: F,
) -> Result<ItemFnMut<'_>, ContextError>
pub fn index_function<F, A>( &mut self, protocol: Protocol, index: usize, f: F, ) -> Result<ItemFnMut<'_>, ContextError>
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: Protocol,
index: usize,
f: F,
) -> Result<ItemFnMut<'_>, ContextError>
👎Deprecated: Use Module::index_function() instead
pub fn index_fn<F, A>( &mut self, protocol: Protocol, index: usize, f: F, ) -> Result<ItemFnMut<'_>, ContextError>
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::{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."
])?;
Sourcepub fn raw_fn<F, N>(
&mut self,
name: N,
f: F,
) -> Result<ItemFnMut<'_>, ContextError>
👎Deprecated: Use raw_function
builder instead
pub fn raw_fn<F, N>( &mut self, name: N, f: F, ) -> Result<ItemFnMut<'_>, ContextError>
raw_function
builder insteadSee Module::raw_function
.