tinyscript-derive 0.4.0

Procedural macros for tinyscript
Documentation

tinyscript - A small, C-like scripting language

tinyscript implements a small, C-like scripting language, a superset of the BehaviorTree.CPP script language. It is meant for short inline scripts, such as conditions and assignments in a behavior tree, evaluated against variables that the host application owns.

The implementation follows the pattern of clox as described in Part III of Crafting Interpreters: a script is compiled into a bytecode Chunk, which a small stack based virtual machine executes.

It supports both std and no_std environments (requires alloc).

Usage

use tinyscript::prelude::*;

fn main() -> Result<(), Box<dyn core::error::Error>> {
    let mut runtime = Runtime::default();
    let mut env = DefaultEnvironment::default();

    let value = runtime.run("2 * 2 == 4", &mut env)?;
    assert!(bool::try_from(value)?);
    Ok(())
}

A Runtime compiles and executes scripts. The variables of a script live in an Environment, a key-value store provided by the host, so they survive between script runs and the host can read and write them. DefaultEnvironment is a simple implementation for tests and the REPL.

Exchanging values with the host

use tinyscript::prelude::*;

fn main() -> Result<(), Box<dyn core::error::Error>> {
    let mut runtime = Runtime::default();
    let mut env = DefaultEnvironment::default();

    // the host provides values to the script
    env.define_env("temperature", 42.5)?;
    env.define_env("limit", 40)?;
    let value = runtime.run("temperature > limit ? 'too hot' : 'ok'", &mut env)?;
    assert_eq!(String::try_from(value)?, "too hot");

    // variables defined by a script are kept in the environment
    runtime.run("counter := 40; counter += 2", &mut env)?;
    let counter: i64 = env.get_env("counter")?.try_into()?;
    assert_eq!(counter, 42);
    Ok(())
}

Values are exchanged as ScriptingValues. They convert from and into bool, f64, f32, the integer types and String with From/TryFrom, and from &str. A conversion fails if the type does not match or the value is out of range for the target integer type or f32.

To bind scripts to your own variable storage, such as a blackboard, implement the Environment trait.

Compile once, execute often

Runtime::run compiles the script every time. For scripts that are executed repeatedly, compile them once with Runtime::parse and execute the resulting Chunk with Runtime::execute:

use tinyscript::prelude::*;

fn main() -> Result<(), Box<dyn core::error::Error>> {
    let mut runtime = Runtime::default();
    let mut env = DefaultEnvironment::default();

    env.define_env("ticks", 0)?;
    let chunk = runtime.parse("ticks += 1")?;
    for _ in 0..3 {
        runtime.execute(&chunk, &mut env)?;
    }
    assert_eq!(i64::try_from(env.get_env("ticks")?)?, 3);
    Ok(())
}

Enums

Enum values are names for integer values. They must be registered with the runtime before a script using them is compiled, as the compiler replaces them by their value. Register them one by one with Runtime::register_enum_tuple, or derive ScriptEnum for a Rust enum. The discriminants must fit into an i8, negative ones included, and the variants must have no fields.

use tinyscript::prelude::*;

#[derive(ScriptEnum)]
#[allow(dead_code)]
enum Mode {
    Off,
    Eco,
    Boost = 10,
}

fn main() -> Result<(), Box<dyn core::error::Error>> {
    let mut runtime = Runtime::default();
    let mut env = DefaultEnvironment::default();

    for (name, discriminant) in Mode::key_value_tuples() {
        runtime.register_enum_tuple(name, discriminant)?;
    }
    runtime.run("mode := Boost", &mut env)?;
    assert_eq!(i8::try_from(env.get_env("mode")?)?, 10);
    Ok(())
}

Sharing a runtime

Runtime::into_shared turns a runtime into a SharedRuntime, which can be used from several tasks or threads. It is locked with a closure, which runs within a critical section and therefore must be short and must not lock the same runtime again:

use tinyscript::prelude::*;

