ReefVM/examples/README.md
2025-10-05 21:29:30 -07:00

92 lines
2.6 KiB
Markdown

# Bytecode Examples
This directory contains example `.reef` bytecode files demonstrating various features of the ReefVM.
## Running Examples
You can run any example using the reef binary:
```bash
./bin/reef examples/add.reef
```
## Examples
### Basic Operations
- **add.reef** - Simple addition of two numbers
- **simple-function.reef** - Function that adds two parameters
- **arrays.reef** - Array creation and operations (MAKE_ARRAY, ARRAY_PUSH, ARRAY_GET)
- **dicts.reef** - Dictionary operations (MAKE_DICT, DICT_GET)
- **loop.reef** - Simple loop using JUMP and conditional jumps
### Advanced Function Features
- **variadic.reef** - Variadic parameters that collect remaining positional arguments (`...rest`)
- **kwargs.reef** - Named arguments that collect unmatched named args into a dict (`@kwargs`)
- **mixed-variadic-kwargs.reef** - Combining variadic positional and named arguments
- **tail-recursion.reef** - Tail-recursive factorial using TAIL_CALL
- **closure.reef** - Closures that capture variables from outer scope
### Exception Handling
- **exception-handling.reef** - Try-catch-finally blocks with PUSH_TRY, THROW, and PUSH_FINALLY
## Bytecode Syntax
The `.reef` files use the following syntax:
- Comments start with `;`
- Instructions are written as `OPCODE operand`
- Labels use `#N` for relative offsets
- Function signatures: `MAKE_FUNCTION (params) #address`
- Fixed params: `(a b c)`
- Variadic: `(a ...rest)`
- Named args: `(a @kwargs)`
- Mixed: `(a ...rest @kwargs)`
## Function Calling Convention
When calling functions, the stack must contain (bottom to top):
1. The function to call
2. Positional arguments (in order)
3. Named argument key-value pairs (key, value, key, value, ...)
4. Positional argument count
5. Named argument count
Example with positional arguments:
```
LOAD functionName ; push function onto stack
PUSH arg1 ; first positional arg
PUSH arg2 ; second positional arg
PUSH 2 ; positional count
PUSH 0 ; named count
CALL
```
Example with named arguments:
```
LOAD functionName ; push function onto stack
PUSH "key1" ; first named arg key
PUSH "value1" ; first named arg value
PUSH "key2" ; second named arg key
PUSH "value2" ; second named arg value
PUSH 0 ; positional count
PUSH 2 ; named count
CALL
```
Example with mixed arguments:
```
LOAD functionName ; push function onto stack
PUSH arg1 ; positional arg
PUSH "name" ; named arg key
PUSH "Bob" ; named arg value
PUSH 1 ; positional count
PUSH 1 ; named count
CALL
```