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 *;
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 *;
Values are exchanged as ScriptingValues.
They convert from and into bool, f64, the integer types and String with From/TryFrom.
A conversion fails if the type does not match or the value is out of range for the target integer type.
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 *;
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.
use *;
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 *;
Errors
All functions return Error:
Error::Compilationif a script is invalid, e.g. a syntax error, an unterminated string or a statement that fails to compile,Error::Executionif 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 theEnvironment,Error::DuplicateVariantif an enum value is registered twice,Error::TryConversionif aScriptingValuecannot 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::continue_run and Runtime::execute append 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 |
For no_std, disable the default features. A global allocator and a
critical-section implementation for the target are needed.
= { = "0.7", = 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.
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 |
nilsignals the absence of a value.- 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;
-5is the negation operator applied to5. A float literal needs digits on both sides of the dot:1.0, not1.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 / 2is 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' + 1is'a1'. All other arithmetic operators fail on strings.- Booleans and
nilcannot 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⁻¹⁵.
- A string holding a number is compared as that number:
'5' == 5and'5' > 3are true. <,<=,>and>=need two numbers (or numeric strings) and fail otherwise.==and!=never fail: values of different kinds are not equal, e.g.true == 1is false.- Comparisons cannot be chained, as the result is a boolean:
1 < 2 < 3is 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.!turnstrueintofalseand vice versa;!nilistrueand!of any other value isfalse.
Ternary operator if-then-else
val_b := (val_a > 1) ? 42 : 24
The condition must be a boolean; only the selected branch is evaluated.
Precedence
From highest to lowest; operators on the same level are evaluated from left to 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.
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
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.