fn main() -> Result<(), Box<dyn core::error::Error>> {
    let shared: SharedRuntime = Runtime::default().into_shared();
    let mut env = DefaultEnvironment::default();

    let value = shared.lock(|runtime| runtime.borrow_mut().run("6 * 7", &mut env))?;
    assert_eq!(i64::try_from(value)?, 42);
    Ok(())
}

Errors

All functions return Error:

  • Error::Compilation if a script is invalid, e.g. a syntax error, an unterminated string or a statement that fails to compile,
  • Error::Execution if a script fails while it runs, e.g. an operation on incompatible types, an undefined variable, an integer division by zero or overflow, or an error reported by the Environment,
  • Error::DuplicateVariant if an enum value is registered twice,
  • Error::TryConversion if a ScriptingValue cannot be converted into the requested Rust type.

Output with print

With the feature std, print writes its value and a newline into an output buffer of the runtime, available with Runtime::stdout. Runtime::run clears that buffer before executing, Runtime::execute appends to it, and Runtime::clear clears it. Without std, print evaluates its expression and discards the value.

Features

Feature Default Description
std yes Uses the standard library; enables print output and Runtime::stdout
disassemble no Makes Chunk::disassemble public, which prints the bytecode of a compiled script; implies std. Try it with cargo run --example repl --features disassemble and the command :dis

For no_std, disable the default features. A global allocator and a critical-section implementation for the target are needed.

tinyscript = { version = "0.8", default-features = false }

The folder embedded of the repository contains examples for Ariel OS and Embassy.

The language

A script consists of statements; the result of running a script is the value of its last expression.

val_a := 7;
val_b := 5;
val_b *= 2;
(val_a * 3) + val_b

Running this script defines the variables val_a (7) and val_b (10) and returns 31.

Statements

Statements are separated by a semicolon; the last statement may or may not end with one. Line breaks are whitespace and do not separate statements. There are no comments. Operators of two characters, such as ==, := or &&, are written without whitespace in between.

print 42
print 42;
42; print 42; variable := 42; (13 + 12)

A statement is either an expression or print followed by an expression.

Result of a script

Every expression statement leaves its value on the stack of the virtual machine. The value on top of the stack, i.e. the value of the last expression, is the result of the script. Assignments and print leave no value, so a script ending with one of them returns nil.

Script Result
42; 43 43
x := 3 nil
x := 3; x > 2 true

Data types

Type Examples Stored as
Nil nil Nil
Boolean true, false Boolean
String 'hello world' String
Integer 42 Int64
Hexadecimal 0x01, 0XFF Int64
Float 3.14 Float64
Enum RED, GREEN Int64
  • nil signals the absence of a value.
  • Integers are signed 64 bit. A hexadecimal literal has up to 16 digits and stands for the 64-bit pattern, so 0xFFFFFFFFFFFFFFFF is -1 and 0x8000000000000000 is the smallest integer, which can also be written as -9223372036854775808.
  • Strings are enclosed in single quotes '...'. There are no escape sequences, so a string cannot contain a '. It may span several lines.
  • Number literals have no sign; -5 is the negation operator applied to 5. A float literal needs digits on both sides of the dot: 1.0, not 1. or .5.
  • An enum value is replaced by its integer value when the script is compiled, so under the hood an enum is always its integer value.

Variables

Variables are stored in the Environment and are global to all scripts using it. Names start with a letter, _ or @, followed by letters, digits or _; Unicode letters are allowed. Names are case sensitive. true, false, nil, print and registered enum values cannot be used as names.

Operator Description
:= Defines the variable, or sets it if it exists
= Sets an existing variable, using an undefined variable is an error
var_a := 42
var_b := 3.14
message := 'hello world'
var_a = var_a + 1

An assignment is a statement of its own, not an expression with a value, so it cannot be part of another expression or be chained like a := b := 1. It may be enclosed in parentheses if they form the whole statement, like (a := 1).

Whether a variable may change its type is up to the Environment; DefaultEnvironment allows it. Reading a variable that does not exist is an error.

Arithmetic operators

