forked from defunkt/ReefVM
2.9 KiB
2.9 KiB
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:
./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) - named.reef - Named arguments that collect unmatched named args into a dict (
@named) - mixed-variadic-named.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:
- Definition:
.label_name:marks an instruction position - Reference:
.label_namein operands (e.g.,JUMP .loop_start) - Also supports numeric offsets:
#Nfor relative offsets
- Definition:
- Function signatures:
MAKE_FUNCTION (params) address- Address can be a label
.bodyor numeric offset#7 - Fixed params:
(a b c) - Variadic:
(a ...rest) - Named args:
(a @named) - Mixed:
(a ...rest @named)
- Address can be a label
Function Calling Convention
When calling functions, the stack must contain (bottom to top):
- The function to call
- Positional arguments (in order)
- Named argument key-value pairs (key, value, key, value, ...)
- Positional argument count
- Named argument count
Example with positional arguments:
MAKE_FUNCTION (a b) .add_body
PUSH arg1 ; first positional arg
PUSH arg2 ; second positional arg
PUSH 2 ; positional count
PUSH 0 ; named count
CALL
HALT
.add_body:
LOAD a
LOAD b
ADD
RETURN
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