tinyscript-derive 0.4.0

Procedural macros for tinyscript
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# tinyscript - A small, C-like scripting language

`tinyscript` implements a small, C-like scripting language, a superset of the
[BehaviorTree.CPP script language](https://www.behaviortree.dev/docs/guides/scripting).
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](https://craftinginterpreters.com/): 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

```rust
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

```rust
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 [`ScriptingValue`]s.
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`]:

```rust
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.

```rust
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:

```rust
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`](https://crates.io/crates/critical-section) implementation for the target are needed.

```toml
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.

```text
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.

```text
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 |

```text
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 |

```text
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   |

```text
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**

```text
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:

```text
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

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE or <http://www.apache.org/licenses/LICENSE-2.0>)
- MIT license ([LICENSE-MIT]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.

[`Runtime`]: https://docs.rs/tinyscript/latest/tinyscript/struct.Runtime.html
[`Runtime::run`]: https://docs.rs/tinyscript/latest/tinyscript/struct.Runtime.html#method.run
[`Runtime::parse`]: https://docs.rs/tinyscript/latest/tinyscript/struct.Runtime.html#method.parse
[`Runtime::execute`]: https://docs.rs/tinyscript/latest/tinyscript/struct.Runtime.html#method.execute
[`Runtime::clear`]: https://docs.rs/tinyscript/latest/tinyscript/struct.Runtime.html#method.clear
[`Runtime::stdout`]: https://docs.rs/tinyscript/latest/tinyscript/struct.Runtime.html#method.stdout
[`Runtime::register_enum_tuple`]: https://docs.rs/tinyscript/latest/tinyscript/struct.Runtime.html#method.register_enum_tuple
[`Runtime::into_shared`]: https://docs.rs/tinyscript/latest/tinyscript/struct.Runtime.html#method.into_shared
[`SharedRuntime`]: https://docs.rs/tinyscript/latest/tinyscript/type.SharedRuntime.html
[`Environment`]: https://docs.rs/tinyscript/latest/tinyscript/trait.Environment.html
[`DefaultEnvironment`]: https://docs.rs/tinyscript/latest/tinyscript/struct.DefaultEnvironment.html
[`ScriptingValue`]: https://docs.rs/tinyscript/latest/tinyscript/enum.ScriptingValue.html
[`ScriptEnum`]: https://docs.rs/tinyscript/latest/tinyscript/derive.ScriptEnum.html
[`Chunk`]: https://docs.rs/tinyscript/latest/tinyscript/struct.Chunk.html
[`Error`]: https://docs.rs/tinyscript/latest/tinyscript/enum.Error.html