Operator Assign Operator Description
+ += Add
- -= Subtract
* *= Multiply
/ /= Divide
- Negate
+ Unary plus, no effect

a += b is the same as a = a + b, so a must exist.

  • With two integers the result is an integer; / is the integer division (5 / 2 is 2). An integer division by zero and a result that does not fit into a 64 bit integer are errors.
  • With at least one float the result is a float; a float division by zero gives an infinite value.
  • + with a string concatenates: the other value is converted to its text, 'a' + 1 is 'a1'. All other arithmetic operators fail on strings.
  • Booleans and nil cannot be used in arithmetic.
  • Negation also works on a string holding a number: -'3' is -3.

Bitwise operators

These operators work only on integer (and hexadecimal and enum) values. Using them with a string or a float is an error.

Operator Description
| Bitwise or
& Bitwise and
^ Bitwise xor
~ Bitwise not
value := 0x7F;
val_a := value & 0x0F;
val_b := value | 0xF0

The value of val_a is 0x0F (15), val_b is 0xFF (255). Note that ~0x0F is -16, as integers are signed 64 bit.

Comparison operators

Operator Description
== Equal
!= Not equal
< Less
<= Less equal
> Greater
>= Greater equal
  • Integers and floats can be compared with each other. Floats are equal if they differ by at most 2·10⁻¹⁵ times the larger of their absolute values, or by at most 2·10⁻¹⁵ near zero: 0.1 * 3.0 * 1000.0 == 300.0 is true. An infinity is equal only to the same infinity, a NaN to nothing, not even to itself.
  • A string holding a number, integer or float, is compared with a number as that number: '5' == 5, '5.0' == 5 and 5 > '4.5' are true.
  • <, <=, > and >= are false if a NaN is involved, e.g. 0.0 / 0 >= 1.
  • <, <=, > and >= need two numbers or strings holding numbers, '5' > '4' is true; they fail otherwise. Two strings are equal only if they are the same text: '5' == '5.0' is false.
  • == and != never fail: values of different kinds are not equal, e.g. true == 1 is false.
  • Comparisons cannot be chained, as the result is a boolean: 1 < 2 < 3 is an error.

Logic operators

Operator Description
&& Logic and
|| Logic or
! Logic not
val_a := true;
val_b := 5 > 3;
val_c := (val_a == val_b);
val_d := (val_a && val_b) || !val_c
  • && and || short-circuit: the right side is only evaluated if needed. The left side must be a boolean; if the right side is evaluated, its value is the result.
  • ! turns true into false and vice versa; !nil is true and ! of any other value is false.

Ternary operator if-then-else

val_b := (val_a > 1) ? 42 : 24

The condition must be a boolean; only the selected branch is evaluated. As in C, the operator associates to the right, so conditions can be chained without parentheses:

size := (x < 10) ? 'small' : (x < 20) ? 'medium' : 'large'

Precedence

From highest to lowest; operators on the same level are evaluated from left to right, except the ternary operator, which associates to the right. Parentheses ( ) group expressions.

Operators Description
! - + ~ Unary
* / Multiplicative
+ - Additive
< <= > >= Comparison
== != Equality
& Bitwise and
^ Bitwise xor
| Bitwise or
&& Logic and
|| Logic or
? : Ternary
:= = += -= *= /= Assignment

As in C, the bitwise operators bind weaker than the comparisons: x & 1 == 1 is x & (1 == 1), write (x & 1) == 1.

Limits

tinyscript is made for short scripts and its limits are small:

  • The stack of the virtual machine holds 8 values. As every expression statement leaves its value on the stack, a script can contain at most 8 expression statements that are neither assignments nor print. Deeply nested expressions need stack space too. Exceeding the stack is an execution error.
  • A script can contain at most 255 constants. Every literal and every use of a variable name counts as one. Exceeding this is a compilation error.
  • A script compiles to at most 64 KiB of bytecode, about one byte per operator and two per value. Exceeding this is a compilation error.

License

Licensed under either of

at your option.

Contribution

Any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions.