update some docs and project clean up (only runtime
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
< [Back](chapter-14.md) | [Summary](table-of-contents.md) >
|
||||
< [Back](chapter-14.md) | [Summary](table-of-contents.md) | [Next](chapter-16.md) >
|
||||
|
||||
# Asset Management
|
||||
|
||||
@@ -328,4 +328,4 @@ Where:
|
||||
> **Asset Types describe content.**
|
||||
> **The SDK orchestrates; the hardware executes.**
|
||||
|
||||
< [Back](chapter-14.md) | [Summary](table-of-contents.md) >
|
||||
< [Back](chapter-14.md) | [Summary](table-of-contents.md) | [Next](chapter-16.md) >
|
||||
@@ -0,0 +1,294 @@
|
||||
< [Back](chapter-15.md) | [Summary](table-of-contents.md) >
|
||||
|
||||
# **Host ABI and Syscalls**
|
||||
|
||||
This chapter defines the Application Binary Interface (ABI) between the Prometeu Virtual Machine (PVM) and the host environment. It specifies how syscalls are encoded, invoked, verified, and accounted for.
|
||||
|
||||
Syscalls provide controlled access to host-managed subsystems such as graphics, audio, input, asset banks, and persistent storage.
|
||||
|
||||
This chapter defines the **contract**. Individual subsystems (GFX, AUDIO, MEMCARD, ASSETS, etc.) define their own syscall tables that conform to this ABI.
|
||||
|
||||
---
|
||||
|
||||
## 1 Design Principles
|
||||
|
||||
The syscall system follows these rules:
|
||||
|
||||
1. **Deterministic**: Syscalls must behave deterministically for the same inputs and frame state.
|
||||
2. **Synchronous**: Syscalls execute to completion within the current VM slice.
|
||||
3. **Non-blocking**: Long operations must be modeled as request + status polling.
|
||||
4. **Capability-gated**: Each syscall requires a declared capability.
|
||||
5. **Stack-based ABI**: Arguments and return values are passed via VM slots.
|
||||
6. **Not first-class**: Syscalls are callable but cannot be stored as values.
|
||||
|
||||
---
|
||||
|
||||
## 2 Syscall Instruction Semantics
|
||||
|
||||
The VM provides a single instruction:
|
||||
|
||||
```
|
||||
SYSCALL <id>
|
||||
```
|
||||
|
||||
Where:
|
||||
|
||||
* `<id>` is a 32-bit integer identifying the syscall.
|
||||
|
||||
Execution steps:
|
||||
|
||||
1. The VM looks up the syscall metadata using `<id>`.
|
||||
2. The VM verifies that enough arguments exist on the stack.
|
||||
3. The VM checks capability requirements.
|
||||
4. The syscall executes in the host environment.
|
||||
5. The syscall leaves exactly `ret_slots` values on the stack.
|
||||
|
||||
If any contract rule is violated, the VM traps.
|
||||
|
||||
---
|
||||
|
||||
## 3 Syscall Metadata Table
|
||||
|
||||
Each syscall is defined by a metadata entry.
|
||||
|
||||
### SyscallMeta structure
|
||||
|
||||
```
|
||||
SyscallMeta {
|
||||
id: u32
|
||||
name: string
|
||||
arg_slots: u8
|
||||
ret_slots: u8
|
||||
capability: CapabilityId
|
||||
may_allocate: bool
|
||||
cost_hint: u32
|
||||
}
|
||||
```
|
||||
|
||||
Fields:
|
||||
|
||||
| Field | Description |
|
||||
| -------------- | ------------------------------------------------ |
|
||||
| `id` | Unique syscall identifier |
|
||||
| `name` | Human-readable name |
|
||||
| `arg_slots` | Number of input stack slots |
|
||||
| `ret_slots` | Number of return stack slots |
|
||||
| `capability` | Required capability |
|
||||
| `may_allocate` | Whether the syscall may allocate VM heap objects |
|
||||
| `cost_hint` | Expected cycle cost (for analysis/profiling) |
|
||||
|
||||
The verifier uses this table to validate stack effects.
|
||||
|
||||
---
|
||||
|
||||
## 4 Arguments and Return Values
|
||||
|
||||
Syscalls use the same slot-based ABI as functions.
|
||||
|
||||
### Argument passing
|
||||
|
||||
Arguments are pushed onto the stack before the syscall.
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
push a
|
||||
push b
|
||||
SYSCALL X // expects 2 arguments
|
||||
```
|
||||
|
||||
### Return values
|
||||
|
||||
After execution, the syscall leaves exactly `ret_slots` values on the stack.
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
// before: []
|
||||
SYSCALL input_state
|
||||
// after: [held, pressed, released]
|
||||
```
|
||||
|
||||
### Slot types
|
||||
|
||||
Each slot contains one of the VM value types:
|
||||
|
||||
* int
|
||||
* bool
|
||||
* float
|
||||
* handle
|
||||
* null
|
||||
|
||||
Composite return values are represented as multiple slots (stack tuples).
|
||||
|
||||
---
|
||||
|
||||
## 5 Syscalls as Callable Entities (Not First-Class)
|
||||
|
||||
Syscalls behave like functions in terms of arguments and return values, but they are **not first-class values**.
|
||||
|
||||
This means:
|
||||
|
||||
* Syscalls can be invoked.
|
||||
* Syscalls cannot be stored in variables.
|
||||
* Syscalls cannot be passed as arguments.
|
||||
* Syscalls cannot be returned from functions.
|
||||
|
||||
Only user-defined functions and closures are first-class.
|
||||
|
||||
### Example declaration (conceptual)
|
||||
|
||||
```
|
||||
host fn input_state() -> (int, int, int)
|
||||
```
|
||||
|
||||
This represents a syscall with three return values, but it cannot be treated as a function value.
|
||||
|
||||
---
|
||||
|
||||
## 6 Error Model: Traps vs Status Codes
|
||||
|
||||
Syscalls use a hybrid error model.
|
||||
|
||||
### Trap conditions (contract violations)
|
||||
|
||||
The VM traps when:
|
||||
|
||||
* The syscall id is invalid.
|
||||
* The required capability is missing.
|
||||
* The stack does not contain enough arguments.
|
||||
* A handle is invalid or dead.
|
||||
|
||||
These are considered fatal contract violations.
|
||||
|
||||
### Status returns (domain conditions)
|
||||
|
||||
Normal operational states are returned as values.
|
||||
|
||||
Examples:
|
||||
|
||||
* asset not yet loaded
|
||||
* audio voice unavailable
|
||||
* memcard full
|
||||
|
||||
These are represented by status codes in return slots.
|
||||
|
||||
---
|
||||
|
||||
## 7 Capability System
|
||||
|
||||
Each syscall requires a capability.
|
||||
|
||||
Capabilities are declared by the cartridge manifest.
|
||||
|
||||
Example capability groups:
|
||||
|
||||
* `gfx`
|
||||
* `audio`
|
||||
* `input`
|
||||
* `asset`
|
||||
* `memcard`
|
||||
|
||||
If a syscall is invoked without the required capability:
|
||||
|
||||
* The VM traps.
|
||||
|
||||
---
|
||||
|
||||
## 8 Interaction with the Garbage Collector
|
||||
|
||||
The VM heap is managed by the GC. Host-managed memory is separate.
|
||||
|
||||
### Heap vs host memory
|
||||
|
||||
| Memory | Managed by | GC scanned |
|
||||
| --------------- | ---------- | ---------- |
|
||||
| VM heap objects | VM GC | Yes |
|
||||
| Asset banks | Host | No |
|
||||
| Audio buffers | Host | No |
|
||||
| Framebuffers | Host | No |
|
||||
|
||||
Assets are addressed by identifiers, not VM heap handles.
|
||||
|
||||
### Host root rule
|
||||
|
||||
If a syscall stores a handle to a VM heap object beyond the duration of the call, it must register that handle as a **host root**.
|
||||
|
||||
This prevents the GC from collecting objects still in use by the host.
|
||||
|
||||
This rule applies only to VM heap objects (such as closures or user objects), not to asset identifiers or primitive values.
|
||||
|
||||
---
|
||||
|
||||
## 9 Determinism Rules
|
||||
|
||||
Syscalls must obey deterministic execution rules.
|
||||
|
||||
Forbidden behaviors:
|
||||
|
||||
* reading real-time clocks
|
||||
* accessing non-deterministic OS APIs
|
||||
* performing blocking I/O
|
||||
|
||||
Allowed patterns:
|
||||
|
||||
* frame-based timers
|
||||
* request + poll status models
|
||||
* event delivery at frame boundaries
|
||||
|
||||
---
|
||||
|
||||
## 10 Cost Model and Budgeting
|
||||
|
||||
Each syscall contributes to frame cost.
|
||||
|
||||
The VM tracks:
|
||||
|
||||
* cycles spent in syscalls
|
||||
* syscall counts
|
||||
* allocation cost (if any)
|
||||
|
||||
Example telemetry:
|
||||
|
||||
```
|
||||
Frame 10231:
|
||||
Syscalls: 12
|
||||
Cycles (syscalls): 380
|
||||
Allocations via syscalls: 2
|
||||
```
|
||||
|
||||
Nothing is free.
|
||||
|
||||
---
|
||||
|
||||
## 11 Blocking and Long Operations
|
||||
|
||||
Syscalls must not block.
|
||||
|
||||
Long operations must use a two-phase model:
|
||||
|
||||
1. Request
|
||||
2. Status polling or event notification
|
||||
|
||||
Example pattern:
|
||||
|
||||
```
|
||||
asset.load(id)
|
||||
...
|
||||
status, progress = asset.status(id)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 12 Summary
|
||||
|
||||
* Syscalls are deterministic, synchronous, and non-blocking.
|
||||
* They use the same slot-based ABI as functions.
|
||||
* They are callable but not first-class.
|
||||
* Capabilities control access to host subsystems.
|
||||
* GC only manages VM heap objects.
|
||||
* Host-held heap objects must be registered as roots.
|
||||
* All syscall costs are tracked per frame.
|
||||
|
||||
|
||||
< [Back](chapter-15.md) | [Summary](table-of-contents.md) >
|
||||
@@ -1,457 +1,427 @@
|
||||
< [Back](chapter-1.md) | [Summary](table-of-contents.md) | [Next](chapter-3.md) >
|
||||
|
||||
# ⚙️ ** PVM (PROMETEU VM) — Instruction Set**
|
||||
# **Prometeu Virtual Machine (PVM)**
|
||||
|
||||
## 1. Overview
|
||||
This chapter defines the execution model, value system, calling convention, memory model, and host interface of the Prometeu Virtual Machine.
|
||||
|
||||
The **PROMETEU VM** is a mandatory virtual machine always present in the logical hardware:
|
||||
The PVM is a **deterministic, stack-based VM** designed for a 2D fantasy console environment. Its primary goal is to provide predictable performance, safe memory access, and a stable execution contract suitable for real-time games running at a fixed frame rate. fileciteturn2file0
|
||||
|
||||
* **stack-based**
|
||||
---
|
||||
|
||||
## 1 Core Design Principles
|
||||
|
||||
The PVM is designed around the following constraints:
|
||||
|
||||
1. **Deterministic execution**: no hidden threads or asynchronous callbacks.
|
||||
2. **Frame-based timing**: execution is bounded by frame time.
|
||||
3. **Safe memory model**: all heap objects are accessed through handles.
|
||||
4. **Simple compilation target**: stack-based bytecode with verified control flow.
|
||||
5. **Stable ABI**: multi-value returns with fixed slot semantics.
|
||||
6. **First-class functions**: functions can be passed, stored, and returned.
|
||||
|
||||
---
|
||||
|
||||
## 2 Execution Model
|
||||
|
||||
The PVM executes bytecode in a **frame loop**. Each frame:
|
||||
|
||||
1. The firmware enters the VM.
|
||||
2. The VM runs until:
|
||||
|
||||
* the frame budget is consumed, or
|
||||
* a `FRAME_SYNC` instruction is reached.
|
||||
3. At `FRAME_SYNC`:
|
||||
|
||||
* events are delivered
|
||||
* input is sampled
|
||||
* optional GC may run
|
||||
4. Control returns to the firmware.
|
||||
|
||||
`FRAME_SYNC` is the **primary safepoint** in the system.
|
||||
|
||||
---
|
||||
|
||||
## 3 Value Types
|
||||
|
||||
All runtime values are stored in VM slots as a `Value`.
|
||||
|
||||
### Primitive value types (stack values)
|
||||
|
||||
| Type | Description |
|
||||
| ------- | --------------------- |
|
||||
| `int` | 64-bit signed integer |
|
||||
| `bool` | Boolean value |
|
||||
| `float` | 64-bit floating point |
|
||||
|
||||
### Built-in vector and graphics types (stack values)
|
||||
|
||||
These are treated as VM primitives with dedicated opcodes:
|
||||
|
||||
| Type | Description |
|
||||
| ------- | --------------------------------- |
|
||||
| `vec2` | 2D vector (x, y) |
|
||||
| `color` | Packed color value |
|
||||
| `pixel` | Combination of position and color |
|
||||
|
||||
These types:
|
||||
|
||||
* live entirely on the stack
|
||||
* are copied by value
|
||||
* never allocate on the heap
|
||||
|
||||
### Heap values
|
||||
|
||||
All user-defined objects live on the heap and are accessed via **handles**.
|
||||
|
||||
| Type | Description |
|
||||
| -------- | -------------------------- |
|
||||
| `handle` | Reference to a heap object |
|
||||
| `null` | Null handle |
|
||||
|
||||
Handles may refer to:
|
||||
|
||||
* user objects
|
||||
* arrays
|
||||
* strings
|
||||
* closures
|
||||
|
||||
---
|
||||
|
||||
## 4 Handles and Gate Table
|
||||
|
||||
Heap objects are accessed through **handles**. A handle is a pair:
|
||||
|
||||
```
|
||||
handle = { index, generation }
|
||||
```
|
||||
|
||||
The VM maintains a **gate table**:
|
||||
|
||||
```
|
||||
GateEntry {
|
||||
alive: bool
|
||||
generation: u32
|
||||
base: usize
|
||||
slots: u32
|
||||
type_id: u32
|
||||
}
|
||||
```
|
||||
|
||||
When an object is freed:
|
||||
|
||||
* its gate entry is marked dead
|
||||
* its generation is incremented
|
||||
|
||||
If a handle’s generation does not match the gate entry, the VM traps.
|
||||
|
||||
This prevents use-after-free bugs.
|
||||
|
||||
---
|
||||
|
||||
## 5 Heap Model
|
||||
|
||||
* All user objects live in the heap.
|
||||
* Objects are fixed-layout blocks of slots.
|
||||
* No inheritance at the memory level.
|
||||
* Traits/interfaces are resolved by the compiler or via vtables.
|
||||
|
||||
Built-in types remain stack-only.
|
||||
|
||||
Heap objects include:
|
||||
|
||||
* user structs/classes
|
||||
* strings
|
||||
* arrays
|
||||
* closures
|
||||
|
||||
---
|
||||
|
||||
## 6 Tuples and Multi-Return ABI
|
||||
|
||||
The PVM supports **multi-value returns**.
|
||||
|
||||
### Tuple rules
|
||||
|
||||
* Tuples are **stack-only**.
|
||||
* Maximum tuple arity is **N = 6**.
|
||||
* Tuples are not heap objects by default.
|
||||
* To persist a tuple, it must be explicitly boxed.
|
||||
|
||||
### Call convention
|
||||
|
||||
Each function declares a fixed `ret_slots` value.
|
||||
|
||||
At call time:
|
||||
|
||||
1. Caller prepares arguments.
|
||||
2. `CALL` transfers control.
|
||||
3. Callee executes.
|
||||
4. `RET` leaves exactly `ret_slots` values on the stack.
|
||||
|
||||
The verifier ensures that:
|
||||
|
||||
* all control paths produce the same `ret_slots`
|
||||
* stack depth is consistent.
|
||||
|
||||
---
|
||||
|
||||
## 7 Call Stack and Frames
|
||||
|
||||
The VM uses a **call stack**.
|
||||
|
||||
Each frame contains:
|
||||
|
||||
```
|
||||
Frame {
|
||||
return_pc
|
||||
base_pointer
|
||||
ret_slots
|
||||
}
|
||||
```
|
||||
|
||||
Execution uses only the following call instructions:
|
||||
|
||||
| Opcode | Description |
|
||||
| ------ | ---------------------- |
|
||||
| `CALL` | Calls a function by id |
|
||||
| `RET` | Returns from function |
|
||||
|
||||
There is no separate `PUSH_FRAME` or `POP_FRAME` instruction in the public ISA.
|
||||
|
||||
---
|
||||
|
||||
## 8 Closures and First-Class Functions
|
||||
|
||||
Closures are heap objects and represent **function values**.
|
||||
|
||||
The PVM treats functions as **first-class values**. This means:
|
||||
|
||||
* Functions can be stored in variables.
|
||||
* Functions can be passed as arguments.
|
||||
* Functions can be returned from other functions.
|
||||
* All function values are represented as closures.
|
||||
|
||||
Even functions without captures are represented as closures with an empty capture set.
|
||||
|
||||
### Closure layout
|
||||
|
||||
```
|
||||
Closure {
|
||||
func_id
|
||||
captures[]
|
||||
}
|
||||
```
|
||||
|
||||
Captures are stored as handles or value copies.
|
||||
|
||||
All closure environments are part of the GC root set.
|
||||
|
||||
### Direct and indirect calls
|
||||
|
||||
The PVM supports two forms of function invocation:
|
||||
|
||||
| Opcode | Description |
|
||||
| -------------- | -------------------------------------- |
|
||||
| `CALL` | Direct call by function id |
|
||||
| `CALL_CLOSURE` | Indirect call through a closure handle |
|
||||
|
||||
For `CALL_CLOSURE`:
|
||||
|
||||
1. The closure handle is read from the stack.
|
||||
2. The VM extracts the `func_id` from the closure.
|
||||
3. The function is invoked using the closure’s captures as its environment.
|
||||
|
||||
The verifier ensures that:
|
||||
|
||||
* The closure handle is valid.
|
||||
* The target function’s arity matches the call site.
|
||||
* The `ret_slots` contract is respected.
|
||||
|
||||
---
|
||||
|
||||
## 9 Coroutines (Deterministic)
|
||||
|
||||
The PVM supports **cooperative coroutines**.
|
||||
|
||||
Characteristics:
|
||||
|
||||
* Coroutines are scheduled deterministically.
|
||||
* No preemption.
|
||||
* No parallel execution.
|
||||
* All scheduling happens at safepoints.
|
||||
|
||||
Each coroutine contains:
|
||||
|
||||
```
|
||||
Coroutine {
|
||||
call_stack
|
||||
operand_stack
|
||||
state
|
||||
}
|
||||
```
|
||||
|
||||
### Coroutine instructions
|
||||
|
||||
| Opcode | Description |
|
||||
| ------- | -------------------------- |
|
||||
| `SPAWN` | Creates a coroutine |
|
||||
| `YIELD` | Suspends current coroutine |
|
||||
| `SLEEP` | Suspends for N frames |
|
||||
|
||||
Scheduling is:
|
||||
|
||||
* round-robin
|
||||
* deterministic
|
||||
* cycle-oriented
|
||||
* designed for teaching and inspection
|
||||
* bounded by frame budget
|
||||
|
||||
It exists to:
|
||||
|
||||
* map high-level language concepts
|
||||
* make computational cost visible
|
||||
* allow execution analysis
|
||||
* serve as the foundation of the PROMETEU cartridge
|
||||
|
||||
> The PROMETEU VM is simple by choice.
|
||||
> Simplicity is a pedagogical tool.
|
||||
Coroutine stacks are part of the GC root set.
|
||||
|
||||
---
|
||||
|
||||
## 2. Execution Model
|
||||
## 10 Garbage Collection
|
||||
|
||||
### 2.1 Main Components
|
||||
The PVM uses a **mark-sweep collector**.
|
||||
|
||||
The VM has:
|
||||
### GC rules
|
||||
|
||||
* **PC (Program Counter)** — next instruction
|
||||
* **Operand Stack** — value stack
|
||||
* **Call Stack** — stores execution frames for function calls
|
||||
* **Scope Stack** — stores frames for blocks within a function
|
||||
* **Heap** — dynamic memory
|
||||
* **Globals** — global variables
|
||||
* **Constant Pool** — literals and references
|
||||
* **ROM** — cartridge bytecode
|
||||
* **RAM** — mutable data
|
||||
* GC runs only at **safepoints**.
|
||||
* The primary safepoint is `FRAME_SYNC`.
|
||||
* GC is triggered by:
|
||||
|
||||
* heap thresholds, or
|
||||
* allocation pressure.
|
||||
|
||||
### Root set
|
||||
|
||||
The GC marks from:
|
||||
|
||||
* operand stack
|
||||
* call stack frames
|
||||
* global variables
|
||||
* coroutine stacks
|
||||
* closure environments
|
||||
* host-held handles
|
||||
|
||||
The collector:
|
||||
|
||||
* does not compact memory (v1)
|
||||
* uses free lists for reuse
|
||||
|
||||
---
|
||||
|
||||
### 2.2 Execution Cycle
|
||||
## 11 Event and Interrupt Model
|
||||
|
||||
Each instruction executes:
|
||||
The PVM does not allow asynchronous callbacks.
|
||||
|
||||
```
|
||||
FETCH → DECODE → EXECUTE → ADVANCE PC
|
||||
```
|
||||
All events are:
|
||||
|
||||
Properties:
|
||||
* queued by the firmware
|
||||
* delivered at `FRAME_SYNC`
|
||||
|
||||
* every instruction has a fixed cost in cycles
|
||||
* there is no invisible implicit work
|
||||
* execution is fully deterministic
|
||||
This ensures:
|
||||
|
||||
---
|
||||
|
||||
## 3. Fundamental Types
|
||||
|
||||
| Type | Description |
|
||||
| --------- | ------------------------- |
|
||||
| `int32` | 32-bit signed integer |
|
||||
| `int64` | 64-bit signed integer |
|
||||
| `float` | 64-bit floating point |
|
||||
| `boolean` | true/false |
|
||||
| `string` | immutable UTF-8 |
|
||||
| `null` | absence of value |
|
||||
| `ref` | heap reference |
|
||||
|
||||
### 3.1 Numeric Promotion
|
||||
The VM promotes types automatically during operations:
|
||||
* `int32` + `int32` → `int32`
|
||||
* `int32` + `int64` → `int64`
|
||||
* `int` + `float` → `float`
|
||||
* Bitwise operations promote `int32` to `int64` if any operand is `int64`.
|
||||
|
||||
Do not exist:
|
||||
|
||||
* magic coercions
|
||||
* implicit casts
|
||||
* silent overflows
|
||||
|
||||
---
|
||||
|
||||
## 4. Stack Conventions & Calling ABI
|
||||
|
||||
* Operations use the top of the stack.
|
||||
* Results always return to the stack.
|
||||
* **LIFO Order:** Last pushed = first consumed.
|
||||
* **Mandatory Return:** Every function (`Call`) and `Syscall` MUST leave exactly **one** value on the stack upon completion. If there is no meaningful value to return, `Null` must be pushed.
|
||||
|
||||
### 4.1 Calling Convention (Call / Ret)
|
||||
|
||||
1. **Arguments:** The caller pushes arguments in order (arg0, arg1, ..., argN-1).
|
||||
2. **Execution:** The `Call` instruction specifies `args_count`. These `N` values become the **locals** of the new frame (local 0 = arg0, local 1 = arg1, etc.).
|
||||
3. **Return Value:** Before executing `Ret`, the callee MUST push its return value.
|
||||
4. **Cleanup:** The `Ret` instruction is responsible for:
|
||||
- Popping the return value.
|
||||
- Removing all locals (the arguments) from the operand stack.
|
||||
- Re-pushing the return value.
|
||||
- Restoring the previous frame and PC.
|
||||
|
||||
### 4.2 Syscall Convention
|
||||
|
||||
1. **Arguments:** The caller pushes arguments in order.
|
||||
2. **Execution:** The native implementation pops arguments as needed. Since it's a stack, it will pop them in reverse order (argN-1 first, then argN-2, ..., arg0).
|
||||
3. **Return Value:** The native implementation MUST push exactly one value onto the stack before returning to the VM.
|
||||
4. **Cleanup:** The native implementation is responsible for popping all arguments it expects.
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
PUSH_CONST 3
|
||||
PUSH_CONST 4
|
||||
ADD
|
||||
```
|
||||
|
||||
State:
|
||||
|
||||
```
|
||||
[3]
|
||||
[3, 4]
|
||||
[7]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Instruction Categories
|
||||
|
||||
1. Flow control
|
||||
2. Stack
|
||||
3. Arithmetic and logic
|
||||
4. Variables
|
||||
5. Functions
|
||||
6. Heap and structures
|
||||
7. Peripherals (syscalls)
|
||||
8. System
|
||||
|
||||
---
|
||||
|
||||
## 6. Instructions — VM Set 1
|
||||
|
||||
### 6.1 Execution Control
|
||||
|
||||
| Instruction | Cycles | Description |
|
||||
| ------------------- | ------ | ------------------------- |
|
||||
| `NOP` | 1 | Does nothing |
|
||||
| `HALT` | 1 | Terminates execution |
|
||||
| `JMP addr` | 2 | Unconditional jump |
|
||||
| `JMP_IF_FALSE addr` | 3 | Jumps if top is false |
|
||||
| `JMP_IF_TRUE addr` | 3 | Jumps if top is true |
|
||||
|
||||
---
|
||||
|
||||
### 6.2 Stack
|
||||
|
||||
| Instruction | Cycles | Description |
|
||||
| -------------- | ------ | ------------------- |
|
||||
| `PUSH_CONST k` | 2 | Pushes constant |
|
||||
| `POP` | 1 | Removes top |
|
||||
| `DUP` | 1 | Duplicates top |
|
||||
| `SWAP` | 1 | Swaps two tops |
|
||||
| `PUSH_I32 v` | 2 | Pushes 32-bit int |
|
||||
| `PUSH_I64 v` | 2 | Pushes 64-bit int |
|
||||
| `PUSH_F64 v` | 2 | Pushes 64-bit float |
|
||||
| `PUSH_BOOL v` | 2 | Pushes boolean |
|
||||
|
||||
---
|
||||
|
||||
### 6.3 Arithmetic
|
||||
|
||||
| Instruction | Cycles |
|
||||
| ----------- | ------ |
|
||||
| `ADD` | 2 |
|
||||
| `SUB` | 2 |
|
||||
| `MUL` | 4 |
|
||||
| `DIV` | 6 |
|
||||
|
||||
---
|
||||
|
||||
### 6.4 Comparison and Logic
|
||||
|
||||
| Instruction | Cycles |
|
||||
| ----------- | ------ |
|
||||
| `EQ` | 2 |
|
||||
| `NEQ` | 2 |
|
||||
| `LT` | 2 |
|
||||
| `GT` | 2 |
|
||||
| `LTE` | 2 |
|
||||
| `GTE` | 2 |
|
||||
| `AND` | 2 |
|
||||
| `OR` | 2 |
|
||||
| `NOT` | 1 |
|
||||
| `BIT_AND` | 2 |
|
||||
| `BIT_OR` | 2 |
|
||||
| `BIT_XOR` | 2 |
|
||||
| `SHL` | 2 |
|
||||
| `SHR` | 2 |
|
||||
| `NEG` | 1 |
|
||||
|
||||
---
|
||||
|
||||
### 6.5 Variables
|
||||
|
||||
| Instruction | Cycles | Description |
|
||||
| -------------- | ------ | ---------------- |
|
||||
| `GET_GLOBAL i` | 3 | Reads global |
|
||||
| `SET_GLOBAL i` | 3 | Writes global |
|
||||
| `GET_LOCAL i` | 2 | Reads local |
|
||||
| `SET_LOCAL i` | 2 | Writes local |
|
||||
|
||||
---
|
||||
|
||||
### 6.6 Functions
|
||||
|
||||
| Instruction | Cycles | Description |
|
||||
|----------------------| ------ |-----------------------------------------------|
|
||||
| `CALL <u32 func_id>` | 5 | Saves PC and creates a new call frame |
|
||||
| `RET` | 4 | Returns from function, restoring PC |
|
||||
| `PUSH_SCOPE` | 3 | Creates a scope within the current function |
|
||||
| `POP_SCOPE` | 3 | Removes current scope and its local variables |
|
||||
|
||||
**ABI Rules for Functions:**
|
||||
* **`func_id`:** A 32-bit index into the **final FunctionTable**, assigned by the compiler linker at build time.
|
||||
* **Mandatory Return Value:** Every function MUST leave exactly one value on the stack before `RET`. If the function logic doesn't return a value, it must push `null`.
|
||||
* **Stack Cleanup:** `RET` automatically clears all local variables (based on `stack_base`) and re-pushes the return value.
|
||||
|
||||
---
|
||||
|
||||
### 6.7 Heap
|
||||
|
||||
| Instruction | Cycles | Description |
|
||||
| --------------- | ------ | --------------- |
|
||||
| `ALLOC size` | 10 | Allocates on heap |
|
||||
| `LOAD_REF off` | 3 | Reads field |
|
||||
| `STORE_REF off` | 3 | Writes field |
|
||||
|
||||
Heap is:
|
||||
|
||||
* finite
|
||||
* monitored
|
||||
* accounted for in the CAP
|
||||
|
||||
---
|
||||
|
||||
### 6.8 Peripherals (Syscalls)
|
||||
|
||||
| Instruction | Cycles | Description |
|
||||
|--------------| -------- | --------------------- |
|
||||
| `SYSCALL id` | variable | Call to hardware |
|
||||
|
||||
**ABI Rules for Syscalls:**
|
||||
* **Argument Order:** Arguments must be pushed in the order they appear in the call (LIFO stack behavior).
|
||||
* Example: `gfx.draw_rect(x, y, w, h, color)` means:
|
||||
1. `PUSH x`
|
||||
2. `PUSH y`
|
||||
3. `PUSH w`
|
||||
4. `PUSH h`
|
||||
5. `PUSH color`
|
||||
6. `SYSCALL 0x1002`
|
||||
* **Consumption:** The native function MUST pop all its arguments from the stack.
|
||||
* **Return Value:** If the syscall returns a value, it will be pushed onto the stack by the native implementation. If not, the stack state for the caller remains as it was before pushing arguments.
|
||||
|
||||
#### Implemented Syscalls (v0.1)
|
||||
|
||||
| ID | Name | Arguments (Stack) | Return |
|
||||
| ---------- | ----------------- | ---------------------------- | ------- |
|
||||
| `0x0001` | `system.has_cart` | - | `bool` |
|
||||
| `0x0002` | `system.run_cart` | - | - |
|
||||
| `0x1001` | `gfx.clear` | `color_idx` | - |
|
||||
| `0x1002` | `gfx.draw_rect` | `x, y, w, h, color_idx` | - |
|
||||
| `0x1003` | `gfx.draw_line` | `x1, y1, x2, y2, color_idx` | - |
|
||||
| `0x1004` | `gfx.draw_circle` | `xc, yc, r, color_idx` | - |
|
||||
| `0x1005` | `gfx.draw_disc` | `xc, yc, r, b_col, f_col` | - |
|
||||
| `0x1006` | `gfx.draw_square` | `x, y, w, h, b_col, f_col` | - |
|
||||
| `0x2001` | `input.get_pad` | `button_id` | `bool` |
|
||||
| `0x3001` | `audio.play` | `s_id, v_id, vol, pan, pitch`| - |
|
||||
|
||||
**Button IDs:**
|
||||
- `0`: Up, `1`: Down, `2`: Left, `3`: Right
|
||||
- `4`: A, `5`: B, `6`: X, `7`: Y
|
||||
- `8`: L, `9`: R
|
||||
- `10`: Start, `11`: Select
|
||||
|
||||
---
|
||||
|
||||
## 7. Execution Errors
|
||||
|
||||
Errors are:
|
||||
|
||||
* explicit
|
||||
* fatal
|
||||
* never silent
|
||||
|
||||
Types:
|
||||
|
||||
* stack underflow
|
||||
* invalid type
|
||||
* invalid heap
|
||||
* invalid frame
|
||||
|
||||
Generate:
|
||||
|
||||
* clear message
|
||||
* state dump
|
||||
* stack trace
|
||||
|
||||
---
|
||||
|
||||
## 8. Determinism
|
||||
|
||||
Guarantees:
|
||||
|
||||
* same input → same result
|
||||
* same sequence → same cycles
|
||||
* no speculative execution
|
||||
* no invisible optimizations
|
||||
|
||||
> If you see the instruction, you pay for it.
|
||||
|
||||
---
|
||||
|
||||
## 9. Relationship with Languages
|
||||
|
||||
Java, TypeScript, Lua etc:
|
||||
|
||||
* are source languages
|
||||
* compiled to this bytecode
|
||||
* never executed directly
|
||||
|
||||
All run on the **same VM**.
|
||||
|
||||
---
|
||||
|
||||
## 10. Example
|
||||
|
||||
Source:
|
||||
|
||||
```java
|
||||
x = 3 + 4;
|
||||
```
|
||||
|
||||
Bytecode:
|
||||
|
||||
```
|
||||
PUSH_CONST 3
|
||||
PUSH_CONST 4
|
||||
ADD
|
||||
SET_GLOBAL 0
|
||||
```
|
||||
|
||||
Cost:
|
||||
|
||||
```
|
||||
2 + 2 + 2 + 3 = 9 cycles
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11. Execution per Tick
|
||||
|
||||
The VM does not run infinitely.
|
||||
|
||||
It executes:
|
||||
|
||||
* until consuming the **logical frame** budget
|
||||
* or until `HALT`
|
||||
|
||||
The budget is defined by the PROMETEU logical hardware (e.g., `CYCLES_PER_FRAME`).
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
vm.step_budget(10_000)
|
||||
```
|
||||
|
||||
This feeds:
|
||||
|
||||
* CAP
|
||||
* profiling
|
||||
* certification
|
||||
|
||||
---
|
||||
|
||||
## 12. Logical Frame and `FRAME_SYNC`
|
||||
|
||||
PROMETEU defines **logical frame** as the minimum unit of consistent game update.
|
||||
|
||||
* **Input is latched per logical frame** (does not change until the logical frame is completed).
|
||||
* The **cycle budget** is applied to the logical frame.
|
||||
* A new logical frame only starts when the current frame ends.
|
||||
|
||||
### 12.1 System Instruction: `FRAME_SYNC`
|
||||
|
||||
The `FRAME_SYNC` instruction marks the **end of the logical frame**.
|
||||
|
||||
| Instruction | Cycles | Description |
|
||||
| ------------ | ------ | ---------------------------------- |
|
||||
| `FRAME_SYNC` | 1 | Finalizes the current logical frame |
|
||||
|
||||
Properties:
|
||||
|
||||
* `FRAME_SYNC` is a **system instruction**.
|
||||
* It should not be exposed as a "manual" API to the user.
|
||||
* Tooling/compiler can **inject** `FRAME_SYNC` automatically at the end of the main loop.
|
||||
|
||||
### 12.2 Semantics (what happens when it executes)
|
||||
|
||||
When executing `FRAME_SYNC`, the core:
|
||||
|
||||
1. **Finalizes** the current logical frame.
|
||||
2. **Presents** the frame (`gfx.present()` or `gfx.compose_and_present()` depending on the GFX model).
|
||||
3. **Releases** the input latch.
|
||||
4. **Resets** the budget for the next logical frame.
|
||||
|
||||
### 12.3 Overbudget (when the frame doesn't finish on time)
|
||||
|
||||
If the logical frame budget runs out **before** the VM reaches `FRAME_SYNC`:
|
||||
|
||||
* the VM **pauses** (PC and stacks remain at the exact point)
|
||||
* there is **no present**
|
||||
* the input latch is **maintained**
|
||||
* on the next host tick, the VM **continues** from where it left off, still in the same logical frame
|
||||
|
||||
Practical effect:
|
||||
|
||||
* if the code needs 2 budgets to reach `FRAME_SYNC`, the game updates at ~30 FPS (logical frame takes 2 ticks)
|
||||
* this is deterministic and reportable in the CAP
|
||||
|
||||
---
|
||||
|
||||
## 15. Extensibility
|
||||
|
||||
The Instruction Set is versioned.
|
||||
|
||||
Future:
|
||||
|
||||
* DMA
|
||||
* streaming
|
||||
* vectors
|
||||
* fictitious coprocessors
|
||||
|
||||
No existing instruction changes its meaning.
|
||||
|
||||
---
|
||||
|
||||
## 16. Summary
|
||||
|
||||
* stack-based VM
|
||||
* explicit cost
|
||||
* deterministic execution
|
||||
* integrated with CAP
|
||||
* foundation of every PROMETEU cartridge
|
||||
* predictable frame timing
|
||||
|
||||
Coroutines are the only supported concurrency mechanism.
|
||||
|
||||
---
|
||||
|
||||
## 12 Host Interface (Syscalls)
|
||||
|
||||
All hardware access occurs through syscalls.
|
||||
|
||||
Syscalls are:
|
||||
|
||||
* synchronous
|
||||
* deterministic
|
||||
* capability-checked
|
||||
|
||||
They operate on the following subsystems:
|
||||
|
||||
### Graphics
|
||||
|
||||
* tilebanks
|
||||
* layers
|
||||
* sprites
|
||||
* palette control
|
||||
* fade registers
|
||||
* frame present
|
||||
|
||||
### Audio
|
||||
|
||||
* voice allocation
|
||||
* play/stop
|
||||
* volume/pan/pitch
|
||||
* steal policy
|
||||
|
||||
### Input
|
||||
|
||||
* sampled once per frame
|
||||
* exposed as frame state
|
||||
|
||||
### Assets
|
||||
|
||||
Asset banks are **host-owned memory**.
|
||||
|
||||
The VM interacts through handles:
|
||||
|
||||
| Syscall | Description |
|
||||
| -------------- | ---------------------------- |
|
||||
| `asset.load` | Request asset load into slot |
|
||||
| `asset.status` | Query load state |
|
||||
| `asset.commit` | Activate loaded asset |
|
||||
|
||||
Asset memory:
|
||||
|
||||
* is not part of the VM heap
|
||||
* is not scanned by GC
|
||||
|
||||
### Save Memory (MEMCARD)
|
||||
|
||||
| Syscall | Description |
|
||||
| --------------- | --------------- |
|
||||
| `mem.read_all` | Read save data |
|
||||
| `mem.write_all` | Write save data |
|
||||
| `mem.commit` | Persist save |
|
||||
| `mem.size` | Query capacity |
|
||||
|
||||
---
|
||||
|
||||
## 13 Verifier Requirements
|
||||
|
||||
Before execution, bytecode must pass the verifier.
|
||||
|
||||
The verifier ensures:
|
||||
|
||||
1. Valid jump targets
|
||||
2. Stack depth consistency
|
||||
3. Correct `ret_slots` across all paths
|
||||
4. Handle safety rules
|
||||
5. Closure call safety
|
||||
6. No invalid opcode sequences
|
||||
|
||||
Invalid bytecode is rejected.
|
||||
|
||||
---
|
||||
|
||||
## 14 Summary
|
||||
|
||||
The Prometeu VM is:
|
||||
|
||||
* stack-based
|
||||
* deterministic
|
||||
* frame-synchronized
|
||||
* handle-based for heap access
|
||||
* multi-return capable
|
||||
* first-class function capable
|
||||
* coroutine-driven for concurrency
|
||||
|
||||
This design balances:
|
||||
|
||||
* ease of compilation
|
||||
* predictable performance
|
||||
* safety and debuggability
|
||||
* suitability for real-time 2D games.
|
||||
|
||||
< [Back](chapter-1.md) | [Summary](table-of-contents.md) | [Next](chapter-3.md) >
|
||||
@@ -1,309 +1,353 @@
|
||||
< [Back](chapter-2.md) | [Summary](table-of-contents.md) | [Next](chapter-4.md) >
|
||||
|
||||
# 🧠 **Memory: Stack, Heap, and Allocation**
|
||||
# 🧠 **Memory Model**
|
||||
|
||||
## 1. Overview
|
||||
This chapter defines the memory architecture of the Prometeu Virtual Machine (PVM). It describes the stack, heap, handles, object layout, garbage collection, and interaction with host-owned memory such as asset banks.
|
||||
|
||||
PROMETEU treats **memory as an explicit resource**.
|
||||
The memory model is designed to be:
|
||||
|
||||
Nothing is allocated "for convenience".
|
||||
|
||||
Nothing grows "automatically".
|
||||
|
||||
Nothing is invisible.
|
||||
|
||||
This chapter defines:
|
||||
|
||||
- the **memory spaces** of the PROMETEU VM
|
||||
- how **Stack** and **Heap** work
|
||||
- the cost and consequences of **dynamic allocation**
|
||||
- how memory relates to **CAP and certification**
|
||||
* deterministic
|
||||
* safe
|
||||
* simple to verify
|
||||
* suitable for real-time 2D games
|
||||
|
||||
---
|
||||
|
||||
## 2. PROMETEU VM Memory Spaces
|
||||
## 1 Overview
|
||||
|
||||
The PROMETEU VM memory is divided into regions with clear responsibilities:
|
||||
The PVM uses a **split memory model**:
|
||||
|
||||
```
|
||||
+---------------------------+
|
||||
|Constant Pool |
|
||||
+---------------------------+
|
||||
|Global Space |
|
||||
+---------------------------+
|
||||
|Call Stack |
|
||||
| (Frames + Locals) |
|
||||
+---------------------------+
|
||||
| Operand Stack |
|
||||
+---------------------------+
|
||||
| Heap |
|
||||
+---------------------------+
|
||||
1. **Stack memory**
|
||||
|
||||
```
|
||||
* used for temporary values
|
||||
* function arguments
|
||||
* multi-return tuples
|
||||
2. **Heap memory**
|
||||
|
||||
Each region:
|
||||
* used for all user-defined objects
|
||||
* accessed only through handles
|
||||
3. **Host-owned memory**
|
||||
|
||||
- has its own semantics
|
||||
- has defined limits
|
||||
- has a direct impact on execution cost
|
||||
* asset banks
|
||||
* audio buffers
|
||||
* framebuffers
|
||||
* not part of the VM heap
|
||||
|
||||
---
|
||||
|
||||
## 3. Operand Stack
|
||||
## 2 Stack Memory
|
||||
|
||||
### 3.1 Definition
|
||||
The stack is used for:
|
||||
|
||||
The **Operand Stack** is used for:
|
||||
* primitive values
|
||||
* built-in value types
|
||||
* temporary results
|
||||
* function arguments
|
||||
* tuple returns
|
||||
|
||||
- passing operands between instructions
|
||||
- intermediate results
|
||||
- expression evaluation
|
||||
### Stack value types
|
||||
|
||||
It is:
|
||||
| Type | Description |
|
||||
| -------- | ------------------------ |
|
||||
| `int` | 64-bit integer |
|
||||
| `bool` | Boolean |
|
||||
| `float` | 64-bit float |
|
||||
| `vec2` | 2D vector |
|
||||
| `color` | Packed color |
|
||||
| `pixel` | Position + color |
|
||||
| `handle` | Reference to heap object |
|
||||
|
||||
- **LIFO**
|
||||
- automatically growing within the frame
|
||||
- **reset** between frames (except explicitly persisted values)
|
||||
All stack values are:
|
||||
|
||||
* fixed-size
|
||||
* copied by value
|
||||
* never directly reference raw memory
|
||||
|
||||
### Stack properties
|
||||
|
||||
* Stack is bounded and verified.
|
||||
* Stack depth must be consistent across all control paths.
|
||||
* Stack never stores raw pointers.
|
||||
|
||||
---
|
||||
|
||||
### 3.2 Characteristics
|
||||
## 3 Tuples (Stack-Only Aggregates)
|
||||
|
||||
- does not store complex structures
|
||||
- stores primitive values or references
|
||||
- overflow or underflow are **fatal errors**
|
||||
Tuples are used for multi-value returns.
|
||||
|
||||
> The operand stack is cheap, fast, and temporary.
|
||||
>
|
||||
### Tuple rules
|
||||
|
||||
---
|
||||
* Tuples exist only on the stack.
|
||||
* Maximum tuple arity: **6 slots**.
|
||||
* Tuples are not heap objects by default.
|
||||
* To persist a tuple, it must be explicitly boxed into a heap object.
|
||||
|
||||
## 4. Call Stack
|
||||
### Example
|
||||
|
||||
### 4.1 Execution Frames
|
||||
|
||||
Each function call creates a **Call Frame**, containing:
|
||||
|
||||
- local variables
|
||||
- parameters
|
||||
- return address
|
||||
- execution context
|
||||
|
||||
Frames are created with:
|
||||
Function returning two values:
|
||||
|
||||
```
|
||||
PUSH_FRAME n
|
||||
fn position(): (int, int)
|
||||
```
|
||||
|
||||
And destroyed with:
|
||||
At runtime:
|
||||
|
||||
```
|
||||
POP_FRAME
|
||||
stack top → [x, y]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4.2 Costs and Limits
|
||||
## 4 Heap Memory
|
||||
|
||||
- frame creation has an explicit cost
|
||||
- maximum stack depth is limited
|
||||
- deep recursion is discouraged
|
||||
All user-defined objects live in the heap.
|
||||
|
||||
PROMETEU favors:
|
||||
### Heap characteristics
|
||||
|
||||
- iteration
|
||||
- explicit state
|
||||
- conscious depth control
|
||||
* Linear slot-based storage.
|
||||
* Objects are fixed-layout blocks.
|
||||
* No raw pointer access.
|
||||
* No inheritance at memory level.
|
||||
|
||||
Heap objects include:
|
||||
|
||||
* user structs/classes
|
||||
* arrays
|
||||
* strings
|
||||
* closures
|
||||
* boxed tuples (optional)
|
||||
|
||||
---
|
||||
|
||||
## 5. Global Space
|
||||
## 5 Handles and Gate Table
|
||||
|
||||
### 5.1 Definition
|
||||
All heap objects are accessed via **handles**.
|
||||
|
||||
The **Global Space** stores:
|
||||
|
||||
- global variables
|
||||
- persistent game state
|
||||
- long-term references
|
||||
|
||||
Globals:
|
||||
|
||||
- survive between frames
|
||||
- occupy memory permanently
|
||||
- count towards total memory usage
|
||||
|
||||
---
|
||||
|
||||
### 5.2 Conscious usage
|
||||
|
||||
PROMETEU encourages:
|
||||
|
||||
- few globals
|
||||
- compact structures
|
||||
- explicit initialization
|
||||
|
||||
Globals are equivalent to **static RAM** in microcontrollers.
|
||||
|
||||
---
|
||||
|
||||
## 6. Heap
|
||||
|
||||
### 6.1 Definition
|
||||
|
||||
The **Heap** is the dynamic memory region of the PROMETEU VM.
|
||||
|
||||
It is used for:
|
||||
|
||||
- objects
|
||||
- arrays
|
||||
- tables
|
||||
- composite structures
|
||||
|
||||
Every allocation on the heap is done explicitly with:
|
||||
A handle is defined as:
|
||||
|
||||
```
|
||||
ALLOC size
|
||||
handle = { index, generation }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 6.2 Allocation Costs
|
||||
|
||||
Allocating memory:
|
||||
|
||||
- consumes **cycles**
|
||||
- consumes **available heap**
|
||||
- increases pressure on the system
|
||||
|
||||
PROMETEU treats allocation as an **expensive operation by definition**.
|
||||
|
||||
> Allocation is an architectural decision, not a detail.
|
||||
>
|
||||
|
||||
---
|
||||
|
||||
## 7. Heap Limits
|
||||
|
||||
### 7.1 Finite Heap
|
||||
|
||||
The heap:
|
||||
|
||||
- has a defined maximum size
|
||||
- can vary according to the active CAP
|
||||
- never grows dynamically
|
||||
|
||||
Example:
|
||||
The VM maintains a **gate table**:
|
||||
|
||||
```
|
||||
Heap Limit:32KB
|
||||
Heap Used:28KB
|
||||
GateEntry {
|
||||
alive: bool
|
||||
generation: u32
|
||||
base: usize
|
||||
slots: u32
|
||||
type_id: u32
|
||||
}
|
||||
```
|
||||
|
||||
Exceeding the limit:
|
||||
### Handle safety
|
||||
|
||||
- does not crash the game
|
||||
- generates an execution error
|
||||
- appears in the certification report
|
||||
When an object is freed:
|
||||
|
||||
* `alive` becomes false
|
||||
* `generation` is incremented
|
||||
|
||||
When a handle is used:
|
||||
|
||||
* index must exist
|
||||
* generation must match
|
||||
|
||||
Otherwise, the VM traps.
|
||||
|
||||
This prevents:
|
||||
|
||||
* use-after-free
|
||||
* stale references
|
||||
|
||||
---
|
||||
|
||||
### 7.2 Heap and CAP
|
||||
## 6 Object Layout
|
||||
|
||||
During a JAM or evaluation:
|
||||
Heap objects have a simple, fixed layout:
|
||||
|
||||
- heap peak is measured
|
||||
- the value is compared to the CAP limit
|
||||
- non-compliances are recorded
|
||||
```
|
||||
Object {
|
||||
type_id
|
||||
field_0
|
||||
field_1
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
The game **continues running**, but the evidence is recorded.
|
||||
Properties:
|
||||
|
||||
* Fields are stored in slot order.
|
||||
* No hidden base classes.
|
||||
* No pointer arithmetic.
|
||||
|
||||
Traits and method dispatch are resolved:
|
||||
|
||||
* statically by the compiler, or
|
||||
* via vtable handles (if dynamic dispatch is used).
|
||||
|
||||
---
|
||||
|
||||
## 8. Garbage Collection (GC)
|
||||
## 7 Closures
|
||||
|
||||
### 8.1 Existence of GC
|
||||
Closures are heap objects.
|
||||
|
||||
PROMETEU may use **simple Garbage Collection**, with the following properties:
|
||||
Layout:
|
||||
|
||||
- non-incremental (v0.1)
|
||||
- explicit cost
|
||||
- observable pauses
|
||||
- documented behavior
|
||||
```
|
||||
Closure {
|
||||
func_id
|
||||
capture_count
|
||||
captures[]
|
||||
}
|
||||
```
|
||||
|
||||
GC **is not invisible**.
|
||||
Captures may be:
|
||||
|
||||
* copied values
|
||||
* handles to heap objects
|
||||
|
||||
Closure environments are part of the GC root set.
|
||||
|
||||
---
|
||||
|
||||
### 8.2 GC Cost
|
||||
## 8 Coroutine Memory
|
||||
|
||||
When GC occurs:
|
||||
Each coroutine owns its own stacks:
|
||||
|
||||
- cycles are consumed
|
||||
- the frame may be impacted
|
||||
- the event is recorded
|
||||
```
|
||||
Coroutine {
|
||||
call_stack
|
||||
operand_stack
|
||||
state
|
||||
}
|
||||
```
|
||||
|
||||
PROMETEU teaches:
|
||||
All coroutine stacks are included in the GC root set.
|
||||
|
||||
> "Creating garbage has a cost."
|
||||
>
|
||||
Coroutines do not share stacks or frames.
|
||||
|
||||
---
|
||||
|
||||
## 9. Memory Best Practices
|
||||
## 9 Garbage Collection
|
||||
|
||||
PROMETEU explicitly encourages:
|
||||
The PVM uses a **mark-sweep collector**.
|
||||
|
||||
- structure reuse
|
||||
- allocation outside the main loop
|
||||
- persistent buffers
|
||||
- pooling manual
|
||||
### GC properties
|
||||
|
||||
And discourages:
|
||||
* Non-moving (no compaction in v1).
|
||||
* Runs only at **safepoints**.
|
||||
* Primary safepoint: `FRAME_SYNC`.
|
||||
|
||||
- per-frame allocation
|
||||
- disposable temporary structures
|
||||
- unplanned growth
|
||||
### GC triggers
|
||||
|
||||
GC may run when:
|
||||
|
||||
* heap usage exceeds threshold
|
||||
* allocation pressure is high
|
||||
|
||||
### Root set
|
||||
|
||||
The collector marks from:
|
||||
|
||||
* operand stack
|
||||
* call stack frames
|
||||
* global variables
|
||||
* coroutine stacks
|
||||
* closure environments
|
||||
* host-held handles
|
||||
|
||||
---
|
||||
|
||||
## 10. Relationship with Microcontrollers
|
||||
## 10 Allocation and Deallocation
|
||||
|
||||
The PROMETEU memory model is intentionally similar to real MCUs:
|
||||
### Allocation
|
||||
|
||||
| MCU | PROMETEU |
|
||||
| --- | --- |
|
||||
| Static RAM | Global Space |
|
||||
| Stack | Call Stack |
|
||||
| Heap | Heap |
|
||||
| Allocation failure | Explicit error |
|
||||
| Fragmentation | Dev's responsibility |
|
||||
Heap allocation:
|
||||
|
||||
This creates a direct transfer of learning.
|
||||
1. VM reserves a slot block.
|
||||
2. A gate entry is created.
|
||||
3. A handle is returned.
|
||||
|
||||
If allocation fails:
|
||||
|
||||
* VM may trigger GC.
|
||||
* If still failing, a trap occurs.
|
||||
|
||||
### Deallocation
|
||||
|
||||
Objects are freed only by the GC.
|
||||
|
||||
When freed:
|
||||
|
||||
* gate is marked dead
|
||||
* generation is incremented
|
||||
* memory becomes available via free list
|
||||
|
||||
---
|
||||
|
||||
## 11. Pedagogical Implications
|
||||
## 11 Host-Owned Memory (Asset Banks)
|
||||
|
||||
This model allows teaching:
|
||||
Asset memory is **not part of the VM heap**.
|
||||
|
||||
- the difference between stack and heap
|
||||
- allocation cost
|
||||
- data lifetime
|
||||
- architectural impact of simple decisions
|
||||
- the relationship between memory and time
|
||||
It is managed by the firmware.
|
||||
|
||||
Everything with **immediate and visible feedback**.
|
||||
Examples:
|
||||
|
||||
* tilebanks
|
||||
* audio sample banks
|
||||
* sprite sheets
|
||||
|
||||
### Properties
|
||||
|
||||
* VM cannot access asset memory directly.
|
||||
* Access occurs only through syscalls.
|
||||
* Asset memory is not scanned by GC.
|
||||
|
||||
---
|
||||
|
||||
## 12. Summary
|
||||
## 12 Save Memory (MEMCARD)
|
||||
|
||||
- PROMETEU has well-defined memory spaces
|
||||
- stack is temporary and cheap
|
||||
- heap is finite and expensive
|
||||
- allocation has an explicit cost
|
||||
- GC is visible and measurable
|
||||
- memory participates in certification
|
||||
Save memory is a host-managed persistent storage area.
|
||||
|
||||
Properties:
|
||||
|
||||
* fixed size
|
||||
* accessed only via syscalls
|
||||
* not part of the VM heap
|
||||
* not scanned by GC
|
||||
|
||||
---
|
||||
|
||||
## 13 Memory Safety Rules
|
||||
|
||||
The VM enforces:
|
||||
|
||||
1. All heap access via handles.
|
||||
2. Generation checks on every handle use.
|
||||
3. Bounds checking on object fields.
|
||||
4. No raw pointer arithmetic.
|
||||
5. Verified stack discipline.
|
||||
|
||||
Any violation results in a trap.
|
||||
|
||||
---
|
||||
|
||||
## 14 Summary
|
||||
|
||||
The PVM memory model is based on:
|
||||
|
||||
* stack-only primitive and tuple values
|
||||
* heap-only user objects
|
||||
* generation-based handles
|
||||
* deterministic GC at frame safepoints
|
||||
* strict separation between VM heap and host memory
|
||||
|
||||
This design ensures:
|
||||
|
||||
* predictable performance
|
||||
* memory safety
|
||||
* simple verification
|
||||
* suitability for real-time game workloads.
|
||||
|
||||
< [Back](chapter-2.md) | [Summary](table-of-contents.md) | [Next](chapter-4.md) >
|
||||
@@ -1,289 +1,308 @@
|
||||
< [Back](chapter-8.md) | [Summary](table-of-contents.md) | [Next](chapter-10.md) >
|
||||
|
||||
# ⚡ **Events and Interrupts**
|
||||
# ⚡ **Events and Scheduling**
|
||||
|
||||
## 1. Overview
|
||||
This chapter defines how the Prometeu Virtual Machine (PVM) handles events, frame synchronization, and cooperative concurrency. It replaces the older interrupt-oriented terminology with a simpler and more accurate model based on **frame boundaries**, **event queues**, and **coroutines**.
|
||||
|
||||
PROMETEU clearly distinguishes between **normal execution**, **events**, and **interrupts**.
|
||||
|
||||
Nothing occurs "out of time".
|
||||
|
||||
Nothing interrupts the system without cost.
|
||||
|
||||
Nothing happens without a well-defined point in the execution cycle.
|
||||
|
||||
> Events are signals.
|
||||
> Interrupts are machine decisions.
|
||||
>
|
||||
|
||||
This chapter defines:
|
||||
|
||||
- what PROMETEU considers an event
|
||||
- how interrupts are modeled
|
||||
- when they can occur
|
||||
- how they relate to cycles, CAP, and determinism
|
||||
The goal is to preserve determinism while still allowing responsive and structured game logic.
|
||||
|
||||
---
|
||||
|
||||
## 2. Event Philosophy in PROMETEU
|
||||
## 1 Core Philosophy
|
||||
|
||||
PROMETEU **does not use invisible asynchronous callbacks**.
|
||||
Prometeu does **not use asynchronous callbacks** or preemptive interrupts for user code.
|
||||
|
||||
Every event:
|
||||
All external signals are:
|
||||
|
||||
- is registered
|
||||
- is delivered at a predictable moment
|
||||
- is handled within the main loop
|
||||
* queued by the firmware
|
||||
* delivered at deterministic points
|
||||
* processed inside the main execution loop
|
||||
|
||||
This model avoids:
|
||||
Nothing executes “out of time”.
|
||||
Nothing interrupts the program in the middle of an instruction.
|
||||
Nothing occurs without a known cost.
|
||||
|
||||
- implicit concurrency
|
||||
- hidden race conditions
|
||||
- non-deterministic side effects
|
||||
This guarantees:
|
||||
|
||||
PROMETEU favors:
|
||||
|
||||
> explicit control over reactivity.
|
||||
>
|
||||
* deterministic behavior
|
||||
* reproducible runs
|
||||
* stable frame timing
|
||||
|
||||
---
|
||||
|
||||
## 3. Events
|
||||
## 2 Events
|
||||
|
||||
### 3.1 Definition
|
||||
### 2.1 Definition
|
||||
|
||||
An **event** in PROMETEU is a **logical signal** generated by the system or the program, indicating that something has occurred.
|
||||
|
||||
Examples of events:
|
||||
|
||||
- end of frame
|
||||
- timer expired
|
||||
- system state change
|
||||
- execution error
|
||||
|
||||
Events **do not execute code automatically**.
|
||||
|
||||
They only **inform**.
|
||||
|
||||
---
|
||||
|
||||
### 3.2 Event Queue
|
||||
|
||||
PROMETEU maintains an **event queue**:
|
||||
|
||||
- events are queued
|
||||
- the queue is processed in order
|
||||
- processing occurs at defined points in the frame
|
||||
An **event** is a logical signal generated by the system or by internal runtime mechanisms.
|
||||
|
||||
Events:
|
||||
|
||||
- do not interrupt execution arbitrarily
|
||||
- do not execute outside the loop
|
||||
* represent something that has occurred
|
||||
* do not execute code automatically
|
||||
* are processed explicitly during the frame
|
||||
|
||||
Examples:
|
||||
|
||||
* end of frame
|
||||
* timer expiration
|
||||
* asset load completion
|
||||
* system state change
|
||||
* execution error
|
||||
|
||||
---
|
||||
|
||||
## 4. Interrupts
|
||||
### 2.2 Event Queue
|
||||
|
||||
### 4.1 Definition
|
||||
The firmware maintains an **event queue**.
|
||||
|
||||
An **interrupt** is a special event, treated by the system as **priority**, which can:
|
||||
Properties:
|
||||
|
||||
- change the normal flow of execution
|
||||
- execute specific system code
|
||||
- impact cycles and budget
|
||||
* events are queued in order
|
||||
* events are processed at frame boundaries
|
||||
* event processing is deterministic
|
||||
|
||||
Interrupts are **rare and explicit**.
|
||||
Events never:
|
||||
|
||||
* execute user code automatically
|
||||
* interrupt instructions
|
||||
* run outside the main loop
|
||||
|
||||
---
|
||||
|
||||
### 4.2 What is NOT an interrupt
|
||||
## 3 Frame Boundary (Sync Phase)
|
||||
|
||||
In PROMETEU, the following are **not interrupts**:
|
||||
The primary synchronization point in Prometeu is the **frame boundary**, reached by the `FRAME_SYNC` instruction.
|
||||
|
||||
- button input
|
||||
- collisions
|
||||
- common timers
|
||||
- game logic
|
||||
At this point:
|
||||
|
||||
These are treated as **state or normal events**.
|
||||
1. Input state is sampled.
|
||||
2. Events are delivered.
|
||||
3. Coroutine scheduling occurs.
|
||||
4. Optional garbage collection may run.
|
||||
5. Control returns to the firmware.
|
||||
|
||||
This replaces the older notion of a "VBlank interrupt".
|
||||
|
||||
The frame boundary:
|
||||
|
||||
* has a fixed, measurable cost
|
||||
* does not execute arbitrary user code
|
||||
* is fully deterministic
|
||||
|
||||
---
|
||||
|
||||
## 5. Types of Interrupts in PROMETEU
|
||||
## 4 System Events vs System Faults
|
||||
|
||||
PROMETEU defines a small and well-controlled set of interrupts.
|
||||
Prometeu distinguishes between normal events and system faults.
|
||||
|
||||
### 5.1 Frame Interrupt (Conceptual VBlank)
|
||||
### 4.1 Normal events
|
||||
|
||||
The end of each frame generates a **logical synchronization interrupt**, responsible for:
|
||||
Examples:
|
||||
|
||||
- framebuffer swap
|
||||
- audio commit
|
||||
- state synchronization
|
||||
* timer expired
|
||||
* asset loaded
|
||||
* frame boundary
|
||||
|
||||
This interrupt:
|
||||
These are delivered through the event queue.
|
||||
|
||||
- occurs at SYNC
|
||||
- has a fixed cost
|
||||
- does not execute user code
|
||||
|
||||
---
|
||||
|
||||
### 5.2 System Interrupt
|
||||
### 4.2 System faults
|
||||
|
||||
Generated by exceptional conditions:
|
||||
|
||||
- fatal VM error
|
||||
- memory violation
|
||||
- invalid instruction
|
||||
* invalid instruction
|
||||
* memory violation
|
||||
* handle misuse
|
||||
* verifier failure
|
||||
|
||||
Result:
|
||||
|
||||
- execution is halted
|
||||
- VM state is preserved
|
||||
- detailed report is generated
|
||||
* VM execution stops
|
||||
* state is preserved
|
||||
* a diagnostic report is generated
|
||||
|
||||
System faults are not recoverable events.
|
||||
|
||||
---
|
||||
|
||||
### 5.3 Timed Interrupts (Timers)
|
||||
## 5 Timers
|
||||
|
||||
PROMETEU can offer **system timers**, modeled as:
|
||||
Timers are modeled as **frame-based counters**.
|
||||
|
||||
- counters based on frames
|
||||
- signals generated upon reaching zero
|
||||
Properties:
|
||||
|
||||
* measured in frames, not real time
|
||||
* deterministic across runs
|
||||
* generate events when they expire
|
||||
|
||||
Timers:
|
||||
|
||||
- do not trigger code automatically
|
||||
- generate queryable events
|
||||
* do not execute code automatically
|
||||
* produce queryable or queued events
|
||||
|
||||
Conceptual example:
|
||||
Example:
|
||||
|
||||
```
|
||||
if (timer.expired(T1)) {
|
||||
// handle event
|
||||
if timer.expired(t1) {
|
||||
// handle event
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Relationship between Events, Interrupts, and the Loop
|
||||
## 6 Coroutines and Cooperative Scheduling
|
||||
|
||||
The complete flow can be represented as follows:
|
||||
Prometeu provides **coroutines** as the only form of concurrency.
|
||||
|
||||
```
|
||||
FRAME N
|
||||
──────────────
|
||||
SAMPLEINPUT
|
||||
PROCESS EVENTS
|
||||
UPDATE
|
||||
DRAW
|
||||
AUDIO
|
||||
INTERRUPT: VBLANK
|
||||
SYNC
|
||||
──────────────
|
||||
```
|
||||
Coroutines are:
|
||||
|
||||
Important:
|
||||
* cooperative
|
||||
* deterministic
|
||||
* scheduled only at safe points
|
||||
|
||||
- events are processed before main logic
|
||||
- interrupts occur only at safe points
|
||||
- no interrupt occurs "in the middle" of an instruction
|
||||
There is:
|
||||
|
||||
* no preemption
|
||||
* no parallel execution
|
||||
* no hidden threads
|
||||
|
||||
### 6.1 Coroutine lifecycle
|
||||
|
||||
Each coroutine can be in one of the following states:
|
||||
|
||||
* `Ready`
|
||||
* `Running`
|
||||
* `Sleeping`
|
||||
* `Finished`
|
||||
|
||||
### 6.2 Scheduling
|
||||
|
||||
At each frame boundary:
|
||||
|
||||
1. The scheduler selects the next coroutine.
|
||||
2. Coroutines run in a deterministic order.
|
||||
3. Each coroutine executes within the frame budget.
|
||||
|
||||
The default scheduling policy is:
|
||||
|
||||
* round-robin
|
||||
* deterministic
|
||||
|
||||
---
|
||||
|
||||
## 7. Costs and Budget
|
||||
### 6.3 Coroutine operations
|
||||
|
||||
Events and interrupts:
|
||||
Typical coroutine instructions:
|
||||
|
||||
- consume cycles
|
||||
- participate in the CAP
|
||||
- appear in certification
|
||||
| Operation | Description |
|
||||
| --------- | ----------------------------- |
|
||||
| `spawn` | Create a coroutine |
|
||||
| `yield` | Voluntarily suspend execution |
|
||||
| `sleep` | Suspend for N frames |
|
||||
|
||||
Example report:
|
||||
`yield` and `sleep` only take effect at safe points.
|
||||
|
||||
---
|
||||
|
||||
## 7 Relationship Between Events, Coroutines, and the Frame Loop
|
||||
|
||||
The high-level frame structure is:
|
||||
|
||||
```
|
||||
FRAME N
|
||||
------------------------
|
||||
Sample Input
|
||||
Deliver Events
|
||||
Schedule Coroutines
|
||||
Run VM until:
|
||||
- budget exhausted, or
|
||||
- FRAME_SYNC reached
|
||||
Sync Phase
|
||||
------------------------
|
||||
```
|
||||
|
||||
Important properties:
|
||||
|
||||
* events are processed at known points
|
||||
* coroutine scheduling is deterministic
|
||||
* no execution occurs outside the frame loop
|
||||
|
||||
---
|
||||
|
||||
## 8 Costs and Budget
|
||||
|
||||
All event processing and scheduling:
|
||||
|
||||
* consumes cycles
|
||||
* contributes to the CAP (certification and analysis profile)
|
||||
* appears in profiling reports
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
Frame 18231:
|
||||
Event processing:120cycles
|
||||
VBlank interrupt:80cycles
|
||||
Event processing: 120 cycles
|
||||
Coroutine scheduling: 40 cycles
|
||||
Frame sync: 80 cycles
|
||||
```
|
||||
|
||||
Nothing is free.
|
||||
|
||||
---
|
||||
|
||||
## 8. Determinism and Reproducibility
|
||||
## 9 Determinism and Reproducibility
|
||||
|
||||
PROMETEU guarantees:
|
||||
Prometeu guarantees:
|
||||
|
||||
- same sequence of events → same behavior
|
||||
- interrupts always at the same point in the frame
|
||||
- timers based on frame count, not real time
|
||||
* same sequence of inputs and events → same behavior
|
||||
* frame-based timers
|
||||
* deterministic coroutine scheduling
|
||||
|
||||
This allows:
|
||||
|
||||
- reliable replays
|
||||
- precise debugging
|
||||
- fair certification
|
||||
* reliable replays
|
||||
* precise debugging
|
||||
* fair certification
|
||||
|
||||
---
|
||||
|
||||
## 9. Best Practices
|
||||
## 10 Best Practices
|
||||
|
||||
PROMETEU encourages:
|
||||
Prometeu encourages:
|
||||
|
||||
- treating events as data
|
||||
- querying events explicitly
|
||||
- avoiding heavy logic in handlers
|
||||
- using timers instead of excessive polling
|
||||
* treating events as data
|
||||
* querying events explicitly
|
||||
* structuring logic around frame steps
|
||||
* using coroutines for asynchronous flows
|
||||
|
||||
PROMETEU discourages:
|
||||
Prometeu discourages:
|
||||
|
||||
- simulating asynchronous callbacks
|
||||
- depending on implicit order
|
||||
- using events as a "shortcut" for complex logic
|
||||
* simulating asynchronous callbacks
|
||||
* relying on hidden timing
|
||||
* using events as implicit control flow
|
||||
|
||||
---
|
||||
|
||||
## 10. Relationship with Microcontrollers
|
||||
## 11 Conceptual Comparison
|
||||
|
||||
The model reflects real MCUs:
|
||||
| Traditional System | Prometeu |
|
||||
| ------------------ | ----------------------- |
|
||||
| Hardware interrupt | Frame boundary event |
|
||||
| ISR | System sync phase |
|
||||
| Main loop | VM frame loop |
|
||||
| Timer interrupt | Frame-based timer event |
|
||||
| Threads | Coroutines |
|
||||
|
||||
| MCU | PROMETEU |
|
||||
| --- | --- |
|
||||
| ISR | Explicit interrupt |
|
||||
| Main Loop | PROMETEU Loop |
|
||||
| Flags | Events |
|
||||
| Timers | Per-frame timers |
|
||||
|
||||
But without:
|
||||
|
||||
- real concurrency
|
||||
- unpredictable interrupts
|
||||
|
||||
PROMETEU **teaches the concept**, not the chaos.
|
||||
Prometeu teaches reactive system concepts without the unpredictability of real interrupts.
|
||||
|
||||
---
|
||||
|
||||
## 11. Pedagogical Implications
|
||||
## 12 Summary
|
||||
|
||||
This model allows teaching:
|
||||
|
||||
- the difference between event and interrupt
|
||||
- safe synchronization
|
||||
- flow control in reactive systems
|
||||
- the impact of temporal decisions
|
||||
|
||||
Everything with **order, clarity, and measurement**.
|
||||
|
||||
---
|
||||
|
||||
## 12. Summary
|
||||
|
||||
- events inform, they do not execute
|
||||
- interrupts are rare and controlled
|
||||
- no execution occurs outside the loop
|
||||
- costs are explicit
|
||||
- behavior is deterministic
|
||||
* Events inform; they do not execute code.
|
||||
* The frame boundary is the only global synchronization point.
|
||||
* System faults stop execution.
|
||||
* Coroutines provide cooperative concurrency.
|
||||
* All behavior is deterministic and measurable.
|
||||
|
||||
< [Back](chapter-8.md) | [Summary](table-of-contents.md) | [Next](chapter-10.md) >
|
||||
@@ -15,6 +15,7 @@
|
||||
- [Chapter 13: Cartridge](chapter-13.md)
|
||||
- [Chapter 14: Boot Profiles](chapter-14.md)
|
||||
- [Chapter 15: Asset Management](chapter-15.md)
|
||||
- [Chapter 16: Host ABI and Syscalls](chapter-16.md)
|
||||
|
||||
---
|
||||
[Back to README](../README.md)
|
||||
Reference in New Issue
Block a user