Attribute Macro starlark::starlark_module[][src]

#[starlark_module]
Expand description

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 six possible tweaks:

  • this (or _this) as the first argument means the argument is passed as a bound method value, e.g. in a.f(...) the a would be this.
  • 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 to foo if not specified.

During execution there are two local variables injected into scope:

  • eval is the Evaluator.
  • heap is the Heap, obtained from eval.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_methods to attach functions to a specific type (e.g. the string type).

  • When unattached, you can define constants with const. We define True, False and None that way.
  • When attached, you can annotate the functions with #[starlark(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"))] causes f.type to return "test".
  • If a member is annotated with #[starlark(speculative_exec_safe)], then a function is considered safe to execute speculatively: the function should have no global side effects, should not panic, and should finish in reasonable time. The evaluator may invoke such functions early to generate more efficient code.

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.