Attribute Macro starlark_module::starlark_module [−][src]
#[starlark_module]
Write Starlark modules concisely in Rust syntax.
For example:
ⓘ
#[starlark_module] fn global(registry: &mut GlobalsBuilder) { fn cc_binary(name: &str, srcs: Vec<&str>) -> String { Ok(format!("{:?} {:?}", name, srcs)) } }
Parameters operate as named parameters of a given type, with five possible tweaks:
args
means the argument is the*args
.kwargs
means the argument is the**kwargs
.ref name
means the argument must be passed by position, not by name.- A type of
Option
means the argument is optional. - A pattern
x @ foo : bool
means the argument defaults tofoo
if not specified.
During execution there are two local variables injected into scope:
ctx
is theEvaluator
.heap
is theHeap
, obtained fromctx.heap()
.
A function with the #[starlark_module]
attribute can be added to a GlobalsBuilder
value
using the with
function. Those Globals
can be passed to Evaluator
to provide global functions.
Alternatively, you can return Globals
from get_members
to attach functions to
a specific type (e.g. the string
type).
- When unattached, you can define constants with
const
. We defineTrue
,False
andNone
that way. - When attached, you can annotate the functions with
#[attribute]
to turn the name into an attribute on the value. Such a function must take exactly one argument, namely a value of the type you have attached it to. - The attribute
#[starlark_type("test")]
causesf.type
to return"test"
.
All these functions interoperate properly with dir()
, getattr()
and hasattr()
.
If a desired function name is also a Rust keyword, use the r#
prefix, e.g. r#type
.