changes on docs and specs

This commit is contained in:
2026-03-24 13:42:17 +00:00
parent 6befcade91
commit a8f06922db
57 changed files with 0 additions and 0 deletions
-92
View File
@@ -1,92 +0,0 @@
### Prometeu Bytecode — Core ISA (Minimal, Bytecode‑Only)
This document defines the minimal, stable Core ISA surface for the Prometeu Virtual Machine at the bytecode level. It specifies instruction encoding, the stack evaluation model, and the instruction set currently available. Higher‑level constructs (closures, coroutines) are intentionally out of scope at this stage.
#### Encoding Rules
- Endianness: Little‑endian.
- Instruction layout: `[opcode: u16][immediate: spec.imm_bytes]`.
- Opcodes are defined in `prometeu_bytecode::isa::core::CoreOpCode`.
- Immediate sizes and stack effects are defined by `CoreOpCode::spec()` returning `CoreOpcodeSpec`.
- All jump immediates are absolute u32 byte offsets from the start of the current function.
#### Stack Machine Model
- The VM is stack‑based. Unless noted, operands are taken from the top of the operand stack and results are pushed back.
- Types at the bytecode level are represented by the `Value` enum; the VM may perform numeric promotion where appropriate (e.g., `Int32 + Float -> Float`).
- Stack underflow is a trap (TRAP_STACK_UNDERFLOW).
- Some operations may trap for other reasons (e.g., division by zero, invalid indices, type mismatches).
#### Instruction Set (Core)
- Execution control:
- `NOP` — no effect.
- `HALT` — terminates execution (block terminator).
- `JMP u32` — unconditional absolute jump (block terminator).
- `JMP_IF_FALSE u32` — pops `[bool]`, jumps if false.
- `JMP_IF_TRUE u32` — pops `[bool]`, jumps if true.
- `TRAP` — software trap/breakpoint (block terminator).
- Stack manipulation:
- `PUSH_CONST u32` — load constant by index → _pushes `[value]`.
- `PUSH_I64 i64`, `PUSH_F64 f64`, `PUSH_BOOL u8`, `PUSH_I32 i32` — push literals.
- `POP` — pops 1.
- `POP_N u32` — pops N.
- `DUP` — `[x] -> [x, x]`.
- `SWAP` — `[a, b] -> [b, a]`.
- Arithmetic:
- `ADD`, `SUB`, `MUL`, `DIV`, `MOD` — binary numeric ops.
- `NEG` — unary numeric negation.
- Comparison and logic:
- `EQ`, `NEQ`, `LT`, `LTE`, `GT`, `GTE` — comparisons → `[bool]`.
- `AND`, `OR`, `NOT` — boolean logic.
- `BIT_AND`, `BIT_OR`, `BIT_XOR`, `SHL`, `SHR` — integer bit operations.
- Variables:
- `GET_GLOBAL u32`, `SET_GLOBAL u32` — access global slots.
- `GET_LOCAL u32`, `SET_LOCAL u32` — access local slots (current frame).
- Functions and scopes:
- `CALL u32` — call by function index; argument/result arity per function metadata.
- `RET` — return from current function (block terminator).
- `PUSH_SCOPE`, `POP_SCOPE` — begin/end lexical scope.
- System/Timing:
- `SYSCALL u32` — platform call; arity/types are verified by the VM/firmware layer.
- `FRAME_SYNC` — yield until the next frame boundary (e.g., vblank); explicit safepoint.
For exact immediates and stack effects, see `CoreOpCode::spec()` which is the single source of truth used by the decoder, disassembler, and (later) verifier.
#### Canonical Decoder Contract
- The canonical decoder is `prometeu_bytecode::decode_next(pc, bytes)`.
- It uses the Core ISA spec to determine immediate size and the canonical `next_pc`.
- Unknown or legacy opcodes must produce a deterministic `UnknownOpcode` error.
#### Module Boundary
- Core ISA lives under `prometeu_bytecode::isa::core` and re‑exports:
- `CoreOpCode` — the opcode enum of the core profile.
- `CoreOpcodeSpec` and `CoreOpCodeSpecExt` — spec with `imm_bytes`, stack effects, and flags.
- Consumers (encoder/decoder/disasm/verifier) should import from this module to avoid depending on internal layout.
#### FRAME_SYNC — Semantics and Placement (Bytecode Level)
- Semantics:
- `FRAME_SYNC` is a zero-operand instruction and does not modify the operand stack.
- It marks a VM safepoint for GC and the cooperative scheduler. In `CoreOpcodeSpec` this is exposed as `spec.is_safepoint == true`.
- On execution, the VM may suspend the current fiber/coroutine until the next frame boundary (e.g., vsync) and/or perform GC. After resuming, execution continues at the next instruction.
- Placement rules (representable and checkable):
- `FRAME_SYNC` may appear anywhere inside a function body where normal instructions can appear. It is NOT a block terminator (`spec.is_terminator == false`).
- Instruction boundaries are canonical: encoders/emitters must only place `FRAME_SYNC` at valid instruction PCs. The verifier already enforces “jump-to-boundary” and end-exclusive `[start, end)` function ranges using the canonical layout routine.
- Entrypoints that represent a render/update loop SHOULD ensure at least one reachable `FRAME_SYNC` along every long-running path to provide deterministic safepoints for GC/scheduling. This policy is semantic and may be enforced by higher-level tooling; at the bytecode level it is representable via `spec.is_safepoint` and can be counted by static analyzers.
- Disassembly:
- Disassemblers must print the mnemonic `FRAME_SYNC` verbatim for this opcode.
- Tools MAY optionally annotate it as a safepoint in comments, e.g., `FRAME_SYNC ; safepoint`.
- Verification notes:
- The bytecode verifier treats `FRAME_SYNC` as a normal instruction with no stack effect and no control-flow targets. It is permitted before `RET`, between basic blocks, and as the last instruction of a function. Jumps targeting the function end (`pc == end`) remain valid under the end-exclusive rule.
-183
View File
@@ -1,183 +0,0 @@
PR-1.1 — Bytecode Legacy Inventory & Deletion Map
Goal
- Provide an explicit, reviewable inventory of all RC/HIP-era artifacts (opcodes, traps, types, helpers, docs, tests) and a deletion map for the ISA reset.
- No code changes in this PR — documentation only. Follow-up PRs will execute the deletions/edits.
Repository root
- runtime (this file lives at docs/bytecode/RESET_LEGACY_MAP.md)
Quick grep guide (reviewers)
- Use these commands from the project root. They avoid target/ and other generated dirs.
```
# Core RC/HIP signal words
grep -RIn --exclude-dir target --exclude-dir dist-staging --exclude-dir dist-workspace \
-e '\bHIP\b' -e '\bgate\b' -e 'GATE_' -e '\bretain\b' -e '\brelease\b' -e '\bscope\b' .
# Legacy opcodes (bytecode + VM handlers)
grep -RIn --exclude-dir target \
-e 'GateLoad' -e 'GateStore' -e 'GateBeginPeek' -e 'GateEndPeek' \
-e 'GateBeginBorrow' -e 'GateEndBorrow' -e 'GateBeginMutate' -e 'GateEndMutate' \
-e 'GateRetain' -e 'GateRelease' -e 'Alloc' \
crates/console/prometeu-bytecode crates/console/prometeu-vm
# Scope-related (inventory only; not necessarily to delete)
grep -RIn --exclude-dir target -e 'PushScope' -e 'PopScope' crates/console
# Trap codes inventory (post-reset, check for any lingering gate-specific traps)
grep -RIn --exclude-dir target \
-e '\bTRAP_\w\+' \
crates/console/prometeu-bytecode crates/console/prometeu-vm | grep -Ei 'gate|heap|hip' -n || true
# Value::Gate usages
grep -RIn --exclude-dir target -e 'Value::Gate' crates/console
# Docs that describe HIP/RC model
grep -RIn --exclude-dir target --include '*.md' -e '\bHIP\b' docs files
```
Legend for the deletion map
- Remove: file or symbol slated for deletion in follow-up PRs.
- Edit: file will survive but needs edits to remove/rename legacy parts.
- Keep: file or symbol remains under the GC stack+heap model (not part of RC/HIP removal) — listed here when helpful for context.
1) Legacy opcodes (RC/HIP)
Remove — OpCode variants (definitions and all references)
- prometeu-bytecode
- crates/console/prometeu-bytecode/src/opcode.rs
- OpCode::Alloc
- OpCode::GateLoad
- OpCode::GateStore
- OpCode::GateBeginPeek, OpCode::GateEndPeek
- OpCode::GateBeginBorrow, OpCode::GateEndBorrow
- OpCode::GateBeginMutate, OpCode::GateEndMutate
- OpCode::GateRetain, OpCode::GateRelease
- Notes: also appears in TryFrom<u16> mapping and in cycles() table inside same file.
- crates/console/prometeu-bytecode/src/opcode_spec.rs
- Spec entries for each of the above (names: GATE_LOAD, GATE_STORE, GATE_BEGIN_PEEK, ... GATE_RELEASE; ALLOC).
- crates/console/prometeu-bytecode/src/decoder.rs
- Keep file. No direct legacy handling beyond general decoding; remains after removing legacy opcodes.
- crates/console/prometeu-bytecode/src/model.rs
- Keep file. No opcode definitions here; only payload helpers like imm_u32x2 are generic. No deletion but re-check comments if they reference ALLOC semantics.
- crates/console/prometeu-bytecode/src/value.rs
- Edit: enum Value includes Gate(usize). This is HIP-only; plan to remove variant and downstream usages when ISA reset lands.
- crates/console/prometeu-bytecode/src/program_image.rs
- Edit: maps Value to ConstantPoolEntry; has a Value::Gate arm that turns into Null. Will be adjusted once Value::Gate is removed.
- prometeu-vm (execution semantics for legacy opcodes)
- crates/console/prometeu-vm/src/virtual_machine.rs
- Match arms for: Alloc, GateLoad/Store, GateBegin*/End* (Peek/Borrow/Mutate), GateRetain/Release.
- Gate pool and heap structures (GateEntry, GateId), resolve_gate() helper, and related fields in VM state.
- Unit tests tied to HIP/RC model, e.g.:
- fn test_hip_traps_oob()
- fn test_hip_traps_type()
- fn test_invalid_gate_traps()
- fn test_gate_ids_distinct_and_round_trip()
- crates/console/prometeu-vm/src/scope_frame.rs
- Inventory only (scope handling). Scope is not inherently HIP, keep or revise later under GC if needed.
- prometeu-hal / prometeu-system (touch points)
- crates/console/prometeu-hal/src/host_return.rs
- Pushes Value::Gate in some host return paths. Will require edits once Value::Gate is removed.
- crates/console/prometeu-system/*
- No direct HIP opcode handling expected, but grep for Value::Gate and GATE_ in formatting/printing if any.
2) Trap codes (RC/HIP)
Remove — gate-specific traps (delete constants and all usages)
- crates/console/prometeu-bytecode/src/abi.rs
- Remove identifiers tied to HIP/gate semantics
Keep — still meaningful under GC model (names may be revised later, but remain functionally)
- crates/console/prometeu-bytecode/src/abi.rs
- TRAP_OOB (0x03) — out-of-bounds (generic)
- TRAP_INVALID_SYSCALL (0x0000_0007)
- TRAP_STACK_UNDERFLOW (0x0000_0008)
- TRAP_INVALID_LOCAL (0x0000_0009)
- TRAP_DIV_ZERO (0x0000_000A)
- TRAP_INVALID_FUNC (0x0000_000B)
- TRAP_BAD_RET_SLOTS (0x0000_000C)
- TRAP_TYPE — retained; semantics generalized to non-HIP type mismatches
Usages to edit alongside removal
- crates/console/prometeu-vm/src/virtual_machine.rs
- Imports: remove any gate-specific trap imports
- resolve_gate() and gate handlers construct TrapInfo with those codes
- Tests asserting these trap codes
3) Legacy terminology occurrences (inventory)
Gate/GATE_
- Files containing gate-centric logic or names:
- crates/console/prometeu-bytecode/src/opcode.rs — Gate* opcodes
- crates/console/prometeu-bytecode/src/opcode_spec.rs — GATE_* names
- crates/console/prometeu-bytecode/src/value.rs — Value::Gate
- crates/console/prometeu-vm/src/virtual_machine.rs — GateEntry, GateId, handlers, tests
- docs/specs/pbs/Prometeu VM Memory model.md — extensive HIP/gate sections
- docs/specs/pbs/Prometeu Scripting - Prometeu Bytecode Script (PBS).md — HIP/gate model and APIs
Retain/Release (RC semantics)
- Opcode names: GateRetain, GateRelease — bytecode + VM
- Docs: reference counting sections in PBS and VM Memory model docs
Scope
- Opcode names: PushScope, PopScope — present in opcode.rs/opcode_spec.rs and executed in VM
- VM scope_frame.rs and scope_stack usage — not inherently HIP, but inventoried here per task wording
HIP (Heap Interface Protocol)
- Labelled sections/comments:
- crates/console/prometeu-bytecode/src/opcode.rs — comment header “HIP (Heap Interface Protocol)” above Gate* opcodes
- docs/specs/pbs/Prometeu VM Memory model.md — HIP-specific architecture
- docs/specs/pbs/Prometeu Scripting - Prometeu Bytecode Script (PBS).md — HIP world, borrow/mutate/peek, RC
- files/Borrow Mutate - Compiler GC.md — discusses removing RC/HIP in favor of GC; keep as design context but will need text updates after reset
4) Deletion map (by module)
Will be removed outright (symbols or blocks)
- prometeu-bytecode
- opcode.rs: all Gate* variants and Alloc variant; TryFrom/encoding IDs and cycles for those
- opcode_spec.rs: corresponding spec arms (GATE_*, ALLOC)
- abi.rs: gate-specific trap constants
- prometeu-vm
- virtual_machine.rs: handlers for Alloc and all Gate* opcodes; GateEntry/GateId data structures; resolve_gate(); HIP-focused unit tests listed above
Will be edited (kept but changed)
- prometeu-bytecode
- value.rs: remove Value::Gate and update Display/eq code paths
- program_image.rs: remove/adjust Value::Gate mapping in constant pool materialization
- decoder.rs: no semantic change; ensure UnknownOpcode remains deterministic (already the case)
- prometeu-vm
- virtual_machine.rs: remove trap imports for legacy codes; update match to exclude removed opcodes; prune gate/heap fields
- scope_frame.rs: keep unless later ISA changes require scope model changes (not part of HIP removal)
- prometeu-hal
- host_return.rs: stop producing Value::Gate once Value enum loses Gate
Docs to remove or rewrite (architecture reset)
- docs/specs/pbs/Prometeu VM Memory model.md — replace HIP/RC model with GC stack+heap model
- docs/specs/pbs/Prometeu Scripting - Prometeu Bytecode Script (PBS).md — remove HIP world/RC sections; update storage semantics
- Any disasm examples or golden outputs referring to GATE_* or ALLOC — update after opcode removal
Tests/fixtures affected
- Unit tests in prometeu-vm referencing HIP traps or Gate behavior:
- test_hip_traps_oob, test_hip_traps_type, test_invalid_gate_traps, test_gate_ids_distinct_and_round_trip
- Golden disassemblies under test-cartridges/*/build/program.disasm.txt may include GATE_* lines — grep and update in follow-up PRs
5) Reviewer checklist for follow-up PRs
- Bytecode enum/spec cleaned: no Gate*/Alloc variants remain
- VM execution has no references to Gate/GateEntry/resolve_gate
- Value enum no longer has Gate; all Display/eq/serde paths fixed
- Trap ABI contains only GC-era traps (OOB, stack underflow, invalid func/local/syscall, div by zero, bad ret slots, etc.)
- Disassembler/printers do not print legacy names (GATE_*, ALLOC)
- Docs no longer mention HIP/RC; updated to GC model
- All tests green (`cargo test`) after deletions and necessary test updates
6) Notes
- This document inventories occurrences proactively, but exact refactors in the reset may slightly shift responsibilities (e.g., how storage allocation appears under GC). Use the grep guide to double-check any stragglers during code deletion PRs.
-299
View File
@@ -1,299 +0,0 @@
# 📜 Prometeu — The Fire and the Promise
**PROMETEU** is an imaginary console.
But not in the weak sense of "imagining".
PROMETEU was **deliberately designed** to exist as a **complete computational model**: simple enough to be understood, and powerful enough to create real games.
The name PROMETEU carries two intentional meanings:
- **Prometheus, the titan**, who stole fire from the gods and gave it to humans
- **“Prometeu” as a verb**, a promise made (in Portuguese)
In this project:
- the *fire* is the knowledge of how computers really work
- the *promise* is that nothing is magic, nothing is hidden, and everything can be understood
This manual is that written promise.
---
## 🎯 What is PROMETEU
PROMETEU is a **Virtual Microconsole** — a fictitious computer, with clear rules, limited resources, and deterministic behavior.
It was designed to:
- teach real computing fundamentals
- expose time, memory, and execution
- allow full 2D games (platformers, metroidvanias, arcade)
- serve as a bridge between:
- microcontrollers
- classic consoles
- virtual machines
- modern engines
PROMETEU **is not**:
- a generic engine
- a substitute for Unity or Godot
- a real commercial console
PROMETEU **is**:
- a laboratory
- a didactic instrument
- a serious toy
---
## 🧠 Fundamental Mental Model
> PROMETEU is a microcontroller that draws pixels, plays sound, and handles player input.
>
Everything in the system derives from this.
### Conceptual equivalence
| Real microcontroller | PROMETEU |
| --- | --- |
| Clock | VM Tick |
| Flash | PROMETEU Cartridge |
| RAM | Heap + Stack |
| GPIO | Input |
| DMA | Graphics transfer |
| ISR | System events |
| Peripherals | GFX, AUDIO, INPUT, FS |
If you understand an MCU, you understand PROMETEU.
---
## 🧩 Design Philosophy
### 1. Visible Simplicity
- Every operation has a cost
- Every frame has a budget
- Every error has an observable cause
Nothing happens "just because".
### 2. Determinism
- Same cartridge
- Same input
- Same result
Regardless of the platform.
### 3. Limitation as a pedagogical tool
PROMETEU imposes **intentional** limits:
- finite memory
- time per frame
- limited graphics resources
Limits teach design.
### 4. Progressive depth
PROMETEU can be explored in layers:
1. **Game Layer** — `update()` and `draw()`
2. **System Layer** — bytecode, stack, heap
3. **Machine Layer** — cycles, events, peripherals
The student decides how deep to go.
## 🏗️ General Architecture
```
+---------------------------+
| CARTRIDGE |
| (bytecodeX + assets) |
+-------------+-------------+
|
+-------------v-------------+
| PROMETEU VM |
| (stack-based, |
| deterministic) |
+-------------+-------------+
|
+-------------v-------------+
| VIRTUAL PERIPHERALS |
| GFX | AUDIO |INPUT | FS| |
+-------------+-------------+
|
+-------------v-------------+
| PLATFORM LAYER |
| PC | SteamOS | Android |
| iOS | Consoles (future) |
+---------------------------+
```
This manual describes **the PROMETEU machine**, not external tools.
---
## 📦 The PROMETEU Cartridge
A **PROMETEU cartridge** is an immutable package, equivalent to firmware.
Typical content:
- `program.pbx` — PROMETEU bytecode (bytecodeX)
- `assets/` — graphics, audio, maps
- `manifest.json` — metadata and configuration
The cartridge:
- can always be executed
- can always be distributed
- is never blocked by the system
---
## 🧪 Programming Languages
PROMETEU **does not execute high-level languages directly**.
The languages are **sources**, compiled to PROMETEU bytecode.
### Planned languages
- **Java (subset)** — architecture, deep teaching
- **TypeScript (subset)** — accessibility and market
- **Lua (subset)** — classic and lightweight scripting
All converge to:
> The same bytecode. The same VM. The same behavior.
>
---
## 🔄 Execution Model
PROMETEU executes in a fixed loop:
```
BOOT
↓
LOAD CARTRIDGE
↓
INIT
↓
LOOP (60 Hz):
├─INPUT
├─UPDATE
├─ DRAW
├─ AUDIO
└─ SYNC
```
- Default frequency: **60 Hz**
- Each iteration corresponds to **one frame**
- Execution time is **measurable**
---
## ⏱️ CAP — Execution Cap
### Definition
The **CAP** defines an execution budget (time, memory, and resources) **in a specific context**, such as a Game Jam or evaluation.
> CAP never blocks execution.
> CAP never blocks packaging.
> CAP never prevents the game from being played.
>
---
### When the CAP is used
- PROMETEU Game Jams
- Academic evaluations
- Technical challenges
- Comparisons between solutions
Outside of these contexts, PROMETEU operates in **free mode**.
---
### The role of the CAP
The CAP serves to:
- guide technical decisions
- provide measurable feedback
- generate **technical certifications**
- create objective evaluation criteria
PROMETEU **helps during development**:
- visual indicators
- cost alerts
- per-frame profiling
---
## 📄 PROMETEU Certification
### What it is
The **PROMETEU Certification** is a technical report generated from the execution of the game under a defined CAP.
It:
- **does not prevent** the game from running
- **does not invalidate** the delivery
- **records technical evidence**
---
### Report Example
```
PROMETEUCERTIFICATIONREPORT
-----------------------------
Context:PROMETEUJAM#03
Target Profile:PROMETEU-LITE
Execution:
Avg cycles/frame:4,820
Peak cycles/frame:5,612❌
Memory:
Heap peak:34KB❌(limit:32KB)
Status:
❌NOTCOMPLIANT
Notes:
-OverruncausedbyenemyAIupdateloop
-Heappressurecausedbyper-frameallocations
```
The report **accompanies the game**.
---
## 🎓 Educational Use
Evaluation may consider:
- Game quality (creativity, design)
- Technical quality (certification)
- Justified architectural decisions
- Evolution between versions
PROMETEU evaluates **process**, not just result.
< [Summary](topics/table-of-contents.md) >
-254
View File
@@ -1,254 +0,0 @@
< [Summary](table-of-contents.md) | [Next](chapter-2.md) >
# ⏱️ **Time Model and Cycles**
# 1. Overview
PROMETEU is a **time-oriented** system.
Nothing happens "instantly".
Every action consumes **measurable time**, expressed in **execution cycles**.
This chapter defines:
- the system's **base clock**
- the concept of a **PROMETEU cycle**
- how time is distributed across frames
- how the **CAP (Execution Cap)** relates to this model
---
## 2. System Base Clock
PROMETEU operates with a **fixed clock of 60 Hz**.
This means:
- 60 iterations of the main loop per second
- each iteration corresponds to **one frame**
- the clock is **deterministic and stable**, regardless of the platform
> The clock defines the machine's rhythm,
not the amount of mandatory work per frame.
>
---
## 3. The PROMETEU Frame
A **PROMETEU frame** represents a complete unit of execution.
Each frame conceptually executes the following stages:
```
FRAME N
──────────────
INPUT
UPDATE
DRAW
AUDIO
SYNC
──────────────
```
The system guarantees:
- fixed order
- predictable repetition
- absence of "ghost" frames
---
## 4. PROMETEU Cycles
### 4.1 Definition
A **PROMETEU cycle** is the smallest abstract unit of time in the system.
- each VM instruction consumes a fixed number of cycles
- peripheral calls also have a cost
- the cost is **documented and stable**
Cycles are:
- **countable**
- **comparable**
- **independent of real hardware**
---
### 4.2 Why cycles, and not milliseconds?
PROMETEU does not measure time in milliseconds because:
- milliseconds vary between platforms
- real clocks differ
- jitter and latency hide the real cost
Cycles allow stating:
> "This program is more expensive than that one,
>
>
> regardless of where it runs."
>
---
## 5. Per-Frame Budget
Each frame has a **maximum cycle budget**.
This budget:
- is reset every frame
- does not accumulate unused cycles
- represents the capacity of the "virtual CPU"
### Conceptual example
```
Frame Budget:10,000cycles
Used:
-Update logic:4,200
-Draw calls:3,100
-Audio:900
Remaining:
1,800cycles
```
---
## 6. Separation between Clock and Work
PROMETEU **does not require** all logic to run every frame.
The programmer is **explicitly encouraged** to distribute work over time.
### Common examples
- enemy logic every 2 frames (30 Hz)
- pathfinding every 4 frames (15 Hz)
- animations independent of AI
- timers based on frame count
This reflects real-world practices from:
- classic consoles
- embedded systems
- microcontroller firmware
> Not everything needs to happen now.
>
---
## 7. Temporal Distribution as Architecture
PROMETEU treats **work distribution over time** as an architectural decision.
This means that:
- code that runs every frame is more expensive
- distributed code is more efficient
- optimization is, first and foremost, **temporal organization**
PROMETEU teaches:
> performance doesn't just come from "less code",
>
>
> but from **when** the code runs.
>
---
## 8. Execution CAP (Contextual Budget)
### 8.1 What is the CAP
The **CAP** defines a set of technical limits associated with a **specific context**, such as:
- Game Jams
- academic evaluations
- technical challenges
The CAP can define:
- maximum cycle budget per frame
- memory limit
- peripheral call limits
---
### 8.2 CAP does not block execution
Fundamental rules:
- the game **always runs**
- the game **can always be packaged**
- the game **can always be played**
The CAP **never prevents** execution.
---
### 8.3 CAP generates evidence, not punishment
When a CAP is active, PROMETEU:
- measures execution
- records peaks
- identifies bottlenecks
- generates a **certification report**
This report:
- does not block the game
- does not invalidate the delivery
- **documents compliance or non-compliance**
---
## 9. Time-Based Certification
PROMETEU certification analyzes:
- average cycle usage per frame
- maximum peaks
- problematic frames
- cost distribution
Example:
```
Target CAP:PROMETEU-LITE
Frame Budget:5,000cycles
Frame 18231:
Used:5,612cycles❌
Primary cause:
enemy.updateAI():1,012cycles
```
This certification accompanies the game as a **technical artifact**.
---
## 10. Pedagogical Implications
The time and cycles model allows teaching:
- execution planning
- time-oriented architecture
- technical trade-offs
- reading real profiles
< [Summary](table-of-contents.md) | [Next](chapter-2.md) >
-350
View File
@@ -1,350 +0,0 @@
< [Back](chapter-9.md) | [Summary](table-of-contents.md) | [Next](chapter-11.md) >
# 🛠️ **Debug, Inspection, and Profiling**
## 1. Overview
PROMETEU was designed to **be observed**.
Debug, inspection, and profiling **are not optional external tools** —
they are **integral parts of the machine**.
Nothing happens without leaving traces.
Nothing consumes resources without being measured.
Nothing fails without explanation.
> PROMETEU does not hide state.
> PROMETEU exposes behavior.
>
---
## 2. Debug Philosophy in PROMETEU
PROMETEU follows three fundamental debug principles:
1. **State before abstraction**
The programmer sees the machine before seeing “features”.
2. **Time as first class**
Every action is analyzed in the context of the frame and cycles.
3. **Observation does not alter execution**
Debug never changes the behavior of the system.
---
## 3. Execution Modes
PROMETEU operates in three main modes:
### 3.1 Normal Mode
- continuous execution
- no detailed inspection
- focus on game and experience
---
### 3.2 Debug Mode
- controlled execution
- access to internal state
- pauses and stepping
This mode is used for:
- learning
- investigation
- error correction
---
### 3.3 Certification Mode
- deterministic execution
- collected metrics
- report generation
No mode alters the logical result of the program.
---
## 4. Execution Debug
### 4.1 Pause and Resume
The system can be paused at safe points:
- frame start
- before UPDATE
- after DRAW
- before SYNC
During pause:
- state is frozen
- buffers are not swapped
- logical time does not advance
---
### 4.2 Step-by-Step
PROMETEU allows stepping at different levels:
- **by frame**
- **by function**
- **by VM instruction**
Stepping by instruction reveals:
- Program Counter (PC)
- current instruction
- operand stack
- call stack
---
## 5. State Inspection
### 5.1 Stacks
PROMETEU allows inspecting:
- **Operand Stack**
- **Call Stack**
For each frame:
- content
- depth
- growth and cleanup
Stack overflow and underflow are immediately visible.
---
### 5.2 Heap
The heap can be inspected in real time:
- total size
- current usage
- peak usage
- live objects
The programmer can observe:
- allocation patterns
- fragmentation
- GC pressure
---
### 5.3 Global Space
Global variables:
- current values
- references
- initialization
Globals are visible as **static RAM**.
---
## 6. Graphics Debug
PROMETEU allows inspecting the graphics system:
- front buffer
- back buffer
- palette state
- active sprites
It is possible to:
- freeze the image
- observe buffers separately
- identify excessive redraw
---
## 7. Time Profiling (Cycles)
### 7.1 Per-Frame Measurement
For each frame, PROMETEU records:
- total cycles used
- cycles per subsystem
- execution peaks
Conceptual example:
```
Frame 18231:
Total:9,842/10,000cycles
UPDATE:4,210
DRAW:3,180
AUDIO:920
SYSTEM:612
```
---
### 7.2 Per-Function Profiling
PROMETEU can associate cycles with:
- functions
- methods
- logical blocks
This allows answering:
> “where is the time being spent?”
>
---
### 7.3 Per-Instruction Profiling
At the lowest level, the system can display:
- executed instructions
- individual cost
- frequency
This level is especially useful for:
- VM teaching
- deep optimization
- bytecode analysis
---
## 8. Memory Profiling
PROMETEU records:
- average heap usage
- heap peak
- allocations per frame
- GC frequency
Example:
```
Heap:
Avg:24KB
Peak:34KB❌
Limit:32KB
```
These data directly feed the certification.
---
## 9. Breakpoints and Watchpoints
### 9.1 Breakpoints
PROMETEU supports breakpoints in:
- specific frames
- functions
- VM instructions
Breakpoints:
- pause execution
- preserve state
- do not change behavior
---
### 9.2 Watchpoints
Watchpoints monitor:
- variables
- heap addresses
- specific values
Execution can pause when:
- a value changes
- a limit is exceeded
---
## 10. Event and Interrupt Debugging
PROMETEU allows observing:
- event queue
- active timers
- occurred interrupts
Each event has:
- origin
- frame
- cost
- consequence
Nothing happens “silently”.
---
## 11. Integration with CAP and Certification
All debug and profiling data:
- feed the certification report
- are collected deterministically
- do not depend on external tools
The final report is:
- reproducible
- auditable
- explainable
---
## 12. Pedagogical Use
This system allows teaching:
- how to debug real systems
- how to read metrics
- how to correlate time and memory
- how to justify technical decisions
The student learns:
> debug is not trial and error,
> it is informed observation.
>
---
## 13. Summary
- debug is part of the system
- inspection is complete
- profiling is deterministic
- time and memory are visible
- certification is evidence-based
< [Back](chapter-9.md) | [Summary](table-of-contents.md) | [Next](chapter-11.md) >
-258
View File
@@ -1,258 +0,0 @@
< [Back](chapter-10.md) | [Summary](table-of-contents.md) | [Next](chapter-12.md) >
# 🌍 **Portability Guarantees and Cross-Platform Execution**
## 1. Overview
PROMETEU was designed from the beginning to be **portable by construction**, not by later adaptation.
A PROMETEU cartridge:
- executes the same way on any supported platform
- produces the same results for the same inputs
- maintains predictable technical behavior
> PROMETEU does not depend on the platform.
> The platform depends on PROMETEU.
>
This chapter defines the system's **portability contract**.
---
## 2. Fundamental Principle of Portability
Portability in PROMETEU is based on a simple rule:
> Only the PROMETEU VM defines the program's behavior.
>
This means:
- source languages do not matter after compilation
- real hardware does not influence logic
- the operating system does not change semantics
Everything that does not belong to the VM is **adaptation**, not execution.
---
## 3. Separation of Responsibilities
PROMETEU strictly separates three layers:
```
+----------------------------+
| CARTRIDGE |
| (bytecode + assets) |
+-------------+--------------+
|
+-------------v--------------+
| PROMETEU VM |
| (logic, time, memory) |
+-------------+--------------+
|
+-------------v--------------+
| PLATFORM LAYER |
| window, audio, input, FS |
+----------------------------+
```
### What the VM controls
- bytecode execution
- logical time (frames, cycles)
- memory (stack, heap)
- determinism
- costs and metrics
### What the platform provides
- pixel display
- audio output
- physical input collection
- access to the sandbox file system
The platform **never decides behavior**.
---
## 4. Determinism as the Basis of Portability
PROMETEU guarantees determinism through:
- fixed logical clock (60 Hz)
- abstract cycles, not real time
- input sampled per frame
- absence of implicit concurrency
- absence of system-dependent operations
This allows stating:
> “If the cartridge is the same, the game is the same.”
>
---
## 5. Independence from Real Hardware
PROMETEU **does not use**:
- operating system timers
- high-resolution clocks
- CPU-specific instructions
- uncontrolled graphics acceleration
All performance is measured in **PROMETEU cycles**, not in milliseconds.
The real hardware:
- only executes the VM
- never interferes with semantics
---
## 6. Floating Point Precision
To guarantee numerical consistency:
- PROMETEU defines explicit mathematical operations
- avoids dependence on specific FPUs
- standardizes `number` behavior
This avoids:
- divergences between architectures
- unpredictable cumulative errors
- subtle differences between platforms
---
## 7. Cross-Platform Input
PROMETEU abstracts physical input into **logical state**.
- keyboard, gamepad, and touch are mapped externally
- the cartridge only sees logical buttons and axes
- the reading moment is fixed per frame
The same cartridge:
- reacts the same way on PC, mobile, or console
- does not contain device-dependent logic
---
## 8. Cross-Platform Audio
The audio system:
- defines channels and mixing logically
- uses native APIs only as output
- maintains per-frame synchronization
Hardware differences:
- do not change logical timing
- do not change sound sequence
- do not affect certification
---
## 9. Cross-Platform Graphics
The graphics system:
- operates on a logical framebuffer
- uses an indexed palette
- does not depend on a specific GPU
The platform layer:
- only displays the framebuffer
- does not reinterpret graphics commands
PROMETEU **does not delegate graphics decisions to the hardware**.
---
## 10. File System and Persistence
PROMETEU defines a **sandbox logical filesystem**:
- virtual paths
- size limits
- deterministic behavior
The platform maps this filesystem to:
- disk
- mobile storage
- persistent memory
Without changing semantics.
---
## 11. Certification and Portability
The **PROMETEU Certification** is valid for all platforms.
If a cartridge:
- passes on one platform
- with the same inputs
It:
- will pass on all
- will produce the same reports
This is possible because:
> the certification validates the VM, not the environment.
>
---
## 12. What PROMETEU DOES NOT guarantee
PROMETEU **does not promise**:
- identical absolute performance (real FPS)
- identical physical latency
- equivalent energy consumption
PROMETEU promises:
- **identical logical behavior**
- **reproducible technical decisions**
---
## 13. Pedagogical Implications
This model allows teaching:
- the difference between logic and presentation
- why modern engines break determinism
- how to isolate systems
- how to design portable software
The student learns:
> portability is not luck — it is architecture.
>
---
## 14. Summary
- PROMETEU defines behavior in the VM
- platforms only execute
- time is logical, not physical
- input, audio, and graphics are abstracted
- certification is universal
- portability is guaranteed by design
< [Back](chapter-10.md) | [Summary](table-of-contents.md) | [Next](chapter-12.md) >
-236
View File
@@ -1,236 +0,0 @@
< [Back](chapter-11.md) | [Summary](table-of-contents.md) | [Next](chapter-13.md) >
# 🧠 Firmware — PrometeuOS (POS) + PrometeuHub
## 1. Overview
The **PROMETEU Firmware** is composed of two layers:
- **PrometeuOS (POS)**: the system firmware/base. It is the maximum authority for boot, peripherals, PVM execution, and fault handling.
- **PrometeuHub**: the system launcher and UI environment, embedded in the firmware, executed **over** the POS and using the **PROMETEU Window System**.
> **Every cartridge is an App**.
> The difference is the **App mode** (Game or System), specified in the cartridge header.
---
## 2. Terms and Definitions
- **Host**: real platform (desktop, mobile, DIY console, etc.) that calls the core at 60Hz and displays the framebuffer.
- **POS (PrometeuOS)**: firmware (system core). Controls boot, PVM, budget, input latch, peripherals, and crash.
- **PrometeuHub**: system UI / launcher running over POS.
- **PVM (PROMETEU Virtual Machine)**: VM that executes the App's bytecode.
- **App / Cartridge**: PROMETEU executable package (e.g., `.pbc`).
- **AppMode**: App mode in the cartridge header:
- `GAME`: assumes full screen, own UI
- `SYSTEM`: app integrated into the system, should run "in a window" in the Hub
- **Logical frame**: App update unit, terminated by `FRAME_SYNC`.
- **Host tick**: call from the host (real 60Hz).
---
## 3. Responsibilities of the POS (PrometeuOS)
The POS must guarantee:
### 3.1 Boot and System States
- Deterministic RESET (known state)
- Optional SPLASH (short)
- initialization of the PrometeuHub and the Window System
- return to the Hub after app exit/crash
### 3.2 PVM Control
- load cartridge into the PVM
- reset PC/stack/heap upon app start
- execute budget per logical frame
- respect `FRAME_SYNC` as logical frame boundary
- maintain input latched per logical frame
### 3.3 Peripheral Control
- initialization and reset of:
- GFX / buffers
- AUDIO (channels, command queue)
- INPUT / TOUCH
- "safe mode" policy (ignore Hub/config if requested)
### 3.4 Failures and Recovery
- capture fatal PVM faults
- present **POS_CRASH_SCREEN** (outside the PVM)
- allow:
- app restart
- return to Hub
- system reset
---
## 4. Responsibilities of the PrometeuHub
The PrometeuHub must:
- list available Apps in storage
- read metadata from the cartridge header (including `AppMode`)
- allow selection and launch
- apply system theme/UI via Window System
- decide the "execution behavior" based on the `AppMode`
### 4.1 Decision by `AppMode`
When selecting an App:
- If `AppMode = GAME`:
- the Hub delegates to the POS: **execute as a game** (full screen)
- If `AppMode = SYSTEM`:
- the Hub delegates to the POS: **load the App**
- and the Hub **opens a window** and runs the App "integrated into the system"
> Note: the Hub does not execute bytecode directly; it always delegates to the POS.
---
## 5. PROMETEU Window System (System UI)
The Window System is part of the firmware (POS + Hub) and offers:
- global theme (palette, fonts, UI sounds)
- window system (at least: one active window + dialog stack)
- input routing:
- focus, navigation, confirmation/cancellation
- touch as "tap" (single pointer)
### 5.1 System App Integration
System Apps are executed in "window" mode and must:
- respect the viewport area provided by the window
- cooperate with the Window System's focus/inputs
- accept being suspended/closed by the Hub
The Hub can offer window "chrome":
- title
- back/close button
- overlays (toast, dialogs)
---
## 6. Cartridge Header (minimum requirement for the firmware)
The firmware requires every cartridge to provide at least the following in the header:
- `magic` / `version`
- `app_id` (short string or hash)
- `title` (string)
- `entrypoint` (PC address)
- `app_mode`: `GAME` or `SYSTEM`
- (optional) `icon_id` / `cover_id`
- (optional) `requested_cap` / VM version
The POS/HUB must use `app_mode` to decide on execution.
---
## 7. Official Boot States (Firmware)
### 7.1 POS_RESET
- initializes peripherals
- prepares PVM
- loads config
- detects safe mode
Transition: `POS_SPLASH` or `POS_LAUNCH_HUB`
### 7.2 POS_SPLASH (optional)
- displays logo/version
- fixed time or "skip"
Transition: `POS_LAUNCH_HUB`
### 7.3 POS_LAUNCH_HUB
- starts Window System
- enters the Hub loop
Transition: `HUB_HOME`
### 7.4 HUB_HOME
- lists Apps
- allows selection:
- `GAME` → `POS_RUN_GAME(app)`
- `SYSTEM` → `HUB_OPEN_WINDOW(app)` (which delegates `POS_RUN_SYSTEM(app)`)
### 7.5 POS_RUN_GAME(app)
- loads cartridge into the PVM
- executes logical frame (budget + `FRAME_SYNC`)
- presents frames
- maintains latch per logical frame
Exits:
- `APP_EXIT` → `POS_LAUNCH_HUB`
- `APP_FAULT` → `POS_CRASH_SCREEN`
### 7.6 POS_RUN_SYSTEM(app)
- loads cartridge into the PVM (or separate instance, if supported in the future)
- executes under the Hub/Window System cycle
- presents in the window area (viewport)
Exits:
- `APP_EXIT` → returns to the Hub
- `APP_FAULT` → `POS_CRASH_SCREEN` (or crash window + fallback)
### 7.7 POS_CRASH_SCREEN
- displays error (type, PC, stack trace)
- actions: restart app / hub / reset
Transition: as chosen.
---
## 8. Execution Model (Budget, Latch, and `FRAME_SYNC`)
The POS is responsible for guaranteeing:
- **Input latched per logical frame**
- execution in slices (host ticks) until the app reaches `FRAME_SYNC`
- only at `FRAME_SYNC`:
- `present()` (or compose+present)
- advances `logical_frame_index`
- releases input latch
- resets the budget for the next logical frame
If the budget runs out before `FRAME_SYNC`:
- does not present
- maintains latch
- execution continues in the next host tick within the same logical frame
---
## 9. Rules for Returning to the Hub
The firmware must offer a "return to system" mechanism:
- button shortcut (e.g., START+SELECT for X ticks)
- or controlled syscall (System Apps only)
Upon returning to the Hub:
- the POS terminates or suspends the current App
- returns to the Window System with a consistent state
---
## 10. Pedagogical Objectives
This firmware allows teaching:
- boot stages and firmware as an authority
- separation between system and application
- deterministic execution with budget and logical frame
- difference between apps (Game vs System)
- fault tolerance and realistic crash handling
---
## 11. Summary
- POS is the base layer and controls the PVM, budget, latch, peripherals, and crash.
- PrometeuHub is the embedded firmware launcher/UI over the POS.
- Every cartridge is an App; the header defines the `app_mode` (GAME/SYSTEM).
- `GAME` runs in full screen; `SYSTEM` runs integrated into the Hub in a window.
- `FRAME_SYNC` is the logical frame boundary.
< [Back](chapter-11.md) | [Summary](table-of-contents.md) | [Next](chapter-13.md) >
-110
View File
@@ -1,110 +0,0 @@
< [Back](chapter-12.md) | [Summary](table-of-contents.md) | [Next](chapter-14.md) >
# Cartridges
**Version:** 1.0 (stable baseline)
**Status:** Proposal
---
## 1. Objective
Define a minimum and stable contract for Prometeu cartridges, allowing:
* App identification
* Mode selection (Game/System)
* Entrypoint resolution
* Predictable loading by the runtime
---
## 2. Concept
A cartridge is the distributable unit of Prometeu. It can exist as:
* **Directory (dev)** — ideal for development and hot-reload
* **Packaged file (.pmc)** — ideal for distribution
Both share the same logical layout.
---
## 3. Logical Layout
```
<cartridge>/
├── manifest.json
├── program.pbc
└── assets/
└── ...
```
Required fields:
* `manifest.json`
* `program.pbc` (Prometeu bytecode)
---
## 4. manifest.json (Contract v1)
```json
{
"magic": "PMTU",
"cartridge_version": 1,
"app_id": 1234,
"title": "My Game",
"app_version": "1.0.0",
"app_mode": "Game",
"entrypoint": "main"
}
```
### Fields
* `magic`: fixed string `PMTU`
* `cartridge_version`: format version
* `app_id`: unique numerical identifier
* `title`: name of the app
* `app_version`: app version
* `app_mode`: `Game` or `System`
* `entrypoint`: symbol or index recognized by the VM
---
## 5. Runtime Rules
* Validate `magic` and `cartridge_version`
* Read `app_mode` to decide execution flow
* Resolve `entrypoint` in `program.pbc`
* Ignore `assets/` if not supported yet
---
## 6. Usage Modes
### Directory (development)
```
prometeu --run ./mycart/
```
### Packaged file
```
prometeu --run mygame.pmc
```
Both must behave identically in the runtime.
---
## 7. Contract Stability
From v1 onwards:
* `manifest.json` is the source of truth
* Fields can only be added in a backward-compatible manner
* Incompatible changes require a new `cartridge_version`
< [Back](chapter-12.md) | [Summary](table-of-contents.md) | [Next](chapter-14.md) >
-135
View File
@@ -1,135 +0,0 @@
< [Back](chapter-13.md) | [Summary](table-of-contents.md) | [Next](chapter-15.md) >
# Boot Profiles
**Version:** 1.0
**Status:** Proposal
---
## 1. Objective
Define how Prometeu decides what to execute at startup:
* Hub
* Automatic cartridge
* Debug mode
---
## 2. BootTarget Concept
At the beginning of boot, the POS resolves a target:
```rust
enum BootTarget {
Hub,
Cartridge { path: String, debug: bool },
}
```
---
## 3. General Rules
### If BootTarget == Hub
* Firmware enters `HubHome`
* No cartridge is automatically loaded
### If BootTarget == Cartridge
1. Load cartridge
2. Read `app_mode` in the manifest
3. Apply rules:
* `Game`:
* Enter `RunningGame`
* `System`:
* Stay in `HubHome`
* Open the app as a window/system tool
---
## 4. Host CLI
### Default boot
```
prometeu
```
Result: enters the Hub
### Run cartridge
```
prometeu run <cartridge>
```
Result:
* Game → enters directly into the game
* System → opens as a tool in the Hub
### Run with debugger
```
prometeu debug <cartridge>
```
Result:
* Same flow as `run`
* Runtime starts in debug mode
* Waits for connection from the Java Debugger
---
## 5. Firmware States
Firmware maintains only:
* `Boot`
* `HubHome`
* `RunningGame`
* `AppCrashed`
System apps never change the firmware state.
---
## 6. Behavior on Real Hardware (future)
* If miniSD/physical cartridge is present at boot:
* POS can:
* always go to the Hub, or
* auto-execute according to user configuration
---
## 7. Integration with Debugger
When `debug == true`:
* Runtime:
* Initializes
* Opens DevTools socket
* Waits for `start` command
* Only after that does it start cartridge execution
---
## 8. Stability
* BootTarget is an internal POS contract
* Host CLI must respect these rules
* New boot modes must be compatible extensions
< [Back](chapter-13.md) | [Summary](table-of-contents.md) | [Next](chapter-15.md) >
-331
View File
@@ -1,331 +0,0 @@
< [Back](chapter-14.md) | [Summary](table-of-contents.md) | [Next](chapter-16.md) >
# Asset Management
## Bank-Centric Hardware Asset Model
**Scope:** Runtime / Hardware Asset Management (SDK-agnostic)
---
## 1. Fundamental Principles
1. **Every asset in Prometeu resides in a Bank**
2. **A Bank is a hardware memory management system**
3. **Assets are cold binaries stored in the cartridge**
4. **Asset memory belongs to the console, not to the VM**
5. **Loading, residency, and eviction are explicit**
6. **Hardware does not interpret gameplay semantics**
7. **The SDK orchestrates policies; hardware executes contracts**
> In Prometeu, you do not load “data”. You load **residency**.
---
## 2. Asset Origin (Cold Storage)
* All assets initially reside in **cold storage** inside the cartridge.
* Typically, each asset corresponds to a binary file.
* The runtime **never scans the cartridge directly**.
* All access goes through the **Asset Table**.
---
## 3. Asset Table
The Asset Table is an index loaded at cartridge boot.
It describes **content**, not residency.
### Location
* The Asset Table **must be embedded as JSON inside `manifest.json`**.
* Tooling may compile this JSON into a binary table for runtime use, but the source of truth is the manifest.
### Required Fields (conceptual)
* `asset_id` (integer, internal identifier)
* `asset_name` (string, user-facing identifier)
* `asset_type` (TILEBANK, SOUNDBANK, BLOB, TILEMAP, ...)
* `bank_kind` (mandatory, single)
* `offset` (byte offset in cartridge)
* `size` (cold size)
* `decoded_size` (resident size)
* `codec` (RAW, LZ4, ZSTD, ...)
* `asset_metadata` (type-specific)
> `bank_kind` defines **where** an asset may reside in hardware.
---
## 4. Bank — Definition
> **A Bank is the residency and swapping mechanism of the Prometeu hardware.**
A Bank:
* owns **numbered slots**
* enforces **resident memory budgets**
* enforces **staging / inflight budgets**
* accepts only compatible assets
* supports **atomic swap via commit**
* exposes memory and residency metrics
Banks are hardware infrastructure, not assets.
---
## 5. BankKind
Each Bank belongs to a **BankKind**, defining its pipeline and constraints.
### Example BankKinds
* `GFX_TILEBANK`
* `AUDIO_SOUNDBANK`
* `DATA_BLOBBANK`
* `MAP_TILEMAPBANK`
Each BankKind defines:
* slot count
* maximum resident memory
* inflight / staging memory budget
* decode and validation pipeline
* hardware consumer subsystem (renderer, audio mixer, etc.)
---
## 6. Slots and Slot References
* Each BankKind owns a fixed set of **slots**.
* A slot:
* references a resident asset (or is empty)
* never stores data directly
* may expose a **generation counter** (debug)
### Slot Reference
Slots are always referenced with explicit BankKind context:
* `gfxSlot(3)`
* `audioSlot(1)`
* `blobSlot(7)`
This prevents cross-bank ambiguity.
---
## 7. Bank Memory Model
* Bank memory is **console-owned memory**.
* It does not belong to the VM heap.
* It does not participate in GC.
* It can be fully released when the cartridge shuts down.
Each Bank manages:
* total memory
* used memory
* free memory
* inflight (staging) memory
Conceptually, each Bank is a **specialized allocator**.
---
## 8. Unified Loader
### Conceptual API
```text
handle = asset.load(asset_name, slotRef, flags)
```
Load flow:
1. Resolve `asset_name` via Asset Table to get its `asset_id`
2. Read `bank_kind` from asset entry
3. Validate compatibility with `slotRef`
4. Enqueue load request
5. Perform IO + decode on worker
6. Produce materialized asset in staging
### Handle States
* `PENDING` — enqueued
* `LOADING` — IO/decode in progress
* `READY` — staging completed
* `COMMITTED` — installed into slot
* `CANCELED`
* `ERROR`
---
## 9. Commit
```text
asset.commit(handle)
```
* Commit is **explicit** and **atomic**
* Executed at a safe frame boundary
* Performs **pointer swap** in the target slot
* Previous asset is released if no longer referenced
The hardware **never swaps slots automatically**.
---
## 10. Asset Deduplication
* A decoded asset exists **at most once per BankKind**.
* Multiple slots may reference the same resident asset.
* Redundant loads become **install-only** operations.
Memory duplication is forbidden by contract.
---
## 11. Bank Specializations
### 11.1 GFX_TILEBANK
* AssetType: TILEBANK
* Immutable graphical tile + palette structure
* Consumed by the graphics subsystem
### 11.2 AUDIO_SOUNDBANK
* AssetType: SOUNDBANK
* Resident audio samples or streams
* Consumed by the audio mixer
### 11.3 DATA_BLOBBANK
* AssetType: BLOB
* Read-only byte buffers
* Hardware does not interpret contents
Used by the SDK via:
* **Views** (zero-copy, read-only)
* **Decode** (materialization into VM heap)
---
## 12. Views and Decode (SDK Contract)
* **View**
* read-only
* zero-copy
* valid only while the blob remains resident
* **Decode**
* allocates VM-owned entities
* independent from the Bank after creation
Hardware is unaware of Views and Decode semantics.
---
## 13. Manifest and Initial Load
* The cartridge may include a `manifest.json`.
* The manifest may declare:
* assets to preload
* target slot references
These loads occur **before the first frame**.
---
## 14. Shutdown and Eviction
* On cartridge shutdown:
* all Banks are cleared
* all resident memory is released
No implicit persistence exists.
---
## 15. Debugger and Telemetry
Each Bank must expose:
* total memory
* used memory
* free memory
* inflight memory
* occupied slots
* `asset_id` per slot
* `asset_name` per slot
* generation per slot
This enables debuggers to visualize:
* memory stacks per Bank
* memory pressure
* streaming strategies
---
## 16. Minimal Syscall API (Derived)
The following syscalls form the minimal hardware contract for asset management:
```text
asset.load(asset_name, slotRef, flags) -> handle
asset.status(handle) -> LoadStatus
asset.commit(handle)
asset.cancel(handle)
bank.info(bank_kind) -> BankStats
bank.slot_info(slotRef) -> SlotStats
```
Where:
* `LoadStatus` ∈ { PENDING, LOADING, READY, COMMITTED, CANCELED, ERROR }
* `BankStats` exposes memory usage and limits
* `SlotStats` exposes current asset_id, asset_name and generation
---
## 17. Separation of Responsibilities
### Hardware (Prometeu)
* manages memory
* loads bytes
* decodes assets
* swaps pointers
* reports usage
### SDK
* defines packs, scenes, and policies
* interprets blobs
* creates VM entities
### VM
* executes logic
* manages its own heap
* never owns hardware assets
---
## 18. Golden Rule
> **Banks are the foundation of the hardware.**
> **Asset Types describe content.**
> **The SDK orchestrates; the hardware executes.**
< [Back](chapter-14.md) | [Summary](table-of-contents.md) | [Next](chapter-16.md) >
-372
View File
@@ -1,372 +0,0 @@
< [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 identified, resolved, 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.
7. **Language-agnostic identity**: Syscalls are identified by canonical names, not language syntax.
---
## 2 Canonical Syscall Identity
Syscalls are identified by a **canonical triple**:
```
(module, name, version)
```
Example:
```
("gfx", "present", 1)
("input", "state", 1)
("audio", "play", 2)
```
This identity is:
* Independent of language syntax.
* Stable across languages and toolchains.
* Used for capability checks and linking.
### Language independence
Different languages may reference the same syscall using different syntax:
| Language style | Reference form |
| -------------- | --------------- |
| Dot-based | `gfx.present` |
| Namespace | `gfx::present` |
| Object-style | `Gfx.present()` |
| Functional | `present(gfx)` |
All of these map to the same canonical identity:
```
("gfx", "present", 1)
```
The compiler is responsible for this mapping.
---
## 3 Syscall Resolution
The host maintains a **Syscall Registry**:
```
(module, name, version) -> syscall_id
```
Example:
```
("gfx", "present", 1) -> 0x0101
("gfx", "submit", 1) -> 0x0102
("audio", "play", 1) -> 0x0201
```
### Resolution process
At cartridge load time:
1. The cartridge declares required syscalls using canonical identities.
2. The host verifies capabilities.
3. The host resolves each canonical identity to a numeric `syscall_id`.
4. The VM stores the resolved table for fast execution.
At runtime, the VM executes:
```
SYSCALL <id>
```
Only numeric IDs are used during execution.
---
## 4 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 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.
---
## 5 Syscall Metadata Table
Each syscall is defined by a metadata entry.
### SyscallMeta structure
```
SyscallMeta {
id: u32
module: string
name: string
version: u16
arg_slots: u8
ret_slots: u8
capability: CapabilityId
may_allocate: bool
cost_hint: u32
}
```
Fields:
| Field | Description |
| -------------- | ------------------------------------------------ |
| `id` | Unique numeric syscall identifier |
| `module` | Canonical module name |
| `name` | Canonical syscall name |
| `version` | ABI version of the syscall |
| `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 |
The verifier uses this table to validate stack effects.
---
## 6 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]
```
Composite return values are represented as multiple slots (stack tuples).
---
## 7 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.
### Conceptual declaration
```
host fn input_state() -> (int, int, int)
```
This represents a syscall with three return values, but it cannot be treated as a function value.
---
## 8 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 canonical identity cannot be resolved.
* The required capability is missing.
* The stack does not contain enough arguments.
* A handle is invalid or dead.
These are 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.
---
## 9 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.
---
## 10 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.
---
## 11 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
---
## 12 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.
---
## 13 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)
```
---
## 14 Summary
* Syscalls are deterministic, synchronous, and non-blocking.
* They use the same slot-based ABI as functions.
* They are callable but not first-class.
* They are identified canonically by `(module, name, version)`.
* Language syntax does not affect the ABI.
* The host resolves canonical identities to numeric syscall IDs.
* 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) >
-427
View File
@@ -1,427 +0,0 @@
< [Back](chapter-1.md) | [Summary](table-of-contents.md) | [Next](chapter-3.md) >
# **Prometeu Virtual Machine (PVM)**
This chapter defines the execution model, value system, calling convention, memory model, and host interface of the Prometeu Virtual Machine.
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. fileciteturn2file0
---
## 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
* bounded by frame budget
Coroutine stacks are part of the GC root set.
---
## 10 Garbage Collection
The PVM uses a **mark-sweep collector**.
### GC rules
* 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
---
## 11 Event and Interrupt Model
The PVM does not allow asynchronous callbacks.
All events are:
* queued by the firmware
* delivered at `FRAME_SYNC`
This ensures:
* deterministic execution
* 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) >
-353
View File
@@ -1,353 +0,0 @@
< [Back](chapter-2.md) | [Summary](table-of-contents.md) | [Next](chapter-4.md) >
# 🧠 **Memory Model**
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.
The memory model is designed to be:
* deterministic
* safe
* simple to verify
* suitable for real-time 2D games
---
## 1 Overview
The PVM uses a **split memory model**:
1. **Stack memory**
* used for temporary values
* function arguments
* multi-return tuples
2. **Heap memory**
* used for all user-defined objects
* accessed only through handles
3. **Host-owned memory**
* asset banks
* audio buffers
* framebuffers
* not part of the VM heap
---
## 2 Stack Memory
The stack is used for:
* primitive values
* built-in value types
* temporary results
* function arguments
* tuple returns
### Stack value types
| 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 |
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 Tuples (Stack-Only Aggregates)
Tuples are used for multi-value returns.
### 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.
### Example
Function returning two values:
```
fn position(): (int, int)
```
At runtime:
```
stack top → [x, y]
```
---
## 4 Heap Memory
All user-defined objects live in the heap.
### Heap characteristics
* 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 Handles and Gate Table
All heap objects are accessed via **handles**.
A handle is defined as:
```
handle = { index, generation }
```
The VM maintains a **gate table**:
```
GateEntry {
alive: bool
generation: u32
base: usize
slots: u32
type_id: u32
}
```
### Handle safety
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
---
## 6 Object Layout
Heap objects have a simple, fixed layout:
```
Object {
type_id
field_0
field_1
...
}
```
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).
---
## 7 Closures
Closures are heap objects.
Layout:
```
Closure {
func_id
capture_count
captures[]
}
```
Captures may be:
* copied values
* handles to heap objects
Closure environments are part of the GC root set.
---
## 8 Coroutine Memory
Each coroutine owns its own stacks:
```
Coroutine {
call_stack
operand_stack
state
}
```
All coroutine stacks are included in the GC root set.
Coroutines do not share stacks or frames.
---
## 9 Garbage Collection
The PVM uses a **mark-sweep collector**.
### GC properties
* Non-moving (no compaction in v1).
* Runs only at **safepoints**.
* Primary safepoint: `FRAME_SYNC`.
### 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 Allocation and Deallocation
### Allocation
Heap allocation:
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 Host-Owned Memory (Asset Banks)
Asset memory is **not part of the VM heap**.
It is managed by the firmware.
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 Save Memory (MEMCARD)
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) >
-600
View File
@@ -1,600 +0,0 @@
< [Back](chapter-3.md) | [Summary](table-of-contents.md) | [Next](chapter-5.md) >
# 🎨 **GFX Peripheral (Graphics System)**
## 1. Overview
The **GFX** peripheral is responsible for generating images in PROMETEU.
It models **simple graphics hardware**, inspired by classic consoles
(SNES, CPS-2, Neo-Geo), prioritizing:
- determinism
- low computational cost
- didactics
- portability
The GFX **is not a modern GPU**.
It is an explicit device, based on:
- framebuffer
- tilemaps
- tile banks
- priority-based sprites
- composition by drawing order
---
## 2. Resolution and Framebuffer
### Base resolution
- **320 × 180 pixels**
- aspect ratio close to 16:9
- scalable by the host (nearest-neighbor)
### Pixel format
- **RGB565**
- 5 bits Red
- 6 bits Green
- 5 bits Blue
- no alpha channel
Transparency is handled via **color key**.
---
## 3. Double Buffering
The GFX maintains two buffers:
- **Back Buffer** — where the frame is built
- **Front Buffer** — where the frame is displayed
Per-frame flow:
1. The system draws to the back buffer
2. Calls `present()`
3. Buffers are swapped
4. The host displays the front buffer
This guarantees:
- no tearing
- clear per-frame synchronization
- deterministic behavior
---
## 4. PROMETEU Graphical Structure
The graphical world is composed of:
- Up to **16 Tile Banks**
- **4 Tile Layers** (scrollable)
- **1 HUD Layer** (fixed, always on top)
- Sprites with priority between layers
### 4.1 Tile Banks
- There are up to **16 banks**
- Each bank has a fixed tile size:
- 8×8, 16×16, or 32×32
- A bank is a graphics library:
- environment
- characters
- UI
- effects
### 4.2 Layers
- There are:
- 4 Tile Layers
- 1 HUD Layer
- Each layer points to **a single bank**
- Sprites can use **any bank**
- HUD:
- does not scroll
- maximum priority
- generally uses 8×8 tiles
---
## 5. Internal Model of a Tile Layer
A Tile Layer **is not a bitmap of pixels**.
It is composed of:
- A **logical Tilemap** (tile indices)
- A **Border Cache** (window of visible tiles)
- A **Scroll Offset**
### Structure:
- `bank_id`
- `tile_size`
- `tilemap` (large matrix)
- `scroll_x`, `scroll_y`
- `cache_origin_x`, `cache_origin_y`
- `cache_tiles[w][h]`
---
## 6. Logical Tilemap
The tilemap represents the world:
Each cell contains:
- `tile_id`
- `flip_x`
- `flip_y`
- `priority` (optional)
- `palette_id` (optional)
The tilemap can be much larger than the screen.
---
## 7. Border Cache (Tile Cache)
The cache is a window of tiles around the camera.
Example:
- Screen: 320×180
- 16×16 tiles → 20×12 visible
- Cache: 22×14 (1-tile margin)
It stores tiles already resolved from the tilemap.
---
## 8. Cache Update
Every frame:
1. Calculate:
- `tile_x = scroll_x / tile_size`
- `tile_y = scroll_y / tile_size`
- `offset_x = scroll_x % tile_size`
- `offset_y = scroll_y % tile_size`
2. If `tile_x` changed:
- Advance `cache_origin_x`
- Reload only the new column
3. If `tile_y` changed:
- Advance `cache_origin_y`
- Reload only the new line
Only **one row and/or column** is updated per frame.
---
## 9. Cache as Ring Buffer
The cache is circular:
- Does not physically move data
- Only moves logical indices
Access:
- `real_x = (cache_origin_x + logical_x) % cache_width`
- `real_y = (cache_origin_y + logical_y) % cache_height`
---
## 10. Projection to the Back Buffer
For each frame:
1. For each Tile Layer, in order:
- Rasterize visible tiles from the cache
- Apply scroll, flip, and transparency
- Write to the back buffer
2. Draw sprites:
- With priority between layers
- Drawing order defines depth
3. Draw HUD layer last
---
## 11. Drawing Order and Priority
- There is no Z-buffer
- There is no automatic sorting
- Whoever draws later is in front
Base order:
1. Tile Layer 0
2. Tile Layer 1
3. Tile Layer 2
4. Tile Layer 3
5. Sprites (by priority between layers)
6. HUD Layer
---
## 12. Transparency (Color Key)
- One RGB565 value is reserved as TRANSPARENT_KEY
- Pixels with this color are not drawn
```
if src == TRANSPARENT_KEY:
skip
else:
draw
```
---
## 13. Color Math (Discrete Blending)
Inspired by the SNES.
Official modes:
- `BLEND_NONE`
- `BLEND_HALF`
- `BLEND_HALF_PLUS`
- `BLEND_HALF_MINUS`
- `BLEND_FULL`
No continuous alpha.
No arbitrary blending.
Everything is:
- integer
- cheap
- deterministic
---
## 14. Where Blend is Applied
- Blending occurs during drawing
- The result goes directly to the back buffer
- There is no automatic post-composition
---
## 15. What the GFX DOES NOT support
By design:
- Continuous alpha
- RGBA framebuffer
- Shaders
- Modern GPU pipeline
- HDR
- Gamma correction
---
## 16. Performance Rule
- Layers:
- only update the border when crossing a tile
- never redraw the entire world
- Rasterization:
- always per frame, only the visible area
- Sprites:
- always redrawn per frame
---
## 17. Special PostFX — Fade (Scene and HUD)
PROMETEU supports **gradual fade** as a special PostFX, with two independent
controls:
- **Scene Fade**: affects the entire scene (Tile Layers 0–3 + Sprites)
- **HUD Fade**: affects only the HUD Layer (always composed last)
The fade is implemented without continuous per-pixel alpha and without floats.
It uses a **discrete integer level** (0..31), which in practice produces an
"almost continuous" visual result in 320×180 pixel art.
---
### 17.1 Fade Representation
Each fade is represented by:
- `fade_level: u8` in the range **[0..31]**
- `0` → fully replaced by the fade color
- `31` → fully visible (no fade)
- `fade_color: RGB565`
- color the image will be blended into
Registers:
- `SCENE_FADE_LEVEL` (0..31)
- `SCENE_FADE_COLOR` (RGB565)
- `HUD_FADE_LEVEL` (0..31)
- `HUD_FADE_COLOR` (RGB565)
Common cases:
- Fade-out: `fade_color = BLACK`
- Flash/teleport: `fade_color = WHITE`
- Special effects: any RGB565 color
---
### 17.2 Fade Operation (Blending with Arbitrary Color)
For each RGB565 pixel `src` and fade color `fc`, the final pixel `dst` is calculated per channel.
1) Extract components:
- `src_r5`, `src_g6`, `src_b5`
- `fc_r5`, `fc_g6`, `fc_b5`
2) Apply integer blending:
```
src_weight = fade_level // 0..31
fc_weight = 31 - fade_level
r5 = (src_r5 * src_weight + fc_r5 * fc_weight) / 31
g6 = (src_g6 * src_weight + fc_g6 * fc_weight) / 31
b5 = (src_b5 * src_weight + fc_b5 * fc_weight) / 31
```
- `src_r5`, `src_g6`, `src_b5`
- `fc_r5`, `fc_g6`, `fc_b5`
3) Repack:
```
dst = pack_rgb565(r5, g6, b5)
```
Notes:
- Deterministic operation
- Integers only
- Can be optimized via LUT
---
### 17.3 Order of Application in the Frame
The frame composition follows this order:
1. Rasterize **Tile Layers 0–3** → Back Buffer
2. Rasterize **Sprites** according to priority
3. (Optional) Extra pipeline (Emission/Light/Glow etc.)
4. Apply **Scene Fade** using:
- `SCENE_FADE_LEVEL`
- `SCENE_FADE_COLOR`
5. Rasterize **HUD Layer**
6. Apply **HUD Fade** using:
- `HUD_FADE_LEVEL`
- `HUD_FADE_COLOR`
7. `present()`
Rules:
- Scene Fade never affects the HUD
- HUD Fade never affects the scene
---
### 17.4 Use Cases
- HUD Switch:
- decrease `HUD_FADE_LEVEL` to 0
- switch HUD/tilemap
- increase `HUD_FADE_LEVEL` to 31
- Area Switch:
- decrease `SCENE_FADE_LEVEL` to 0
- switch scenery
- increase `SCENE_FADE_LEVEL` to 31
- Flash / damage / teleport:
- use `fade_color = WHITE` or another thematic color
---
## 18. Palette System
### 18.1. Overview
PROMETEU uses **exclusively** palette-indexed graphics.
There is no direct RGB-per-pixel mode.
Every graphical pixel is an **index** pointing to a real color in a palette.
Objectives:
- reduce RAM and storage usage
- allow color swapping without shaders
- maintain retro identity
- facilitate effects like variation, damage, day/night
---
### 18.2. Pixel Format
Each pixel of a tile or sprite is:
- **4 bits per pixel (4bpp)**
- values: `0..15`
Fixed rule:
- Index `0` = TRANSPARENT
- Indices `1..15` = valid palette colors
---
### 18.3. Palette Structure
Each **Tile Bank** contains:
- Up to **256 palettes**
- Each palette has:
- **16 colors**
- each color in **RGB565 (u16)**
Size:
- 1 palette = 16 × 2 bytes = **32 bytes**
- 256 palettes = **8 KB per bank**
- 16 banks = **128 KB maximum palettes**
---
### 18.4. Palette Association
#### Fundamental Rule
- Each **tile** uses **a single palette**
- Each **sprite** uses **a single palette**
- The palette must be provided **explicitly** in every draw
There is no palette swap within the same tile or sprite.
---
### 18.5. Where the Palette is Defined
#### Tilemap
Each tilemap cell contains:
- `tile_id`
- `palette_id (u8)`
- `flip_x`
- `flip_y`
#### Sprite
Each sprite draw contains:
- `bank_id`
- `tile_id`
- `palette_id (u8)`
- `x`, `y`
- `flip_x`, `flip_y`
- `priority`
---
### 18.6. Color Resolution
The pipeline works like this:
1. Read indexed pixel from tile (value 0..15)
2. If index == 0 → transparent pixel
3. Otherwise:
- real_color = palette[palette_id][index]
4. Apply:
- flip
- discrete blend
- writing to back buffer
In other words:
```
pixel_index = tile_pixel(x,y)
if pixel_index == 0:
skip
else:
color = bank.palettes[palette_id][pixel_index]
draw(color)
```
---
### 18.7. Organization of Tile Banks
Tile Banks are "strong assets":
- Tiles and palettes live together
- Export/import always carries:
- tiles + palettes
- The hardware does not impose semantic organization:
- grouping is the creator's decision
- Tooling and scripts can create conventions:
- e.g.: palettes 0..15 = enemies
- 16..31 = scenery
- etc.
---
### 18.8. Possible Effects with Palettes
Without shaders, it is possible to:
- Palette swap:
- enemies with color variation
- States:
- damage, ice, poison, power-up
- Day / night:
- swap palettes globally
- Biomes:
- same art, different climate
- UI themes
All this without changing tiles.
---
### 18.9. Artistic Limitations
- Each tile/sprite:
- maximum of 16 colors
- Smooth gradients require:
- dithering
- discrete blend
- glow/emission
This limitation is intentional and part of the PROMETEU identity.
---
### 18.10. Metrics for Certification (CAP)
The system can measure:
- `palettes_loaded_total`
- `palettes_referenced_this_frame`
- `tiles_drawn_by_palette_id`
- `sprites_drawn_by_palette_id`
This allows:
- analyzing artistic cost
- teaching the impact of excessive variety
- suggesting best practices for visual cohesion
---
## 19. Summary
PROMETEU's GFX is simple **by choice**, not by limitation.
- RGB565 Framebuffer with double buffer
- Color key for transparency
- SNES-style discrete blending
- Up to 16 tile banks
- 4 Tile Layers + 1 HUD
- Layer = tilemap + cache + scroll
- Rasterized projection per frame
- Depth defined by drawing order
< [Back](chapter-3.md) | [Summary](table-of-contents.md) | [Next](chapter-5.md) >
-331
View File
@@ -1,331 +0,0 @@
< [Back](chapter-4.md) | [Summary](table-of-contents.md) | [Next](chapter-6.md) >
# 🔊 AUDIO Peripheral (Audio System)
## 1. Overview
The **AUDIO Peripheral** is responsible for **sound generation and mixing** in PROMETEU.
Just like the other subsystems:
- it is not automatic
- it is not free
- it is not magic
Each sound is the result of **explicit commands**, executed under a **time and resource budget**.
> Sound consumes time.
> Sound consumes memory.
---
## 2. Philosophy
PROMETEU treats audio as:
- an **active peripheral**
- with **limited channels**
- **deterministic** behavior
- **explicit** control
Objective: architectural and didactic clarity, not absolute realism.
---
## 3. General Architecture
The audio system is composed of:
- **Voices (channels)** — independent players
- **Samples** — PCM data
- **Mixer** — summation of voices
- **Output** — PCM stereo buffer
Conceptual separation:
- Game sends **commands at 60Hz**
- Audio is **generated continuously** at 48kHz
---
## 4. Output Format
- Sample rate: **48,000 Hz**
- Format: **PCM16 stereo (signed i16)**
- Clipping: saturation/clamp
This format is compatible with:
- common I2S DACs
- HDMI audio
- USB audio
- DIY SBCs (Raspberry Pi, Orange Pi, etc.)
---
## 5. Voices (Channels)
### 5.1 Quantity
```
MAX_VOICES = 16
```
Each voice:
- plays **1 sample at a time**
- is independent
- is mixed into the final output
---
### 5.2 Voice State
Each voice maintains:
- `sample_id`
- `pos` (fractional position in the sample)
- `rate` (pitch)
- `volume` (0..255)
- `pan` (0..255, left→right)
- `loop_mode` (off / on)
- `loop_start`, `loop_end`
- `priority` (optional)
---
### 5.3 Voice Conflict
If all voices are occupied:
- an explicit policy is applied:
- `STEAL_OLDEST`
- `STEAL_QUIETEST`
- `STEAL_LOWEST_PRIORITY`
PROMETEU does not resolve this automatically without a defined rule.
---
## 6. Conceptual Model: “Audio CPU”
The PROMETEU AUDIO is conceived as an **independent peripheral**, just as classic consoles had:
- Main game CPU
- Dedicated sound CPU
In PROMETEU:
- The **logical core** assumes this conceptual separation
- The **host decides** how to implement it:
- same thread
- separate thread
- separate core
### 6.1 Hardware Metaphor
Conceptually:
```
[Game CPU] → sends 60Hz commands → [AUDIO Peripheral]
|
v
Voices + Mixer
|
v
PCM Output
```
### 6.2 Implementation is the Host's Role
The core:
- defines the **model**
- defines the **commands**
- defines the **limits**
The host:
- chooses:
- threads
- CPU affinity
- audio backend
- guarantees continuous delivery of buffers
Thus:
> PROMETEU models the hardware.
> The host decides how to physically realize it.
---
## 7. Samples
### 7.1 Format
PROMETEU samples:
- **PCM16 mono**
- own sample_rate (e.g., 22050, 44100, 48000)
- immutable data at runtime
Fields:
- `sample_rate`
- `frames_len`
- `loop_start`, `loop_end` (optional)
---
### 7.2 Usage
Example:
```
audio.play(sample_id, voice_id, volume, pan, pitch, priority)
```
Or:
```
audio.playAuto(sample_id, volume, pan, pitch, priority)
```
(uses stealing policy)
---
## 8. Pitch and Interpolation
- `rate = 1.0` → normal speed
- `rate > 1.0` → higher pitch
- `rate < 1.0` → lower pitch
As position becomes fractional:
- **linear interpolation** is used between two neighboring samples
---
## 9. Mixer
For each output frame (48kHz):
1. For each active voice:
- read sample at current position
- apply pitch
- apply volume
- apply pan → generates L/R
2. Sum all voices
3. Apply clamp
4. Write to the stereo buffer
Cost depends on:
- number of active voices
- use of interpolation
---
## 10. Synchronization with the Game
- Game runs at **60Hz**
- Audio generates data at **48kHz**
Every frame (60Hz):
- game sends commands:
- play
- stop
- set_volume
- set_pan
- set_pitch
The audio applies these commands and continues playing.
---
## 11. Basic Commands
Conceptual examples:
```
audio.play(sample, voice, volume, pan, pitch, priority)
audio.stop(voice)
audio.setVolume(voice, v)
audio.setPan(voice, p)
audio.setPitch(voice, p)
audio.isPlaying(voice)
```
---
## 12. Audio and CAP
Audio participates in the Execution CAP:
- mixing cost per frame
- cost per active voice
- command cost
Example:
```
Frame 1024:
voices_active: 9
mix_cycles: 410
audio_commands: 6
```
---
## 13. Best Practices
Recommended:
- reuse samples
- limit simultaneous voices
- treat sound as an event
- separate music and effects
Avoid:
- playing sound every frame
- abusing voices
- giant samples for simple effects
---
## 14. Historical Inspiration
The PROMETEU model is inspired by:
- NES: fixed channels
- SNES: sample playback + mixing
- CPS2: comfortable polyphony
- Neo Geo: heavy samples (not fully copied)
But abstracted for:
- clarity
- simplicity
- teaching
---
## 15. Summary
- Output: stereo PCM16 @ 48kHz
- 16 voices
- mono PCM16 samples
- Volume, pan, pitch
- Linear interpolation
- Explicit mixer
- "Audio CPU" concept
- Implementation is the host's role
< [Back](chapter-4.md) | [Summary](table-of-contents.md) | [Next](chapter-6.md) >
-260
View File
@@ -1,260 +0,0 @@
< [Back](chapter-5.md) | [Summary](table-of-contents.md) | [Next](chapter-7.md) >
# 🎮 **INPUT Peripheral (Input System)**
## 1. Overview
The **INPUT Peripheral** is responsible for **collecting and providing the state of controls** to the PROMETEU program.
In PROMETEU:
- input is **state**, not an implicit event
- input is **sampled over time**, not delivered asynchronously
- input has a **defined order, cost, and moment**
> Buttons do not “trigger events”.
> They change state.
>
---
## 2. Philosophy of the Input System
PROMETEU models input like classic hardware:
- the state of controls is read **once per frame**
- the program queries this state during `UPDATE`
- there are no asynchronous input callbacks
This model:
- is deterministic
- is simple to understand
- reflects microcontrollers and classic consoles
---
## 3. Input Devices
PROMETEU abstracts different devices into a common interface.
Typical devices:
- digital control (D-Pad + botões)
- keyboard (mapped to buttons)
- gamepad
- touch (mobile, mapped)
Regardless of the origin, PROMETEU exposes **the same logical model**.
---
## 4. State Model
### 4.1 Per-Frame State
For each frame, the system maintains:
- current state of buttons
- state from the previous frame
This allows querying:
- button pressed
- button released
- button held down
---
### 4.2 Query Types
Typical operations:
```
input.btn(id)// button is pressed
input.btnp(id)// button was pressed this frame
input.btnr(id)// button was released this frame
```
These functions:
- are purely advisory
- do not change state
- have an explicit cost
---
## 5. Sampling Moment
The input state is captured **at the beginning of each frame**, before the `UPDATE` phase.
Conceptual flow:
```
FRAME N:
SAMPLEINPUT
UPDATE
DRAW
AUDIO
SYNC
```
Throughout the entire frame:
- the input state is immutable
- repeated calls return the same value
> Input does not change in the middle of the frame.
>
---
## 6. Determinism and Reproducibility
The PROMETEU input model guarantees:
- same sequence of inputs
- same frames
- same results
This allows:
- execution playback
- deterministic replays
- reliable certification
Input can be:
- recorded
- played back
- artificially injected
---
## 7. Input and CAP
Input operations:
- consume few cycles
- participate in the per-frame budget
- appear in certification reports
Example:
```
Frame 18231:
input.btn():12cycles
```
Although cheap, input **is not free**.
---
## 8. Button Mapping
### 8.1 Logical Identifiers
PROMETEU defines logical button identifiers:
- `UP`, `DOWN`, `LEFT`, `RIGHT`
- `A`, `B`, `X`, `Y`
- `START`, `SELECT`
The physical mapping:
- depends on the platform
- is resolved outside the VM
- is transparent to the program
---
### 8.2 Portability
The same PROMETEU cartridge:
- runs on a keyboard
- runs on a gamepad
- runs on touch
Without any code changes.
---
## 9. Analog Input (Optional)
PROMETEU can expose analog axes explicitly:
```
input.axis(id)
```
Characteristics:
- normalized value (e.g.: -1.0 to 1.0)
- explicit cost
- per-frame update
Analog input:
- is not mandatory
- does not replace digital input
- must be used consciously
---
## 10. Input Best Practices
PROMETEU encourages:
- treating input as state
- querying input only in `UPDATE`
- separating input from heavy logic
- mapping actions, not keys
And discourages:
- logic dependent on excessive polling
- reading input in DRAW
- direct coupling to physical hardware
---
## 11. Relationship with Classic Consoles
The PROMETEU model reflects:
- reading input registers
- per-frame polling
- absence of asynchronous events
This model:
- simplifies reasoning
- increases predictability
- facilitates debugging
---
## 12. Pedagogical Implications
The INPUT Peripheral allows teaching:
- the difference between event and state
- temporal sampling
- determinism in interactive systems
- synchronization between input and logic
With clear and reproducible feedback.
---
## 13. Summary
- input is state, not an event
- sampled once per frame
- immutable during the frame
- queries have an explicit cost
- input participates in the CAP
- model is deterministic
< [Back](chapter-5.md) | [Summary](table-of-contents.md) | [Next](chapter-7.md) >
-262
View File
@@ -1,262 +0,0 @@
< [Back](chapter-6.md) | [Summary](table-of-contents.md) | [Next](chapter-8.md) >
# 🖐️ TOUCH Peripheral (Absolute Pointer Input System)
## 1. Overview
The **TOUCH** peripheral provides PROMETEU with an **absolute pointer**, based on screen coordinates, intended for:
- UI interaction
- direct element selection
- contextual actions in the scenery
- drag-based mechanics (drag, slash, trail)
The TOUCH is a **first-class peripheral**, as valid as D-Pad and buttons.
---
## 2. Design Principles
TOUCH in PROMETEU follows strict principles:
- ✅ **Universal single-touch**
- ✅ **Deterministic**
- ✅ **Per-frame state**
- ✅ **No gestures**
- ✅ **No acceleration**
- ✅ **No heuristics**
- ✅ **Same behavior on all platforms**
> If a behavior cannot be guaranteed on all platforms, it does not exist in PROMETEU.
>
---
## 3. Conceptual Model
PROMETEU exposes **only one active pointer at a time**, regardless of how many physical touches the hardware recognizes.
- Hardware may detect multitouch
- Runtime selects **only one active touch**
- The API **never exposes multitouch**
This model guarantees:
- total portability
- predictability
- absence of ambiguities
---
## 4. Coordinate Space
- TOUCH coordinates use **the same space as the framebuffer**
- Resolution: **320×180**
- Origin: top-left corner `(0,0)`
- Ranges:
- `x ∈ [0, 319]`
- `y ∈ [0, 179]`
TOUCH is **absolute**:
> (x, y) represents the exact position of contact, without dynamic transformation.
>
---
## 5. TOUCH Peripheral API
### 5.1 Exposed Structure
```
TOUCH:
present : bool
down : bool
pressed : bool
released : bool
x : int
y : int
```
---
### 5.2 Field Semantics
- **present**
- `true` if the TOUCH peripheral is available
- `false` if there is no physical touch (desktop, hardware without touch)
- **down**
- `true` while the active pointer is pressed
- **pressed**
- `true` only in the frame where the active pointer was captured
- **released**
- `true` only in the frame where the active pointer was released
- **x, y**
- current position of the active pointer
- valid only when `down == true`
---
## 6. Pointer Selection Policy
### *Single Pointer Capture Policy*
When multiple physical touches occur, PROMETEU applies the following policy:
---
### 6.1 Initial Capture
1. If **no pointer is active**
2. And a **new physical touch** occurs
3. The **first detected touch** is captured
4. This touch becomes the **active pointer**
This frame generates:
- `pressed = true`
- `down = true`
---
### 6.2 Capture Maintenance
While the active pointer is pressed:
- Only it is tracked
- All other physical touches are ignored
- `x, y` follow only the active pointer
---
### 6.3 Release
When the active pointer is released:
- `released = true`
- `down = false`
- The system enters a **no active pointer** state
---
### 6.4 Recapture (Important Rule)
After release:
- Touches that **were already present** are ignored
- A new pointer is only captured with a **new touch event**
> This avoids unexpected pointer jumps and accidental actions.
>
---
## 7. Deliberately NOT Supported Behaviors
The TOUCH peripheral **does not implement**:
❌ Multitouch
❌ Gestures (swipe, pinch, rotate, long-press)
❌ Acceleration or smoothing
❌ Dynamic sensitivity
❌ Implicit history
❌ Intent interpretation
If a game wants any of these behaviors, it must:
- implement them explicitly
- using only per-frame state
- without implicit hardware support
---
## 8. “No Gesture” — Formal Definition
PROMETEU **does not interpret temporal patterns**.
The TOUCH peripheral **does not classify actions** as:
- swipe
- drag
- long press
- double tap
It only reports:
- current position
- contact state
All semantics are the game's responsibility.
---
## 9. “No Acceleration” — Formal Definition
PROMETEU **does not modify** the TOUCH input.
- No sensitivity curves
- No speed-based amplification
- No smoothing
The relationship between the physical touch and `(x, y)` is **1:1** after normalization.
---
## 10. Integration with Other Input Forms
- Desktop:
- mouse can emulate TOUCH
- Mobile:
- direct physical touch
- Steam Deck:
- physical touchscreen
- PROMETEU Hardware:
- optional touch, but supported
From PROMETEU's point of view:
> TOUCH is always TOUCH.
>
---
## 11. Expected Uses
The TOUCH peripheral is suitable for:
- UI (menus, inventory, maps)
- drag-and-drop
- direct selection
- “click to investigate”
- pointing-based puzzles
- trail mechanics (e.g.: Fruit Ninja-like)
---
## 12. Portability Guarantees
Every PROMETEU game that uses TOUCH:
- behaves identically on all platforms
- does not depend on host-specific capabilities
- does not suffer semantic variation between desktop, mobile, and dedicated hardware
---
## 13. Summary
The TOUCH in PROMETEU is:
- simple
- explicit
- predictable
- universal
- deterministic
< [Back](chapter-6.md) | [Summary](table-of-contents.md) | [Next](chapter-8.md) >
-238
View File
@@ -1,238 +0,0 @@
< [Back](chapter-7.md) | [Summary](table-of-contents.md) | [Next](chapter-9.md) >
# 📀 MEMCARD Peripheral (Save/Load System)
## 1. Overview
The **MEMCARD** is the peripheral responsible for the **explicit persistence of game data** in PROMETEU.
It simulates the behavior of classic *memory cards* (PS1, GameCube), providing:
- limited storage
- explicit I/O cost
- full game control over when to save
- portability across platforms
The MEMCARD **is not a save state**.
It represents **data that the game itself decides to persist**.
---
## 2. Design Principles
The MEMCARD peripheral follows these principles:
- ✅ **Explicit persistence** (nothing automatic)
- ✅ **Limited and known size**
- ✅ **Mandatory commit**
- ✅ **Measurable time cost (cycles)**
- ✅ **Stable and documented format**
- ✅ **Platform independent**
- ❌ No complex file system (in v0.1)
- ❌ No multiple internal files (in v0.1)
---
## 3. Conceptual Model
Each PROMETEU cartridge can access **one or more MEMCARD slots**, the default model being:
- **Slot A** — main
- **Slot B** — optional (future)
Each slot corresponds to **a file on the host**:
```
MyGame_A.mem
MyGame_B.mem
```
The runtime mounts this file as a **persistent storage device**.
---
## 4. Capacity and CAP
The size of the MEMCARD is **fixed**, defined by the execution profile (CAP).
### Suggested sizes
| Profile | Size |
| --- | --- |
| JAM | 8 KB |
| STANDARD | 32 KB |
| ADVANCED | 128 KB |
The game **cannot exceed** this size.
Attempts to write above the limit result in an error.
---
## 5. Peripheral API (v0.1)
### 5.1 Logical Interface
The MEMCARD exposes a **simple single-blob API**:
```
mem.read_all() -> byte[]
mem.write_all(byte[])
mem.commit()
mem.clear()
mem.size() -> int
```
---
### 5.2 Operation Semantics
### `read_all()`
- Returns all persisted content
- If the card is empty, returns a zeroed buffer
- Cycle cost proportional to size
---
### `write_all(bytes)`
- Writes the buffer **to temporary memory**
- Does not persist immediately
- Fails if `bytes.length > mem.size()`
---
### `commit()`
- Persists data to the device
- **Mandatory** operation
- Simulates hardware flush
- May fail (e.g., I/O, simulated corruption)
---
### `clear()`
- Zeroes the card content
- Requires `commit()` to persist
---
### `size()`
- Returns total card capacity in bytes
---
## 6. Explicit Commit (Fundamental Rule)
PROMETEU **does not save automatically**.
Without `commit()`:
- data remains volatile
- can be lost upon exiting the game
- simulates abrupt hardware shutdown
👉 This teaches:
- data flushing
- atomicity
- risk of corruption
- real cost of persistence
---
## 7. Execution Cost (Cycles)
All MEMCARD operations have an explicit cost.
### Example (illustrative values)
| Operation | Cost |
| --- | --- |
| read_all | 1 cycle / 256 bytes |
| write_all | 1 cycle / 256 bytes |
| commit | fixed + proportional cost |
These costs appear:
- in the profiler
- in the frame timeline
- in the CAP report
---
## 8. `.mem` File Format
The MEMCARD file has a simple and robust format.
### 8.1 Header
| Field | Size |
| --- | --- |
| Magic (`PMEM`) | 4 bytes |
| Version | 1 byte |
| Cart ID | 8 bytes |
| Payload Size | 4 bytes |
| CRC32 | 4 bytes |
---
### 8.2 Payload
- Binary buffer defined by the game
- Fixed size
- Content interpreted only by the game
---
## 9. Integrity and Security
- CRC validates corruption
- Cart ID prevents using wrong save
- Version allows future format evolution
- Runtime can:
- warn of corruption
- allow card reset
---
## 10. Integration with the Editor / GUI
The main tool can provide a **Memory Card Manager**:
- create/reset card
- see size and usage
- import/export `.mem`
- visualize last commits
- associate cards with projects
None of these operations change the runtime.
---
## 11. Planned Evolutions (outside v0.1)
- Block API (`read_block`, `write_block`)
- multiple internal slots
- wear simulation
- save versioning
- optional encryption (educational)
---
## 12. Summary
The MEMCARD peripheral in PROMETEU:
- simulates real hardware
- forces design decisions
- teaches persistence correctly
- is simple to use
- is hard to abuse
- grows without breaking compatibility
< [Back](chapter-7.md) | [Summary](table-of-contents.md) | [Next](chapter-9.md) >
-308
View File
@@ -1,308 +0,0 @@
< [Back](chapter-8.md) | [Summary](table-of-contents.md) | [Next](chapter-10.md) >
# ⚡ **Events and Scheduling**
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**.
The goal is to preserve determinism while still allowing responsive and structured game logic.
---
## 1 Core Philosophy
Prometeu does **not use asynchronous callbacks** or preemptive interrupts for user code.
All external signals are:
* queued by the firmware
* delivered at deterministic points
* processed inside the main execution loop
Nothing executes “out of time”.
Nothing interrupts the program in the middle of an instruction.
Nothing occurs without a known cost.
This guarantees:
* deterministic behavior
* reproducible runs
* stable frame timing
---
## 2 Events
### 2.1 Definition
An **event** is a logical signal generated by the system or by internal runtime mechanisms.
Events:
* 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
---
### 2.2 Event Queue
The firmware maintains an **event queue**.
Properties:
* events are queued in order
* events are processed at frame boundaries
* event processing is deterministic
Events never:
* execute user code automatically
* interrupt instructions
* run outside the main loop
---
## 3 Frame Boundary (Sync Phase)
The primary synchronization point in Prometeu is the **frame boundary**, reached by the `FRAME_SYNC` instruction.
At this point:
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
---
## 4 System Events vs System Faults
Prometeu distinguishes between normal events and system faults.
### 4.1 Normal events
Examples:
* timer expired
* asset loaded
* frame boundary
These are delivered through the event queue.
### 4.2 System faults
Generated by exceptional conditions:
* invalid instruction
* memory violation
* handle misuse
* verifier failure
Result:
* VM execution stops
* state is preserved
* a diagnostic report is generated
System faults are not recoverable events.
---
## 5 Timers
Timers are modeled as **frame-based counters**.
Properties:
* measured in frames, not real time
* deterministic across runs
* generate events when they expire
Timers:
* do not execute code automatically
* produce queryable or queued events
Example:
```
if timer.expired(t1) {
// handle event
}
```
---
## 6 Coroutines and Cooperative Scheduling
Prometeu provides **coroutines** as the only form of concurrency.
Coroutines are:
* cooperative
* deterministic
* scheduled only at safe points
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
---
### 6.3 Coroutine operations
Typical coroutine instructions:
| Operation | Description |
| --------- | ----------------------------- |
| `spawn` | Create a coroutine |
| `yield` | Voluntarily suspend execution |
| `sleep` | Suspend for N frames |
`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: 120 cycles
Coroutine scheduling: 40 cycles
Frame sync: 80 cycles
```
Nothing is free.
---
## 9 Determinism and Reproducibility
Prometeu guarantees:
* same sequence of inputs and events → same behavior
* frame-based timers
* deterministic coroutine scheduling
This allows:
* reliable replays
* precise debugging
* fair certification
---
## 10 Best Practices
Prometeu encourages:
* treating events as data
* querying events explicitly
* structuring logic around frame steps
* using coroutines for asynchronous flows
Prometeu discourages:
* simulating asynchronous callbacks
* relying on hidden timing
* using events as implicit control flow
---
## 11 Conceptual Comparison
| 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 |
Prometeu teaches reactive system concepts without the unpredictability of real interrupts.
---
## 12 Summary
* 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) >
@@ -1,21 +0,0 @@
# Table of Contents
- [Chapter 1: Time Model and Cycles](chapter-1.md)
- [Chapter 2: PROMETEU VM Instruction Set](chapter-2.md)
- [Chapter 3: Memory: Stack, Heap, and Allocation](chapter-3.md)
- [Chapter 4: GFX Peripheral (Graphics System)](chapter-4.md)
- [Chapter 5: AUDIO Peripheral (Audio System)](chapter-5.md)
- [Chapter 6: INPUT Peripheral (Input System)](chapter-6.md)
- [Chapter 7: TOUCH Peripheral (Absolute Pointer Input System)](chapter-7.md)
- [Chapter 8: MEMCARD Peripheral (Save/Load System)](chapter-8.md)
- [Chapter 9: Events and Interrupts](chapter-9.md)
- [Chapter 10: Debug, Inspection, and Profiling](chapter-10.md)
- [Chapter 11: Portability Guarantees and Cross-Platform Execution](chapter-11.md)
- [Chapter 12: Firmware — PrometeuOS (POS) + PrometeuHub](chapter-12.md)
- [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)
-94
View File
@@ -1,94 +0,0 @@
# PBS Language Charter
Status: Draft v1
Applies to: Prometeu Base Script (PBS) language design
## 1. Mission
PBS exists to make 2D game development on Prometeu intuitive for beginners and reliable for experienced developers, without sacrificing deterministic runtime behavior.
## 2. Product Vision
PBS is a game-first language for a logical, evolving hardware platform.
It must feel fluid for frame-driven gameplay code while remaining strict enough to produce stable, verifiable bytecode for a closed VM target.
## 3. Target Users
- Beginner creators building their first playable 2D games.
- Intermediate developers shipping complete games with predictable behavior.
- Advanced developers who need explicit control of architecture and performance costs.
## 4. Core Principles
1. Game-first ergonomics: common gameplay patterns must be concise.
2. Determinism first: same program + same inputs/events => same behavior.
3. Explicit boundaries: host interaction, costs, and side effects must be visible.
4. Safe defaults: simple code paths should be hard to misuse.
5. Progressive power: advanced control is opt-in, not mandatory.
6. Compatibility discipline: language evolution must not silently break cartridges.
## 5. Scope of PBS v1
- Stable core syntax and grammar contract.
- Static and dynamic semantics for deterministic game code.
- Toolchain-managed host binding model aligned with syscall/capability model.
- Module visibility and import model suitable for multi-file game projects.
- Diagnostics and conformance requirements for interoperable implementations.
## 6. Out of Scope for PBS v1
- New VM opcodes as a language requirement.
- Non-deterministic async execution models.
- Mandatory custom allocator model replacing runtime GC.
- Advanced memory syntax (`alloc/borrow/mutate/...`) before explicit profile activation.
- User-authored declaration of canonical host primitive bindings outside reserved SDK/toolchain `declare host` surfaces.
## 7. Non-Negotiable Constraints
- Runtime and bytecode authority override language preferences.
- Closed VM compatibility is mandatory.
- `FRAME_SYNC`-based execution semantics are preserved.
- Host API usage remains capability-gated and versioned.
- Canonical host primitive bindings remain reserved to SDK/toolchain-controlled `declare host` surfaces.
## 8. Evolution Commitments
- Additive-first evolution for minor releases.
- Incompatible changes only in major lines with migration guidance.
- Canonical host primitive versioning by `(module, name, version)`.
- User-facing host-backed APIs evolve through SDK/stdlib surfaces, not direct user-authored host-binding declarations outside reserved `declare host` modules.
- Deterministic loader rejection when target contracts are unsupported.
## 9. Quality Bar
PBS is considered healthy only if:
- newcomers can produce a working 2D game loop quickly,
- generated behavior is deterministic and replayable,
- diagnostics are stable and actionable,
- performance risks are visible in tooling,
- older supported cartridges keep running across updates.
## 10. Required Spec Set Before Implementation
Before implementation starts, PBS must define at least:
1. Core Syntax Specification.
2. Static Semantics Specification.
3. Dynamic Semantics Specification.
4. Memory and Lifetime Specification.
5. Host ABI Binding Specification.
6. Module/Package Specification.
7. Diagnostics Specification.
8. IR and Lowering Specification.
9. Conformance Test Specification.
10. Compatibility and Evolution Policy.
## 11. Decision Rule
When trade-offs appear, decisions must prioritize, in order:
1. Determinism and compatibility.
2. Clarity for beginners.
3. Fluency for real game workflows.
4. Performance transparency for advanced users.
@@ -1,131 +0,0 @@
# PBS Memory and Lifetime Specification
Status: Draft v0 (Skeleton)
Applies to: runtime memory spaces, value representation classes, identity, aliasing, GC baseline, and host-memory boundaries in PBS core
## 1. Purpose
This document will define the authoritative PBS memory and lifetime model for v1.
Its purpose is to make the language's runtime storage model explicit enough that:
- implementations agree on which values are heap-backed,
- identity and aliasing are not left implicit,
- GC remains compatible with deterministic execution,
- the VM heap and host-owned memory boundary stay understandable,
- tooling can surface runtime-visible memory and allocation costs consistently.
## 2. Scope
This document is intended to define:
- runtime memory spaces relevant to PBS user semantics,
- value categories and their representation classes,
- identity, aliasing, and copy behavior,
- baseline GC guarantees and non-guarantees,
- host-memory boundary rules,
- memory-related safety invariants and remaining runtime failure boundaries,
- hooks that later diagnostics and tooling may rely on for cost reporting.
This document does not define:
- exact GC algorithm internals,
- general-purpose allocator APIs,
- future explicit lifetime syntax activation,
- final IR lowering details,
- subsystem-specific host resource APIs.
## 3. Authority and Precedence
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
3. `1. Language Charter.md`
4. `3. Core Syntax Specification.md`
5. `4. Static Semantics Specification.md`
6. `9. Dynamic Semantics Specification.md`
7. This document
If a rule here conflicts with higher authority, it is invalid.
## 4. Normative Inputs
This document depends on, at minimum:
- `1. Language Charter.md`
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `9. Dynamic Semantics Specification.md`
This document is expected to be closed using decisions from:
- `docs/agendas/Heap Model - Agenda.md`
- `docs/agendas/Memory and Lifetime - Agenda.md`
- `docs/agendas/Dynamic Semantics - Execution Model Agenda.md`
- `docs/agendas/Dynamic Semantics - Effect Surfaces Agenda.md`
## 5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- Struct values are heap-backed reference values in v1 core.
- Assigning a struct value copies the reference, not the underlying field storage.
- Service values are canonical module-owned singleton values in v1 core.
- Assigning a service value copies the same singleton identity and does not create a new instance.
- `declare const` values are compile-time constants rather than mutable runtime module storage.
- Advanced memory syntax such as `alloc`, `borrow`, `mutate`, `peek`, `take`, and `weak` is not active in PBS core v1.
## 6. Initial Section Targets
At minimum, the completed document should contain normative sections for:
1. runtime memory spaces,
2. value representation classes,
3. identity and aliasing,
4. copy and passing behavior,
5. GC guarantees and safepoint constraints,
6. host-memory boundary rules,
7. memory-related safety properties,
8. cost visibility hooks consumed by diagnostics/tooling.
## 7. A Ver
The following items remain to be closed in agenda discussion before this document can be considered complete.
### 7.1 `Memory and Lifetime - Agenda.md`
- Heap residency by value category beyond already-settled struct and service behavior.
- Which values have stable user-visible identity.
- Exact aliasing story for tuples, callbacks, collections, `optional`, and `result<E>`.
- Normative GC guarantees versus implementation-defined GC details.
- Representation and safety model of host-backed resources and handles.
### 7.2 `Heap Model - Agenda.md`
- Cross-cutting visibility of allocation, copy, retention, and host-boundary costs.
- Which memory facts are normative versus profiler-quality best effort.
- Migration policy and activation criteria for reserved lifetime keywords in future profiles.
### 7.3 `Dynamic Semantics - Execution Model Agenda.md` and `Dynamic Semantics - Effect Surfaces Agenda.md`
- Which constructs allocate or retain memory during ordinary execution.
- Which effect-bearing constructs may trap only because their subexpressions trap.
- Which safepoints are observable versus implementation detail.
## 8. Non-Goals
- Designing full pool, arena, or weak-reference libraries in this pass.
- Reintroducing mandatory user-authored lifetime syntax in core v1.
- Defining exact collector implementation strategy.
- Rewriting already-settled source syntax.
## 9. Exit Criteria
This document is ready to move beyond skeleton status only when:
1. every core value category has an explicit representation and aliasing story,
2. GC guarantees and non-guarantees are separated clearly,
3. the VM heap versus host-memory boundary is normatively described,
4. memory-related costs are specified well enough for diagnostics/tooling hooks,
5. the document no longer relies on unresolved `A Ver` items for ordinary v1 behavior.
@@ -1,133 +0,0 @@
# PBS Diagnostics Specification
Status: Draft v0 (Skeleton)
Applies to: deterministic diagnostics emitted by PBS-facing tooling across parsing, static analysis, manifest/import resolution, lowering boundaries, and related load-facing validation surfaces
## 1. Purpose
This document will define the PBS diagnostics contract.
Its purpose is to make diagnostics stable enough that:
- conforming tools report failures in the same places,
- users receive deterministic and actionable feedback,
- conformance can validate not only acceptance/rejection but also diagnostic class and location,
- frontend, manifest, and load-facing validation remain aligned.
## 2. Scope
This document is intended to define:
- diagnostic categories and phases,
- minimum metadata carried by diagnostics,
- stability expectations for source spans, file attribution, and phase attribution,
- the normative relationship between syntax/static diagnostics and later lowering/load diagnostics,
- which diagnostics are required versus implementation-defined enrichments,
- cost-visibility diagnostics or warnings once memory/effect decisions are closed.
This document does not define:
- the full runtime trap catalog,
- UI presentation or IDE styling,
- implementation-specific hint ranking,
- profiling output formats.
## 3. Authority and Precedence
Normative precedence:
1. `1. Language Charter.md`
2. `3. Core Syntax Specification.md`
3. `4. Static Semantics Specification.md`
4. `5. Manifest, Stdlib, and SDK Resolution Specification.md`
5. `6.2. Host ABI Binding and Loader Resolution Specification.md`
6. `7. Cartridge Manifest and Runtime Capabilities Specification.md`
7. `9. Dynamic Semantics Specification.md`
8. `10. Memory and Lifetime Specification.md`
9. `12. IR and Lowering Specification.md`
10. This document
If a diagnostic rule here contradicts a normative acceptance/rejection rule in a higher-precedence document, the higher-precedence document wins.
## 4. Normative Inputs
This document depends on, at minimum:
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `5. Manifest, Stdlib, and SDK Resolution Specification.md`
- `6.2. Host ABI Binding and Loader Resolution Specification.md`
- `7. Cartridge Manifest and Runtime Capabilities Specification.md`
This document will also depend on decisions closed in:
- `9. Dynamic Semantics Specification.md`
- `10. Memory and Lifetime Specification.md`
- the future backend agenda sequence tracked in `docs/agendas/`
## 5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- The syntax specification already enumerates minimum required syntax diagnostics.
- The static semantics specification already enumerates minimum required static diagnostics.
- Manifest/import resolution failures are required to be deterministic compile-time errors.
- Loader failures around malformed or unauthorized host usage are required to be deterministic.
- Stable source span metadata is required at the token level and must remain useful to later diagnostics.
## 6. Initial Section Targets
At minimum, the completed document should contain normative sections for:
1. diagnostic phases,
2. required diagnostic metadata,
3. span and file attribution,
4. syntax-diagnostic contract,
5. static-diagnostic contract,
6. manifest/import-resolution diagnostics,
7. lowering and host-binding diagnostics,
8. load-facing and capability diagnostics,
9. cost-visibility diagnostics and warnings.
## 7. A Ver
The following items remain to be closed before this document can be considered complete.
### 7.1 Depends on `9. Dynamic Semantics Specification.md`
- Which runtime-observable trap categories need source-facing compile-time or conformance hooks.
- Which constructs require special diagnostics for abrupt completion, propagation, or effect misuse beyond what static semantics already lists.
### 7.2 Depends on `10. Memory and Lifetime Specification.md`
- Which allocations, copies, escapes, and host-boundary crossings must surface as normative diagnostics or warnings.
- Which cost facts are mandatory versus implementation-defined enrichment.
### 7.3 Depends on the future backend agenda sequence tracked in `docs/agendas/`
- Whether diagnostic stability includes IR/lowering phase names, artifact offsets, or source maps.
- How host-binding lowering failures are surfaced back to source locations.
- Whether verifier/load diagnostics are part of the PBS diagnostics contract directly or only through artifact-facing tooling.
### 7.4 Still to decide inside this document
- Whether diagnostic codes are mandatory in v1.
- Which portions of human-readable wording are normative versus illustrative.
- Whether notes/help text are required, optional, or outside conformance.
- Exact cross-file diagnostic expectations for module/barrel/import failures.
## 8. Non-Goals
- Mandating one UI or IDE presentation style.
- Freezing a localization strategy in this pass.
- Turning every optimization hint into a normative diagnostic.
- Replacing the acceptance/rejection rules already defined elsewhere.
## 9. Exit Criteria
This document is ready to move beyond skeleton status only when:
1. every required rejection in the current spec set is mapped to a diagnostic phase,
2. diagnostic metadata and attribution rules are explicit enough for conformance,
3. cost-visibility expectations are aligned with memory/effect specs,
4. the document no longer relies on unresolved backend and runtime-facing `A Ver` items for v1 tooling behavior.
@@ -1,136 +0,0 @@
# PBS IR and Lowering Specification
Status: Draft v0 (Skeleton)
Applies to: lowering of bound PBS programs into internal compiler IR and runtime-facing artifacts
## 1. Purpose
This document will define the normative lowering contract from PBS source semantics to implementation artifacts.
Its purpose is to make backend-facing behavior explicit enough that:
- different compilers lower the same bound program compatibly,
- host-binding emission does not drift from frontend resolution,
- builtin and intrinsic lowering does not drift from VM-owned metadata,
- later verifier and loader behavior can rely on stable artifact expectations,
- conformance can test more than parser and binder behavior.
## 2. Scope
This document is intended to define:
- the minimum semantic obligations of the compiler after parsing, binding, and type checking,
- the role of internal IR as an implementation stage,
- what semantic facts lowering must preserve,
- lowering of control flow, calls, callbacks, services, contracts, constants, and host-backed calls,
- lowering of builtin projections, builtin constants, and intrinsic member calls,
- artifact-facing requirements that must hold before loader/verifier consumption.
This document does not define:
- the full PBX binary layout,
- optimizer heuristics or performance tuning strategy,
- the exact in-memory data structures of one compiler implementation,
- runtime GC algorithm internals.
## 3. Authority and Precedence
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
3. `3. Core Syntax Specification.md`
4. `4. Static Semantics Specification.md`
5. `5. Manifest, Stdlib, and SDK Resolution Specification.md`
6. `6. VM-owned vs Host-backed.md`
7. `6.1. Intrinsics and Builtin Types Specification.md`
8. `6.2. Host ABI Binding and Loader Resolution Specification.md`
9. `9. Dynamic Semantics Specification.md`
10. `10. Memory and Lifetime Specification.md`
11. This document
If a lowering rule here contradicts a higher-precedence semantic rule, the higher-precedence rule wins.
## 4. Normative Inputs
This document depends on, at minimum:
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `5. Manifest, Stdlib, and SDK Resolution Specification.md`
- `6. VM-owned vs Host-backed.md`
- `6.1. Intrinsics and Builtin Types Specification.md`
- `6.2. Host ABI Binding and Loader Resolution Specification.md`
- `9. Dynamic Semantics Specification.md`
- `10. Memory and Lifetime Specification.md`
This document is expected to be closed using a future backend agenda sequence tracked in `docs/agendas/`.
## 5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- The compiler consumes reserved `Host` metadata while resolving host-backed SDK members.
- The compiler consumes reserved `BuiltinType`, `BuiltinConst`, `IntrinsicCall`, and `Slot` metadata while resolving builtin shells.
- The compiler emits canonical host-binding declarations into the PBX `SYSC` table.
- The compiler emits host-backed callsites in pre-load form as `HOSTCALL <sysc_index>`.
- `SYSC` entries are deduplicated by canonical identity and ordered by first occurrence.
- The loader, not the compiler, resolves canonical host bindings to final numeric syscall identifiers.
- Builtin projection lowering remains VM-owned and does not emit host-binding metadata.
- Builtin constants lower through VM-owned materialization rather than through ordinary compile-time constant evaluation.
- Builtin intrinsic member calls lower through a VM-owned intrinsic path rather than through `SYSC`, `HOSTCALL`, or `SYSCALL`.
- Stdlib interface modules are compile-time-only and do not emit executable bytecode by themselves.
## 6. Initial Section Targets
At minimum, the completed document should contain normative sections for:
1. lowering preconditions,
2. semantic obligations preserved by IR,
3. lowering of expressions and control flow,
4. lowering of callable categories,
5. lowering of `optional` and `result<E>` constructs,
6. lowering of callbacks, services, and contracts,
7. lowering of builtin projections, builtin constants, and builtin intrinsic calls,
8. host-binding emission,
9. artifact invariants required before verifier/loader stages.
## 7. A Ver
The following items remain to be closed before this document can be considered complete.
### 7.1 Depends on `9. Dynamic Semantics Specification.md`
- Which evaluation-order guarantees must be preserved explicitly in lowering.
- Which traps, abrupt completions, and propagation paths require dedicated lowered forms.
- Whether callback formation and contract dispatch need dedicated runtime artifacts or only implementation-defined IR shapes.
### 7.2 Depends on `10. Memory and Lifetime Specification.md`
- Which lowered operations allocate, alias, retain, or cross the host-memory boundary.
- Which runtime storage/identity facts IR must preserve explicitly versus infer later.
### 7.3 Depends on the future backend agenda sequence tracked in `docs/agendas/`
- Whether one canonical IR is normative or only the preserved semantic obligations are normative.
- The exact mapping from bound PBS constructs to PBX/bytecode-facing artifacts beyond already-settled host-binding and intrinsic behavior.
- Lowering strategy for services, contracts, callbacks, tuples, and result propagation.
- Whether declaration-based intrinsic preload forms such as `INTRCALL` are part of v1 lowering or whether compilers should emit final `INTRINSIC <id>` directly for a selected VM line.
- Which artifact invariants belong here versus a future dedicated PBX/bytecode mapping document.
## 8. Non-Goals
- Freezing one optimizer design.
- Requiring one compiler implementation architecture.
- Repeating the full bytecode ISA specification.
- Defining loader-side patching internals already owned elsewhere.
## 9. Exit Criteria
This document is ready to move beyond skeleton status only when:
1. every semantically distinct core construct has an explicit lowering story,
2. the boundary between source semantics, compiler IR, and emitted artifacts is clear,
3. host-binding emission is fully aligned with the Host ABI spec,
4. builtin and intrinsic lowering is fully aligned with the VM-owned builtin spec,
5. the document no longer relies on unresolved backend `A Ver` items for ordinary v1 lowering behavior.
@@ -1,138 +0,0 @@
# PBS Conformance Test Specification
Status: Draft v0 (Skeleton)
Applies to: conformance obligations, test categories, and acceptance criteria for PBS implementations
## 1. Purpose
This document will define the PBS conformance testing contract.
Its purpose is to make the specification operational by defining:
- what an implementation must demonstrate to claim conformance,
- which parts of the spec require positive versus negative tests,
- how deterministic diagnostics and runtime behavior are validated,
- how compatibility and version claims are checked.
## 2. Scope
This document is intended to define:
- conformance levels or profiles, if any,
- required test categories,
- expectations for syntax, static, manifest, lowering, loader, and runtime tests,
- diagnostic-conformance expectations,
- artifact and runtime fixtures needed for host-binding and capability-gating tests,
- compatibility-matrix conformance hooks.
This document does not define:
- one specific test runner implementation,
- CI policy for one repository,
- benchmark or performance certification,
- product release governance process.
## 3. Authority and Precedence
Normative precedence:
1. `1. Language Charter.md`
2. `2. Governance and Versioning.md`
3. `3. Core Syntax Specification.md`
4. `4. Static Semantics Specification.md`
5. `5. Manifest, Stdlib, and SDK Resolution Specification.md`
6. `6.2. Host ABI Binding and Loader Resolution Specification.md`
7. `7. Cartridge Manifest and Runtime Capabilities Specification.md`
8. `9. Dynamic Semantics Specification.md`
9. `10. Memory and Lifetime Specification.md`
10. `11. Diagnostics Specification.md`
11. `12. IR and Lowering Specification.md`
12. This document
This document must not weaken a normative requirement imposed by higher-precedence specs.
## 4. Normative Inputs
This document depends on, at minimum, the full active PBS v1 spec set.
In the current phase, it should be drafted against:
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `5. Manifest, Stdlib, and SDK Resolution Specification.md`
- `6.2. Host ABI Binding and Loader Resolution Specification.md`
- `7. Cartridge Manifest and Runtime Capabilities Specification.md`
It will require closure of:
- `9. Dynamic Semantics Specification.md`
- `10. Memory and Lifetime Specification.md`
- `11. Diagnostics Specification.md`
- `12. IR and Lowering Specification.md`
## 5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- The parser must behave deterministically.
- Syntax and static semantics already enumerate minimum required rejection cases.
- Import/manifest failures are required to be deterministic.
- Loader failures for malformed or unauthorized host usage are required to be deterministic.
- Governance requires conformance updates before release.
- Compatibility claims must be reflected in a published compatibility matrix.
## 6. Initial Section Targets
At minimum, the completed document should contain normative sections for:
1. scope of conformance,
2. implementation claims and version domains,
3. required positive parsing/binding/type-checking tests,
4. required negative syntax/static tests,
5. manifest/import-resolution tests,
6. dynamic-semantics runtime tests,
7. host-binding and capability-gating tests,
8. diagnostics-conformance tests,
9. compatibility and regression test expectations.
## 7. A Ver
The following items remain to be closed before this document can be considered complete.
### 7.1 Depends on `9. Dynamic Semantics Specification.md` and `10. Memory and Lifetime Specification.md`
- Exact runtime-oracle model for observable evaluation order, traps, and effect behavior.
- Which memory/aliasing facts must be tested directly versus only through diagnostics/tooling hooks.
### 7.2 Depends on `11. Diagnostics Specification.md`
- Whether conformance checks diagnostic codes, spans, categories, wording classes, or only rejection phase and location.
- Which warnings or cost diagnostics are in conformance scope.
### 7.3 Depends on `12. IR and Lowering Specification.md`
- Whether artifact-level conformance is required in addition to source-level conformance.
- Which emitted host-binding and lowering invariants require golden tests.
### 7.4 Still to decide inside this document
- Whether PBS v1 has one conformance level or staged claims such as frontend-only versus full toolchain.
- Fixture strategy for stdlib environments, host registries, and capability-grant scenarios.
- How compatibility-matrix claims are validated across language/profile/stdlib domains.
## 8. Non-Goals
- Replacing the normative specs with tests as the primary authority.
- Forcing one repository layout or one test harness.
- Treating performance benchmarking as language conformance.
- Inventing new language rules through test-only precedent.
## 9. Exit Criteria
This document is ready to move beyond skeleton status only when:
1. every active PBS v1 spec has a corresponding conformance surface,
2. positive and negative obligations are clearly separated,
3. diagnostics and runtime behavior have explicit oracle expectations,
4. compatibility and version claims can be tested rather than asserted informally,
5. the document no longer relies on unresolved `A Ver` items for the intended conformance level.
@@ -1,169 +0,0 @@
# PBS Name Resolution and Module Linking Specification
Status: Draft v0 (Skeleton)
Applies to: scope formation, name lookup, imports, exports, barrel visibility, cross-module resolution, and semantic linking of PBS programs
## 1. Purpose
This document will define the normative name-resolution and semantic-linking model for PBS.
## 2. Scope
This document is intended to define:
- scope formation and lookup order,
- namespace separation and collision rules,
- import and export resolution,
- barrel-mediated visibility and module linking,
- cross-file and cross-module symbol resolution,
- resolution of reserved stdlib shells for host-backed and VM-owned surfaces,
- linkage-time rejection conditions before lowering.
This document does not define:
- runtime execution behavior,
- optimizer or backend internals,
- full PBX binary linking.
## 3. Authority and Precedence
Normative precedence:
1. `3. Core Syntax Specification.md`
2. `4. Static Semantics Specification.md`
3. `5. Manifest, Stdlib, and SDK Resolution Specification.md`
4. `6. VM-owned vs Host-backed.md`
5. `6.1. Intrinsics and Builtin Types Specification.md`
6. `18. Standard Library Surface Specification.md`
7. This document
If a rule here conflicts with higher-precedence specs, it is invalid.
## 4. Normative Inputs
This document depends on, at minimum:
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `5. Manifest, Stdlib, and SDK Resolution Specification.md`
- `6. VM-owned vs Host-backed.md`
- `6.1. Intrinsics and Builtin Types Specification.md`
- `8. Stdlib Environment Packaging and Loading Specification.md`
- `18. Standard Library Surface Specification.md`
## 5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- PBS has distinct type, value, callable, and host-owner namespaces.
- `mod.barrel` is the single source of module visibility.
- Imports target modules, not files.
- Reserved stdlib project spaces are resolved only from the selected stdlib environment.
- Only `pub` symbols may be imported from another module.
- Reserved stdlib/interface modules may expose compile-time-only shells for both host-backed and VM-owned surfaces.
- Source-visible builtin names are resolved through imported builtin shell declarations rather than by hardcoded source spelling alone.
- Canonical builtin identity and canonical intrinsic identity are governed by builtin metadata rather than by the imported PBS-visible declaration name alone.
## 6. Initial Section Targets
At minimum, the completed document should contain normative sections for:
1. scope construction,
2. lookup order by namespace,
3. import and alias resolution,
4. barrel export matching and linking,
5. reserved stdlib shell resolution for builtin and host-backed surfaces,
6. duplicate and shadowing rules,
7. cross-module resolution failures.
## 7. A Ver
The following items remain to be closed in future agenda discussion.
- Exact lookup order across local bindings, top-level declarations, imports, and reserved intrinsic surfaces.
- Whether shadowing rules differ by namespace or declaration kind.
- Whether semantic linking is fully part of static semantics or split into a distinct phase contract.
- Exact rejection model for ambiguous cross-module overload visibility and barrel-linked callable sets.
- Whether stdlib/interface-module linking imposes extra restrictions beyond ordinary modules.
- Whether builtin shell declarations may be synthesized by the toolchain in addition to being provided by stdlib modules.
## 8. Non-Goals
- Reopening the already-settled import surface syntax.
- Defining runtime loader behavior.
- Freezing one compiler symbol-table implementation.
## 9. Exit Criteria
This document is ready to move beyond skeleton status only when:
1. name lookup is deterministic across all relevant scopes,
2. barrel and module linking behavior is explicit,
3. reserved stdlib shell resolution is explicit for host-backed and VM-owned surfaces,
4. cross-module ambiguity and failure cases are normatively defined,
5. the document no longer relies on unresolved `A Ver` items for ordinary v1 resolution behavior.
## 10. Reserved Stdlib Shell Resolution
Reserved stdlib modules may expose compile-time-only declarations that do not
behave like ordinary user-authored implementation bodies.
Rules:
- `declare host` surfaces exported from reserved stdlib modules resolve in the host-owner namespace.
- `declare builtin type` surfaces exported from reserved stdlib modules resolve in the type namespace.
- builtin constants exported from reserved stdlib modules resolve in the value namespace.
- builtin intrinsic methods are not imported as free functions; they are resolved through the imported builtin type declaration of the receiver type.
- canonical host identity is not derived from the imported host owner spelling,
- and canonical builtin/intrinsic identity is not derived solely from the imported builtin type spelling.
Example:
- importing `Vec2` from `@core:math` may introduce the PBS-visible type name `Vec2`,
- while the declaration's metadata may still lower that type to canonical builtin identity `("vec2", 1)`.
## 11. Import and Barrel Rules for Builtin Shells
Builtin shells follow ordinary module visibility rules at the source level and
special metadata rules at lowering time.
Rules:
- a builtin type, builtin constant, or host owner may be imported only if it is exported through the target module's `mod.barrel`,
- aliasing an imported builtin type changes only the source-visible local name, not the canonical builtin identity declared by metadata,
- aliasing an imported builtin constant changes only the local binding name, not the canonical builtin constant identity declared by metadata,
- aliasing an imported host owner changes only the source-visible local name, not the canonical host identity declared by `Host(...)`,
- barrel matching for builtin declarations is declaration-based rather than executable-body based,
- and resolution must complete before lowering begins.
## 12. Lookup Order for Builtin and Intrinsic Surfaces
Lookup remains namespace-based.
Rules:
- type-position lookup considers visible builtin type declarations alongside other visible type declarations,
- value-position lookup considers visible builtin constants alongside other visible values,
- callable lookup does not treat builtin intrinsic members as top-level callable declarations,
- member lookup on a builtin-typed receiver considers builtin projection fields first as field-like surfaces of that builtin declaration,
- method lookup on a builtin-typed receiver considers builtin intrinsic member signatures declared by that builtin shell,
- and host-owner lookup remains separate from builtin type lookup.
This preserves the distinction between:
- imported builtin type shells,
- imported host owners,
- and compiler-recognized intrinsic method surfaces on existing core forms such as `optional` and enums.
## 13. Deterministic Resolution Failures
At minimum, a conforming implementation must reject:
1. import of a non-exported builtin type shell,
2. import of a non-exported builtin constant shell,
3. import of a non-exported host owner shell,
4. ambiguous cross-module visibility of builtin declarations after barrel resolution,
5. duplicate visible builtin type declarations that claim the same canonical builtin identity in one resolved environment,
6. duplicate visible builtin constants that claim the same canonical builtin constant identity in one resolved environment,
7. member lookup on a builtin receiver where the imported builtin shell does not declare the requested field or intrinsic member,
8. any resolution path that attempts to derive host or builtin canonical identity from alias spelling alone.
@@ -1,92 +0,0 @@
# PBS Bytecode and PBX Mapping Specification
Status: Draft v0 (Skeleton)
Applies to: mapping from lowered PBS programs into PBX sections, bytecode-facing artifacts, and related source-to-artifact invariants
## 1. Purpose
This document will define the normative mapping between lowered PBS semantics and emitted PBX/bytecode-facing artifacts.
## 2. Scope
This document is intended to define:
- artifact-level obligations after lowering,
- mapping of semantic constructs into PBX-visible structures,
- source-to-artifact invariants required by verifier and loader stages,
- interaction points with host-binding metadata such as `SYSC`,
- interaction points with VM-owned builtin and intrinsic metadata.
This document does not define:
- the full bytecode ISA,
- UI/tooling presentation,
- one compiler's internal IR representation.
## 3. Authority and Precedence
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
3. `6.1. Intrinsics and Builtin Types Specification.md`
4. `6.2. Host ABI Binding and Loader Resolution Specification.md`
5. `12. IR and Lowering Specification.md`
6. This document
If a rule here conflicts with higher-precedence authorities, it is invalid.
## 4. Normative Inputs
This document depends on, at minimum:
- `6.1. Intrinsics and Builtin Types Specification.md`
- `6.2. Host ABI Binding and Loader Resolution Specification.md`
- `12. IR and Lowering Specification.md`
## 5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- The compiler emits host-binding declarations into PBX `SYSC`.
- Host-backed callsites are emitted in pre-load form as `HOSTCALL <sysc_index>`.
- `SYSC` entries are deduplicated by canonical identity and ordered by first occurrence.
- The loader resolves host bindings and rewrites `HOSTCALL` into `SYSCALL`.
- VM-owned builtin projections, builtin constants, and intrinsic callsites do not emit host-binding metadata.
- VM-owned intrinsic artifacts are distinct from `SYSC`, `HOSTCALL`, and `SYSCALL`.
## 6. Initial Section Targets
At minimum, the completed document should contain normative sections for:
1. artifact mapping goals,
2. section-level invariants,
3. callsite and control-flow mapping invariants,
4. metadata mapping obligations,
5. intrinsic and builtin artifact obligations,
6. source-attribution hooks for diagnostics/conformance.
## 7. A Ver
The following items remain to be closed in future agenda discussion.
- Which PBX sections beyond `SYSC` are part of the PBS-facing contract.
- Whether a distinct intrinsic declaration section is part of the PBS-facing contract in v1.
- Which source-level constructs require dedicated artifact patterns versus implementation freedom.
- How much of artifact ordering, numbering, and layout is normative at PBS level versus owned purely by PBX authority.
- Whether compilers should emit final `INTRINSIC <id>` directly for a selected VM line or may emit a declaration-based preload form such as `INTRCALL <decl_index>`.
- Whether a separate debug/source-map surface is part of v1.
## 8. Non-Goals
- Repeating the full PBX or ISA documentation.
- Mandating one binary-emitter implementation strategy.
- Defining loader patching internals already owned elsewhere.
## 9. Exit Criteria
This document is ready to move beyond skeleton status only when:
1. the PBS-to-artifact boundary is explicit,
2. artifact-level invariants needed by verifier and loader are normative,
3. the document no longer relies on unresolved `A Ver` items for ordinary v1 artifact mapping behavior.
@@ -1,91 +0,0 @@
# PBS Runtime Execution and Initialization Specification
Status: Draft v0 (Skeleton)
Applies to: runtime startup, entry behavior, module/service initialization, and execution lifecycle of PBS programs after successful load
## 1. Purpose
This document will define the runtime execution and initialization contract for PBS programs.
## 2. Scope
This document is intended to define:
- entry and startup behavior,
- initialization ordering relevant to PBS-visible semantics,
- lifecycle of module-owned and service-owned runtime state,
- execution boundaries before, during, and after frame-driven program operation,
- runtime assumptions that are neither purely dynamic semantics nor purely loader behavior.
This document does not define:
- loader-side host resolution,
- full packaging format,
- scheduler models outside v1 execution assumptions.
## 3. Authority and Precedence
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. `1. Language Charter.md`
3. `6.2. Host ABI Binding and Loader Resolution Specification.md`
4. `9. Dynamic Semantics Specification.md`
5. `10. Memory and Lifetime Specification.md`
6. This document
If a rule here conflicts with higher-precedence authorities, it is invalid.
## 4. Normative Inputs
This document depends on, at minimum:
- `1. Language Charter.md`
- `6.2. Host ABI Binding and Loader Resolution Specification.md`
- `7. Cartridge Manifest and Runtime Capabilities Specification.md`
- `9. Dynamic Semantics Specification.md`
- `10. Memory and Lifetime Specification.md`
## 5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- `FRAME_SYNC`-based execution semantics are preserved.
- Loader-side host binding resolution and capability gating happen before program execution begins.
- Service values are canonical module-owned singleton values.
- Top-level executable statements are forbidden in PBS source modules.
## 6. Initial Section Targets
At minimum, the completed document should contain normative sections for:
1. execution entry assumptions,
2. initialization ordering,
3. service singleton runtime lifecycle,
4. runtime frame and step boundaries,
5. failure and non-start conditions.
## 7. A Ver
The following items remain to be closed in future agenda discussion.
- Exact runtime entry contract between loaded artifact and PBS-visible program behavior.
- Whether module initialization exists as a distinct semantic phase in v1 beyond load success.
- When service singleton state becomes initialized and observable.
- Which runtime lifecycle boundaries are observable to user code versus VM-internal.
- Whether shutdown/finalization behavior has any PBS-visible contract in v1.
## 8. Non-Goals
- Defining OS/process lifecycle outside Prometeu runtime authority.
- Reopening the ban on top-level executable statements.
- Designing a future async runtime.
## 9. Exit Criteria
This document is ready to move beyond skeleton status only when:
1. runtime startup and initialization order are normatively described,
2. service and module runtime lifecycle assumptions are explicit,
3. execution lifecycle boundaries are aligned with dynamic semantics and runtime authority,
4. the document no longer relies on unresolved `A Ver` items for ordinary v1 runtime startup behavior.
@@ -1,90 +0,0 @@
# PBS Compatibility and Evolution Policy
Status: Draft v0 (Skeleton)
Applies to: compatibility commitments, migration boundaries, deprecation discipline, and evolution constraints across PBS language and related domains
## 1. Purpose
This document will define the normative compatibility and evolution policy for PBS.
## 2. Scope
This document is intended to define:
- compatibility promises across language, profile, stdlib, and artifact domains,
- migration boundaries for additive versus incompatible changes,
- deprecation and removal policy details,
- behavioral versus binary compatibility expectations,
- obligations when publishing changes that affect older cartridges or projects.
This document does not define:
- one repository's release workflow,
- one implementation's branching strategy,
- detailed changelog formatting.
## 3. Authority and Precedence
Normative precedence:
1. `1. Language Charter.md`
2. `2. Governance and Versioning.md`
3. Runtime and bytecode authority where applicable
4. This document
If a rule here conflicts with higher-precedence authorities, it is invalid.
## 4. Normative Inputs
This document depends on, at minimum:
- `1. Language Charter.md`
- `2. Governance and Versioning.md`
- `6.2. Host ABI Binding and Loader Resolution Specification.md`
- `7. Cartridge Manifest and Runtime Capabilities Specification.md`
## 5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- Additive-first evolution is preferred for minor releases.
- Incompatible changes belong only in major lines with migration guidance.
- Canonical host primitive versioning uses `(module, name, version)`.
- Toolchains must reject unsupported targets deterministically.
- Older supported cartridges are expected to keep running across updates.
## 6. Initial Section Targets
At minimum, the completed document should contain normative sections for:
1. compatibility domains,
2. behavioral versus binary compatibility,
3. deprecation windows,
4. migration obligations,
5. compatibility-matrix expectations,
6. artifact and runtime compatibility boundaries.
## 7. A Ver
The following items remain to be closed in future agenda discussion.
- Exact compatibility window by domain.
- Whether PBX/binary compatibility has an independent policy track from source-level compatibility.
- How stdlib-line compatibility interacts with dependency projects over time.
- Which changes require migration tooling versus documentation-only migration notes.
- Whether frontend-only phased implementation claims need distinct compatibility labels.
## 8. Non-Goals
- Replacing governance with ad hoc decisions.
- Defining one product release calendar.
- Freezing every editorial clarification as a compatibility event.
## 9. Exit Criteria
This document is ready to move beyond skeleton status only when:
1. compatibility commitments are explicit by domain,
2. deprecation and migration duties are normatively described,
3. source, stdlib, artifact, and runtime compatibility boundaries are separated clearly,
4. the document no longer relies on unresolved `A Ver` items for ordinary v1 compatibility claims.
@@ -1,185 +0,0 @@
# PBS Standard Library Surface Specification
Status: Draft v0 (Skeleton)
Applies to: normative stdlib-facing API surface, reserved stdlib project spaces, and versioned standard-library contracts exposed to PBS programs
## 1. Purpose
This document will define the normative user-facing standard-library surface for PBS.
## 2. Scope
This document is intended to define:
- what counts as part of the PBS stdlib contract,
- how stdlib modules are grouped and versioned,
- which APIs are normative versus implementation-private,
- how VM-owned builtin shells are exposed to user code,
- how reserved stdlib project spaces expose user-facing surfaces over host-backed capabilities.
This document does not define:
- one physical packaging layout,
- registry/publication mechanics,
- host loader behavior,
- implementation-private helper modules.
## 3. Authority and Precedence
Normative precedence:
1. `5. Manifest, Stdlib, and SDK Resolution Specification.md`
2. `8. Stdlib Environment Packaging and Loading Specification.md`
3. `6. VM-owned vs Host-backed.md`
4. `6.1. Intrinsics and Builtin Types Specification.md`
5. `6.2. Host ABI Binding and Loader Resolution Specification.md`
6. This document
If a rule here conflicts with higher-precedence specs, it is invalid.
## 4. Normative Inputs
This document depends on, at minimum:
- `5. Manifest, Stdlib, and SDK Resolution Specification.md`
- `6. VM-owned vs Host-backed.md`
- `6.1. Intrinsics and Builtin Types Specification.md`
- `6.2. Host ABI Binding and Loader Resolution Specification.md`
- `8. Stdlib Environment Packaging and Loading Specification.md`
## 5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- Reserved stdlib project spaces include `@sdk:*` and `@core:*`.
- Stdlib interface modules are compile-time-only and loaded as PBS-like modules.
- User code must import stdlib modules explicitly.
- Canonical host identity comes from reserved host-binding metadata, not from source owner spelling.
- VM-owned builtin type, builtin constant, and intrinsic surfaces may be exposed through reserved stdlib shells without transferring semantic ownership away from the VM.
## 6. Initial Section Targets
At minimum, the completed document should contain normative sections for:
1. stdlib contract boundaries,
2. reserved stdlib project spaces and module families,
3. normative versus non-normative API surfaces,
4. VM-owned builtin shells exposed to user code,
5. host-backed SDK surfaces exposed to user code,
6. versioning and deprecation expectations for stdlib APIs.
## 7. A Ver
The following items remain to be closed in future agenda discussion.
- Which stdlib modules are mandatory in each active stdlib line.
- Which APIs are part of the normative core teaching surface versus optional library growth.
- Whether `@core:*` is specified as language-adjacent utility surface or as ordinary stdlib contract.
- How stdlib API evolution is documented and conformance-tested.
- Whether some interface modules remain toolchain-private and outside user-facing stdlib surface.
- Whether builtin shells may appear in `@sdk:*` as well as `@core:*`, or whether `@sdk:*` should remain host-facing only by policy.
## 8. Non-Goals
- Replacing the resolution/packaging specs.
- Defining all future libraries in one pass.
- Hardcoding one distribution format.
## 9. Exit Criteria
This document is ready to move beyond skeleton status only when:
1. the normative user-facing stdlib surface is explicitly bounded,
2. reserved project-space API responsibilities are clear,
3. VM-owned and host-backed stdlib surfaces are explicitly separated,
4. stdlib versioning and deprecation expectations are aligned with compatibility policy,
5. the document no longer relies on unresolved `A Ver` items for ordinary v1 stdlib contract claims.
## 10. Reserved Project-Space Responsibilities
The current stdlib direction distinguishes two user-facing reserved spaces.
### 10.1 `@core:*`
`@core:*` is the preferred surface for VM-owned declarations that belong to the
language-adjacent semantic platform.
Examples:
- builtin type shells,
- builtin constants,
- and other VM-owned helper declarations that are not host capability surfaces.
### 10.2 `@sdk:*`
`@sdk:*` is the preferred surface for host-backed capability-facing APIs.
Examples:
- `declare host` surfaces,
- capability-facing wrappers over host services,
- and domain SDK modules whose execution meaning ultimately depends on host-backed operations.
Rules:
- source packaging location is part of the stdlib contract surface,
- but ownership remains governed by the VM-owned vs host-backed classification,
- and placing a builtin shell in stdlib does not make it host-backed.
## 11. Builtin Shell Surfaces
Reserved stdlib modules may expose builtin declarations as compile-time-only
shells.
Rules:
- stdlib builtin shells may expose `declare builtin type` declarations,
- stdlib builtin shells may expose reserved `declare const` declarations carrying `BuiltinConst(...)`,
- stdlib builtin shells may expose builtin methods carrying `IntrinsicCall(...)`,
- these shells exist for import, name resolution, type checking, and lowering,
- and these shells do not provide executable PBS bodies for builtin behavior.
Stdlib is therefore the delivery surface, not the semantic owner.
## 12. Host-backed SDK Surfaces
Reserved stdlib modules may expose host-backed declarations as compile-time-only
shells.
Rules:
- host-backed stdlib surfaces use `declare host`,
- host-backed method signatures carry `Host(...)`,
- user code may import those host owners through ordinary stdlib module imports,
- and lowering continues through canonical host identity, `SYSC`, `HOSTCALL`, loader resolution, and final `SYSCALL`.
## 13. Stdlib Contract Expectations for Builtin MVP
For the current builtin MVP, stdlib should be able to expose at least:
1. a builtin type shell for `Color`,
2. a builtin type shell for `Vec2`,
3. a builtin type shell for `Pixel`,
4. a builtin constant shell for `vec2.zero`,
5. and any associated documentation-level or teaching-level module organization needed to make those surfaces discoverable.
Illustrative example:
```pbs
import { Vec2, ZERO } from @core:math;
```
The imported names are source-visible conveniences.
Their canonical runtime-facing identities still come from builtin metadata such
as `BuiltinType(name="vec2", version=1)` and
`BuiltinConst(target="vec2", name="zero", version=1)`.
## 14. Deterministic Stdlib Surface Failures
At minimum, a conforming implementation must reject:
1. a stdlib builtin shell that attempts to use host-binding metadata for VM-owned intrinsic behavior,
2. a stdlib host shell that attempts to use builtin metadata in place of host-binding metadata,
3. a user-facing stdlib module that exports executable PBS bodies for builtin semantics,
4. a stdlib line that exposes conflicting canonical builtin identities through the same resolved environment,
5. a stdlib line that exposes conflicting canonical host identities through the same resolved environment.
@@ -1,88 +0,0 @@
# PBS Verification and Safety Checks Specification
Status: Draft v0 (Skeleton)
Applies to: verifier-facing safety obligations, artifact validation boundaries, and the division of safety checks across compiler, loader, verifier, and runtime
## 1. Purpose
This document will define the verification and safety-check model relevant to PBS-produced artifacts.
## 2. Scope
This document is intended to define:
- which safety obligations are enforced before runtime execution,
- the division of responsibility across compiler, loader, verifier, and runtime,
- verifier-facing assumptions about already-lowered artifacts,
- safety properties that must hold for conforming PBS-produced images.
This document does not define:
- full runtime trap semantics,
- source-language typing rules already owned elsewhere,
- one verifier implementation architecture.
## 3. Authority and Precedence
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
3. `6.2. Host ABI Binding and Loader Resolution Specification.md`
4. `12. IR and Lowering Specification.md`
5. `15. Bytecode and PBX Mapping Specification.md`
6. This document
If a rule here conflicts with higher-precedence authorities, it is invalid.
## 4. Normative Inputs
This document depends on, at minimum:
- `6.2. Host ABI Binding and Loader Resolution Specification.md`
- `12. IR and Lowering Specification.md`
- `15. Bytecode and PBX Mapping Specification.md`
## 5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- Loader-side ABI validation is mandatory.
- Capability gating is mandatory during load.
- The verifier runs after loader patching on the final numeric executable image.
- Loader and verifier validate different layers of the contract.
## 6. Initial Section Targets
At minimum, the completed document should contain normative sections for:
1. safety-check phase boundaries,
2. compiler-emitted safety assumptions,
3. loader-side safety checks,
4. verifier-side safety checks,
5. residual runtime safety assumptions,
6. required deterministic rejection conditions.
## 7. A Ver
The following items remain to be closed in future agenda discussion.
- Exact verifier obligations beyond what is already implied by runtime/bytecode authority.
- Which safety properties must be proven before execution versus checked defensively at runtime.
- Whether PBS-level conformance includes explicit verifier test surfaces or only artifact validity outcomes.
- How source-level diagnostics relate to verifier and artifact-level safety failures.
## 8. Non-Goals
- Replacing runtime or bytecode authority.
- Duplicating the full Host ABI spec.
- Freezing one verifier implementation algorithm.
## 9. Exit Criteria
This document is ready to move beyond skeleton status only when:
1. the division of safety responsibilities is explicit,
2. verifier-facing assumptions are aligned with lowering and artifact mapping,
3. deterministic rejection surfaces are normatively described,
4. the document no longer relies on unresolved `A Ver` items for ordinary v1 safety claims.
@@ -1,152 +0,0 @@
# PBS Governance and Versioning
Status: Draft v1
Applies to: PBS language, profiles, and related specifications
## 1. Purpose
This document defines how PBS decisions are made and how versions evolve without breaking the ecosystem unpredictably.
## 2. Scope
This policy governs:
- language specification changes,
- profile changes (for example, Core/Game),
- standard library specification changes,
- compatibility policy updates,
- release and deprecation decisions.
## 3. Governance Model
PBS uses a spec-first governance model.
No implementation change is considered normative until the relevant spec change is accepted.
### 3.1 Roles
- Maintainers: approve/reject RFCs and cut releases.
- Editors: keep specs coherent, complete, and cross-referenced.
- Implementers: provide feasibility feedback and conformance evidence.
- Community contributors: propose RFCs and review drafts.
### 3.2 Authority Rule
If a governance decision conflicts with runtime/bytecode authority, runtime/bytecode authority wins.
## 4. Decision Process (RFC)
All non-trivial changes MUST go through RFC.
### 4.1 RFC Lifecycle
1. Draft: problem, proposal, alternatives, migration impact.
2. Review: open feedback period.
3. Decision: `Accepted`, `Rejected`, or `Deferred`.
4. Spec Merge: normative documents updated.
5. Implementation: only after spec merge.
6. Conformance: tests and diagnostics updated before release.
### 4.2 Fast-Track
Fast-track is allowed only for:
- critical correctness fixes,
- security/capability violations,
- deterministic behavior regressions.
Fast-track changes still require post-merge RFC backfill.
## 5. Version Domains
PBS versioning is separated by domain to avoid ambiguity.
1. Language Version (`pbs_lang`): syntax + semantics.
2. Profile Version (`pbs_profile`): profile-specific surface (Core/Game).
3. Stdlib Version (`pbs_stdlib`): standard library contract.
4. Compatibility Policy Version (`pbs_compat`): evolution/deprecation policy text.
Host primitives remain versioned by canonical identity `(module, name, version)`.
Direct declaration of canonical host primitive bindings is reserved to SDK/toolchain-managed `declare host` surfaces, not ordinary user-authored PBS modules.
User-facing PBS and stdlib APIs over host primitives MAY evolve independently from those bindings as long as canonical host identity, capability policy, and compatibility commitments remain preserved.
## 6. Versioning Scheme
Each domain uses semantic versioning:
- `MAJOR`: incompatible changes.
- `MINOR`: backward-compatible additions.
- `PATCH`: clarifications/fixes with no intended behavior break.
## 7. Change Classification
### 7.1 Patch Changes
- wording fixes,
- unambiguous typo corrections,
- diagnostics wording adjustments without code/behavior contract changes.
### 7.2 Minor Changes
- additive syntax behind explicit profile gates,
- new stdlib APIs,
- new host primitive versions added without removing old supported versions.
### 7.3 Major Changes
- behavior changes that can alter valid program outcomes,
- removal of previously supported constructs,
- incompatible type or resolution rule changes.
## 8. Compatibility Rules
- Supported old versions MUST continue to compile/link/run as declared by the compatibility window.
- A release MUST publish a compatibility matrix for language/profile/stdlib domains.
- Toolchains MUST reject unsupported targets deterministically with explicit diagnostics.
## 9. Deprecation and Removal Policy
Deprecation stages:
1. Introduce deprecation notice in specs and tooling.
2. Keep feature functional during declared support window.
3. Remove only in a subsequent major version.
Every deprecation MUST include:
- replacement path,
- migration notes,
- timeline (first deprecated version, last supported version, removal version).
## 10. Release Requirements
Before any version release:
1. Specs for changed domains are updated.
2. Changelog is published with change classification.
3. Conformance suite is updated and passing.
4. Compatibility matrix is published.
5. Migration guide is provided for any major-impact changes.
## 11. Documentation Contract
Every accepted change MUST update, when relevant:
- normative spec sections,
- examples,
- diagnostics documentation,
- conformance tests,
- compatibility matrix/changelog.
## 12. Conflict Resolution
When maintainers disagree, the tie-breaker is:
1. determinism and compatibility,
2. clarity for beginners,
3. implementation feasibility and tooling stability.
## 13. Non-Goals
- Replacing runtime authority with governance-only decisions.
- Defining subsystem-specific API semantics in this document.
- Granting implementation behavior override over normative specs.
File diff suppressed because it is too large Load Diff
@@ -1,760 +0,0 @@
# PBS Static Semantics Specification
Status: Draft v1 (Normative)
Scope: binding, callable formation, type checking, and deterministic function application
## 1. Purpose
This document defines the static semantics of PBS core language.
It is intended to:
- give deterministic meaning to declarations accepted by the syntax specification,
- define callable identity and application rules,
- make type checking stable across implementations,
- preserve beginner-facing clarity without hidden callable behavior.
## 2. Core Semantic Model
### 2.1 Authority and precedence
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
3. `3. Core Syntax Specification.md`
4. This document
If a rule here conflicts with higher authority, it is invalid.
### 2.2 Semantic namespaces
PBS distinguishes at least:
- type namespace,
- value namespace,
- callable namespace.
- host-owner namespace.
Rules:
- `declare struct`, `declare service`, `declare contract`, `declare error`, `declare enum`, `declare callback`, and `declare builtin type` introduce names in the type namespace.
- `declare host` introduces names in the host-owner namespace.
- `let`, parameters, and `declare const` introduce names in the value namespace.
- `declare service Name` also introduces the canonical singleton value `Name` in the value namespace.
- Top-level `fn`, service methods, and host methods participate in the callable namespace.
- `fn` declarations are not first-class values in v1 core and therefore do not become ordinary value expressions.
- `bind(...)` is a callback-formation construct, not a general function-value construct.
- `declare host` declarations are reserved to SDK/toolchain-controlled modules and are not formable in ordinary user-authored PBS source.
- `declare builtin type` declarations are reserved to SDK/toolchain-controlled modules and are not formable in ordinary user-authored PBS source.
- A host owner name is not an ordinary value expression in v1 core; it is used only as a qualified host-call owner.
- The builtin simple types `int`, `float`, `bool`, and `str` are always present in the type namespace.
- Builtin simple types are resolved without import or declaration.
- User-authored type declarations must not reuse builtin simple type names.
### 2.3 Attribute metadata
Attributes are compile-time metadata attached to declaration surfaces.
Rules:
- An attribute has no value-level or type-level meaning by itself.
- Attributes are not first-class values and are not reflectable in v1 core.
- Attributes do not automatically survive into runtime or bytecode artifacts.
- An attribute affects runtime artifacts only when another specification defines an explicit lowering for its semantic effect.
- In v1 core, the normative reserved attributes are `Host`, `BuiltinType`, `BuiltinConst`, `IntrinsicCall`, and `Slot`.
- `Host` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body.
- `Host` is invalid on ordinary user-authored modules, top-level `fn`, struct methods, service methods, callbacks, contracts, and constants.
- `Host` metadata is consumed by the compiler during host-binding lowering.
- The `Host` attribute syntax itself is not exported as runtime metadata; instead, its canonical identity participates in PBX host-binding emission as defined by the Host ABI Binding specification.
- `BuiltinType` is valid only on a reserved top-level `declare builtin type` declaration.
- `BuiltinConst` is valid only on a reserved top-level `declare const` declaration that omits an initializer.
- `IntrinsicCall` is valid only on a method signature declared directly inside a reserved `declare builtin type` body.
- `Slot` is valid only on a field declaration in the header of a reserved `declare builtin type`.
- Builtin metadata is consumed by the compiler during VM-owned builtin and intrinsic lowering rather than by host-binding lowering.
### 2.4 Tuple shapes
Static checking uses tuple shapes as semantic objects.
Definitions:
- Input tuple shape: ordered sequence of zero or more input slots.
- Output tuple shape: ordered sequence of zero or more output slots.
- Each slot has a type and a stable label.
Rules:
- Tuple shapes in PBS core are always named, except for unit `()`.
- Input slot labels come from parameter names and are local frame names.
- Output slot labels come from return annotations and are visible for multi-slot member projection.
- Tuple-shape identity for overload and resolution ignores labels.
- Tuple-shape compatibility requires matching arity and positional slot types.
- Labels must still be preserved as part of declaration surface and projection metadata.
- A single-slot tuple shape has a distinguished carrier value type equal to its slot type.
- In value positions, single-slot tuple values collapse to their carrier value type.
- Single-slot tuple shapes have no dedicated tuple-literal surface in v1 core.
## 3. Functions and `apply`
### 3.1 Canonical function model
Every callable `fn` in PBS is modeled statically as:
```text
Fn : InputTuple -> OutputTuple
```
Rules:
- `fn f(a: A, b: B)` has input tuple shape `(a: A, b: B)`.
- `fn f()` has empty input tuple shape `()`.
- `-> void`, `-> ()`, and omitted return annotation all denote empty output tuple shape `()`.
- `-> T` denotes a single-slot output tuple shape `(value: T)`.
- `-> (x: T)` denotes a single-slot output tuple shape `(x: T)`.
- `-> (x: T, y: U)` denotes a two-slot output tuple shape `(x: T, y: U)`.
- `-> T` and `-> (x: T)` are identical for overload identity and differ only in preserved label metadata.
- `optional T` is a regular value type and may appear in parameters, locals, fields, and plain returns.
- `optional T` with single-slot payload is internally normalized to `optional<(value: T)>`.
- `optional` and `optional void` are invalid type surfaces.
- `-> result<E> T` denotes a result return surface over payload shape `T` and error type `E`.
- `-> result<E> T` with single-slot payload is internally normalized to `result<E, (value: T)>`.
- `-> result<E>` is valid and denotes a result return surface with unit payload.
- A function return surface may be plain or `result<E>`.
- A function return surface must not combine `optional` and `result` in the same declaration.
- `result<E>` wraps the declared success payload; the payload itself may be scalar or a named tuple shape.
### 3.2 Callable categories
The following constructs are callable in v1 core:
- top-level `fn`,
- struct methods on concrete receivers,
- contract values,
- callback values,
- service methods,
- host methods on declared host owners,
- builtin intrinsic methods on declared builtin types.
Rules:
- All callable categories use the same input/output tuple model.
- A struct method is identified by `(struct type, method name, input tuple shape excluding the receiver slot, output tuple shape)`.
- A contract value is identified at the type level by its contract type and at runtime by an underlying concrete struct instance or service singleton value plus its selected implementation.
- A callback declaration defines a nominal callable type with exactly one input/output tuple shape.
- A service method is identified by `(service name, method name, input tuple shape, output tuple shape)`.
- A host method is identified by `(host owner name, method name, input tuple shape, output tuple shape)` within the PBS declaration surface.
- A builtin intrinsic method is identified within PBS declaration surface by `(builtin type name, method name, input tuple shape, output tuple shape)` and lowers further by canonical builtin/intrinsic metadata.
- A top-level `fn` is identified by `(name, input tuple shape, output tuple shape)`.
- A callback value is identified at the type level by its declared callback type and signature.
- Contract signatures and barrel signatures must preserve the same callable shape.
- Canonical host primitive identity and binding are governed by the Host ABI Binding specification rather than by ordinary v1 core declaration identity alone.
### 3.3 Declaration validity
Rules:
- Parameter names in a single `ParamList` must be unique.
- Output labels in a named tuple return annotation must be unique.
- Error case labels in a single `declare error` body must be unique.
- Enum case labels in a single `declare enum` must be unique.
- Enum case integer identifiers in a single `declare enum` must be unique.
- Two declarations with the same callable name and the same input/output tuple shape are duplicates.
- Changing only parameter names does not create a new callable.
- Changing only input labels in `ParamList` does not create a new callable.
- Changing only output labels does not create a new callable.
- `mod.barrel` function entries are matched by callable identity, ignoring labels.
- Barrel labels may differ from implementation labels.
- Any return surface that combines `optional` and `result` is statically invalid.
- Any payload-less `optional` type surface is statically invalid.
- Any `optional void` type surface is statically invalid.
- A host method signature in a reserved stdlib/interface module MUST carry exactly one `Host` attribute.
- A `Host` attribute MUST declare exactly the named arguments `module`, `name`, and `version`.
- `Host.module` and `Host.name` MUST be non-empty string literals.
- `Host.version` MUST be a positive integer literal.
- Two host methods in the same resolved stdlib environment MUST NOT lower to the same canonical `(module, name, version)` unless they denote the same host method declaration after project/module resolution.
- A `declare const` declaration must include an explicit type annotation.
- A `declare const` declaration without `BuiltinConst` metadata must include an initializer.
- A `declare const` declaration with `BuiltinConst` metadata must omit the initializer.
- A non-builtin `declare const` initializer must be a constant expression.
- `declare const` dependency resolution is module-wide and must not depend on source-file processing order.
- `declare const` dependencies must form an acyclic graph.
- A `BuiltinType` attribute MUST declare exactly the named arguments `name` and `version`.
- `BuiltinType.name` MUST be a non-empty string literal.
- `BuiltinType.version` MUST be a positive integer literal.
- Two builtin type declarations in the same resolved stdlib environment MUST NOT lower to the same canonical `(name, version)` unless they denote the same builtin declaration after project/module resolution.
- A builtin field type must be builtin-layout-admissible as defined by the builtin/intrinsics specification.
- A builtin field `Slot` attribute, when present, MUST declare a non-negative integer literal and must match the declaration's canonical flattened layout.
- `IntrinsicCall` MUST declare exactly the named argument `name` and MAY additionally declare `version`.
- `IntrinsicCall.name` MUST be a non-empty string literal.
- `IntrinsicCall.version`, when present, MUST be a positive integer literal.
- Two builtin methods in the same canonical builtin owner/version line MUST NOT lower to the same canonical intrinsic `(owner, name, version)` unless they denote the same builtin method declaration after project/module resolution.
- `BuiltinConst` MUST declare exactly the named arguments `target`, `name`, and `version`.
- `BuiltinConst.target` and `BuiltinConst.name` MUST be non-empty string literals.
- `BuiltinConst.version` MUST be a positive integer literal.
- Two builtin constant declarations in the same resolved stdlib environment MUST NOT lower to the same canonical `(target, name, version)` unless they denote the same builtin constant declaration after project/module resolution.
### 3.4 Constant expressions
PBS core v1 restricts top-level constant evaluation to a deterministic compile-time subset.
Rules:
- A non-builtin `declare const` initializer is evaluated at compile time.
- A non-builtin `declare const` may depend only on previously resolved visible `declare const` declarations and enum case values.
- Cross-file constant resolution within a module is defined by dependency analysis, not source-file order.
- Constant evaluation fails if the dependency graph contains a cycle.
- The allowed constant-expression forms in v1 core are:
- scalar literals: `IntLit`, `FloatLit`, `StringLit`, `BoolLit`,
- enum case paths `EnumName.caseName`,
- a reference to another visible `declare const`,
- unary `-` applied to an integer or float constant expression,
- unary `not` or `!` applied to a boolean constant expression,
- binary arithmetic operators over numeric constant expressions,
- binary comparison operators over compatible constant expressions,
- binary boolean operators over boolean constant expressions.
- A non-builtin `declare const` initializer must not use:
- callable application or call sugar,
- `new`,
- `bind(...)`,
- `some(...)` or `none`,
- tuple expressions,
- block expressions,
- `if`, `switch`, `handle`, `else` extraction, or `!` result propagation,
- method calls or member access except enum case paths.
- For non-builtin `declare const`, the initializer type must be compatible with the declared `const` type.
- A `BuiltinConst` declaration is not part of ordinary compile-time constant evaluation and lowers through VM-owned builtin constant materialization instead.
- A `declare const` exported through `mod.barrel` may be imported from another module only through ordinary module import rules.
- A `declare const` does not introduce mutable runtime storage; implementations may inline, fold, or materialize it as an immutable constant as long as observable semantics remain unchanged.
### 3.5 Enum declarations and values
Rules:
- `declare enum Name(case1, case2, ...);` introduces a nominal enum type `Name`.
- `declare enum Name(case1 = n1, case2 = n2, ...);` introduces explicit integer identifiers for enum cases.
- If no enum case uses an explicit identifier, identifiers are assigned as `0..n-1` in declaration order.
- If any enum case uses an explicit identifier, then every enum case in that declaration must use an explicit identifier.
- `Name.case` is a valid enum value surface only when `Name` resolves to a declared enum type and `case` resolves to a declared case of that enum.
- The static type of `Name.case` is the enum type `Name`.
- Error labels are not enum cases and must not be used where enum case values are required.
### 3.6 Structs, services, methods, and contracts
Rules:
- Struct values are heap-backed reference values in v1 core.
- Service values are canonical module-owned singleton values in v1 core.
- `new Struct(args...)` allocates a new struct instance of the declared struct type.
- `new Struct.ctorName(args...)` invokes a named constructor declared in the enclosing struct body and produces a new struct instance of that type.
- Struct construction arguments are matched positionally to the declared struct field order.
- Assigning a struct value copies the reference, not the underlying field storage.
- Assigning a service value copies the same canonical singleton identity; it does not create a new instance.
- A struct field with no access modifier is readable and writable only from methods and `ctor` bodies of its enclosing struct.
- A `pub` struct field is externally readable but remains externally non-assignable.
- A `pub mut` struct field is externally readable and externally assignable.
- An assignment target `expr.name` to a struct field is valid only when the access site is permitted to write that field.
- Writes to a private struct field are valid only through `this.name` inside methods and `ctor` bodies of the enclosing struct.
- A struct method declared in a struct body has an implicit receiver binding `this` of type `Self`.
- A service method declared in a service body has an implicit receiver binding `this` of type `Self`.
- `this` is valid only inside struct method, service method, and `ctor` bodies.
- `Self` is valid only in struct method, service method, and `ctor` declarations and denotes the enclosing owner type.
- The enclosing struct name is in scope inside its own field declarations, enabling self-referential field types.
- A named `ctor` declared in a struct body is not a method, but it does introduce an implicit under-construction `this`.
- A `ctor` has no declared return annotation and is not a `fn`.
- A `ctor` completes by falling off the end of its body after initializing the enclosing struct instance.
- Every field of the enclosing struct must be definitely assigned on every completing `ctor` path.
- Named constructors participate in overload resolution by name plus parameter signature.
- `return;` and `return expr;` are both invalid inside `ctor` bodies.
- Methods declared in a struct body belong to the direct method namespace of that concrete struct type.
- Methods declared in a service body belong to the direct method namespace of that concrete service type.
- `receiver.method(...)` on a concrete struct receiver resolves only against methods declared directly in that struct body.
- `receiver.method(...)` on a service receiver resolves only against methods declared directly in that service body.
- `receiver.ctorName(...)` is never valid on a concrete struct value.
- Service values are ordinary value expressions and may be assigned, passed, and returned under their declared service type.
- Services do not have fields.
- Services do not declare named constructors and are never targets of `new`.
- Contract implementations do not inject their methods into the direct method namespace of the concrete struct or service.
- `implements Contract for Owner using s { ... }` is unique per `(Contract, Owner)` pair, where `Owner` is a declared struct or service.
- A contract for a struct or service may be implemented only in the module where that owner itself is declared.
- Contracts may be declared in other modules and implemented for the local struct or service in its owner module.
- An `implements` block has no independent visibility; its observability follows the visibility of the owner declaration, and the contract must also be nameable at the use site.
- Methods declared directly inside a struct or service follow the visibility of their enclosing owner declaration; they do not have independent visibility.
- A struct value or service singleton value may be coerced to a contract value when exactly one visible `implements Contract for Owner ...` applies.
- Contract coercion may happen by explicit `expr as ContractType` or by contextual typing in assignments, parameter passing, and returns.
- `as` in expression position is reserved for explicit contract coercion only; no other cast semantics exist in v1 core.
- The contract name in `expr as ContractName` must be a simple visible identifier resolved through ordinary scope and import rules.
- A contract value carries the underlying struct reference or service singleton value together with the selected contract implementation for runtime dispatch.
- Calling `contractValue.method(...)` uses dynamic dispatch through the contract value.
- Calling `structValue.contractMethod(...)` is not valid unless that method is also declared directly on the struct.
- Calling `serviceValue.contractMethod(...)` is not valid unless that method is also declared directly on the service.
- Structs do not have static methods in v1 core; named constructors are their only type-qualified callable members.
- Services are accessed through their canonical singleton value, not through `new` or static method declarations.
Example:
```pbs
declare contract StasisProcess {
fn stasis() -> int;
}
declare struct Struct(pub a: int) {
fn compute() -> int {
return this.a;
}
ctor createWithSomethingSpecial(x: int) {
this.a = x;
}
}
implements StasisProcess for Struct using s {
fn stasis() -> int {
return s.compute();
}
}
fn demo() -> int {
let s = new Struct(1);
let s2 = new Struct.createWithSomethingSpecial(2);
let sp: StasisProcess = s;
let sp2 = s as StasisProcess;
let a = s.a;
let _ = s2.compute();
let b = sp.stasis();
let c = sp2.stasis();
return a + b + c;
}
```
### 3.7 Nominal callbacks
Rules:
- `declare callback Name(params...) -> R;` introduces a nominal callback type `Name`.
- A callback type is not a `fn`, and a `fn` declaration does not implicitly define a callback type.
- A value of callback type may be formed only from a compatible top-level `fn` in v1 core.
- A value of callback type may also be formed by `bind(context, fn_name)` when the surrounding static type context expects a callback type.
- Service methods are not assignable to callback values in v1 core.
- Host methods are not assignable to callback values in v1 core.
- Callback values do not capture local environment implicitly.
- Assignment of a top-level `fn` to a callback type succeeds only when exactly one visible overload matches the callback signature.
- `bind(context, fn_name)` succeeds only when exactly one visible top-level `fn` overload matches after consuming the first parameter with `context`.
- Valid expected callback contexts for `bind(context, fn_name)` include variable initialization with an explicit callback type, assignment to an explicitly typed callback location, argument passing to a callback-typed parameter, and return from a callback-typed function.
- The context expression in `bind(context, fn_name)` is evaluated once at bind time and stored explicitly in the resulting callback value.
- The stored context follows normal value semantics for its type.
- `bind(context, fn_name)` does not introduce general closures; it is explicit partial binding of the first parameter only.
- Callback compatibility ignores labels and compares ordered input/output slot types plus the return-surface kind.
Example:
```pbs
declare callback TickCb(dt: int) -> void;
fn on_tick(dt: int) -> void {
}
fn install_tick() -> void {
let cb: TickCb = on_tick;
let _ = cb;
}
```
Bound example:
```pbs
declare callback UpdateCb(dt: int) -> void;
declare struct Enemy(hp: int);
fn update_enemy(self: Enemy, dt: int) -> void {
}
fn install_update(enemy: Enemy) -> void {
let cb: UpdateCb = bind(enemy, update_enemy);
let _ = cb;
}
```
Ambiguous overload example:
```pbs
declare callback TickCb(dt: int) -> void;
fn tick(dt: int) -> void {
}
fn tick(time: int) -> void {
}
fn install_tick() -> void {
let cb: TickCb = tick; // error: ambiguous overloaded fn assignment
}
```
### 3.8 Canonical application
The canonical surface form for function application is:
```pbs
callee apply arg
```
Rules:
- `apply` is an infix operator that is right-associative.
- `f1 apply f2 apply x` is defined as `f1 apply (f2 apply x)`.
- `f1 apply f2 apply f3 apply params` is defined as `f1 apply (f2 apply (f3 apply params))`.
- The left operand of `apply` must resolve to one of: a callable candidate set, a bound struct method target, a bound service method target, a contract-method target, or a callback value.
- The right operand of `apply` is an argument expression.
- If the callable input arity is `0`, the argument expression must be `()`.
- If the callable input arity is `1`, the argument expression is checked against the carrier type of the single input slot.
- If the callable input arity is `2..6`, the argument expression must have a named tuple shape with matching arity and positional types.
- Input labels are not used for compatibility.
- No single-slot tuple argument literal is required or recognized in surface syntax.
- There is no partial application in v1 core.
- There is no currying in v1 core.
- Chained `apply` is nested ordinary application, not callable composition as a first-class value.
- Callback values, service methods, host methods, struct methods, and contract-method targets use the same `apply` rules as top-level `fn`.
### 3.9 Call sugar
The surface form:
```pbs
callee(arg1, arg2, ..., argN)
```
desugars to the canonical `apply` surface according to arity.
Rules:
- The desugaring is purely syntactic.
- `f()` is exact sugar for `f apply ()`.
- `f(x)` is exact sugar for `f apply x`.
- `f(x1, x2, ..., xn)` for `n >= 2` is exact sugar for `f apply (x1, x2, ..., xn)`.
- No semantic distinction exists between direct call sugar and its canonical `apply` form.
- When `(arg1, ..., argN)` is used as positional tuple sugar, the callee input tuple shape supplies the effective labels.
- All overload resolution, diagnostics, and type checking are defined on the canonical `apply` form.
### 3.10 Result type of application
Rules:
- If the selected callable output arity is `0`, the result of `apply` is unit.
- If the selected callable output arity is `1`, the result of `apply` is the carrier type of the single output slot.
- If the selected callable output arity is `2..6`, the result of `apply` has the named output tuple shape of the selected callable.
- Multi-slot output tuple results expose their labels for member projection.
- If the selected callable is a callback value, the visible multi-slot output labels come from the callback type rather than from the original source `fn`.
- If the selected callable returns `()`, the application result is unit.
Example:
```pbs
fn func(a: int, b: int) -> (c: int, d: float) {
return (c: a + b, d: 2.0);
}
fn demo_apply() -> int {
let params: (a: int, b: int) = (1, 2);
let r = func apply params;
let c = r.c;
let d = r.d;
let _ = d;
return c;
}
```
In the example above:
- `func` has input tuple shape `(a: int, b: int)`,
- `func` has output tuple shape `(c: int, d: float)`,
- `r` has named output tuple type `(c: int, d: float)`,
- `r.c` has type `int`,
- `r.d` has type `float`.
Single-slot example:
```pbs
fn plus_one(x: int) -> int {
return x + 1;
}
fn demo_single() -> void {
let r = plus_one apply 1;
if r == 2 {
}
}
```
In the example above:
- `plus_one` has input tuple shape `(x: int)`,
- the argument `1` is accepted directly as the carrier value for the single input slot,
- `plus_one` has output tuple shape `(value: int)`,
- the value produced by `plus_one apply 1` has carrier type `int`,
- `r.value` is not required and should not be used.
### 3.11 Overload resolution
Rules:
- Overload resolution starts from the visible callable candidates with the selected name.
- Candidate filtering first uses callable kind and input tuple arity.
- Remaining candidates are filtered by positional input type compatibility.
- If exactly one candidate remains, resolution succeeds.
- If multiple candidates remain, expected output types or expected multi-slot output tuple shapes may be used as a tie-breaker when statically available.
- If multiple candidates still remain, the `apply` is ambiguous and compilation fails.
- If no candidate remains, the `apply` is unresolved and compilation fails.
- Overloads that differ only by labels are duplicates and are forbidden.
- Overloads that differ only by output positional types are permitted, but uncontextualized `apply` sites may become ambiguous.
### 3.12 Member access and projection
Rules:
- `TypeName.case` is valid when `TypeName` resolves to a declared enum type and `case` resolves to one of its declared enum cases.
- `TypeName.case` has static type `TypeName`.
- `expr.name` is valid when the static type of `expr` is a declared `struct` containing field `name` and the access site is permitted to read that field.
- For `struct` field access, the projected member type is the declared field type.
- Reads of a private struct field are valid only through `this.name` inside methods and `ctor` bodies of the enclosing struct.
- `expr.method` is a valid method-call target when the static type of `expr` is a concrete struct type declaring method `method`.
- `expr.method` over a concrete struct receiver does not search visible contract implementations.
- `expr.method` is a valid method-call target when the static type of `expr` is a concrete service type declaring method `method`.
- `expr.method` over a concrete service receiver does not search visible contract implementations.
- `HostName.method` is a valid method-call target when `HostName` resolves to a visible declared host owner whose body declares method `method`.
- `TypeName.ctorName` is not a general member access surface; named constructors are entered only through `new TypeName.ctorName(...)`.
- `expr.method` is a valid method-call target when the static type of `expr` is a contract value whose contract declares method `method`.
- Bare extraction of a struct, service, host, builtin, or contract method as a value is invalid in v1 core because methods are not first-class.
- `expr.name` is valid when the static type of `expr` is a multi-slot named output tuple containing label `name`.
- For named output tuples, the projected member type is the type of the corresponding output slot.
- Projection is label-based, not position-based.
- `expr.name` is valid when the static type of `expr` is a builtin type declaring projection field `name`.
- For builtin projection fields, the projected member type is the declared builtin field type.
- `expr.method` is a valid method-call target when the static type of `expr` is a builtin type declaring intrinsic member `method`.
- `expr.hasSome()` and `expr.hasNone()` are valid intrinsic method-call surfaces when the static type of `expr` is `optional<P>`.
- `expr.hasSome()` and `expr.hasNone()` both have static type `bool`.
- `expr.name()` and `expr.key()` are valid intrinsic method-call surfaces when the static type of `expr` is an enum type.
- `expr.name()` has static type `str`.
- `expr.key()` has static type `int`.
- Access to a missing output label is a compile-time error.
- Access to a missing struct field is a compile-time error.
- Read access to an inaccessible private struct field is a compile-time error.
- Write access to an inaccessible or non-`pub mut` struct field is a compile-time error.
- Access to a missing struct method is a compile-time error.
- Access to a missing service method is a compile-time error.
- Access to a missing host method is a compile-time error.
- Access to a missing contract method is a compile-time error.
- Access to a missing builtin projection field is a compile-time error.
- Access to a missing builtin intrinsic member is a compile-time error.
- Member projection is not defined for single-slot collapsed carrier values.
### 3.13 Block expressions and function fallthrough
Rules:
- A block expression with a `TailExpr` has the static type of that final expression.
- A block expression without a `TailExpr` has static type unit.
- Only the final unsemicoloned expression in a block contributes to the block result.
- A function body does not implicitly return its trailing `TailExpr`; explicit `return` and ordinary control-flow rules still apply.
- Reaching the end of a plain non-unit function is a compile-time error unless all control-flow paths are proven to return explicitly.
- Reaching the end of a `void` or `()` function is valid and yields unit.
- Reaching the end of an `optional P` function yields `none`.
- Reaching the end of a `result<E>` function is a compile-time error.
### 3.14 Loop forms
Rules:
- `while cond { ... }` requires `cond` to have static type `bool`.
- `for i: T from start until end { ... }` is the declarative counted loop form in v1 core.
- `for i: T from start until end step s { ... }` is the explicit-step counted loop form in v1 core.
- In `for`, the declared iteration variable `i` introduces a loop-local binding of type `T`.
- `start`, `end`, and `step` expressions in `for` must be type-compatible with the declared iteration type `T`.
- If `step` is omitted, the loop uses the integer value `1` of the iteration type domain.
- `for` iteration proceeds by evaluating `start`, `end`, and optional `step` once before loop entry.
- `for ... until ...` uses an exclusive upper bound.
- `continue` inside `while` transfers control to the next condition check.
- `continue` inside `for` transfers control to the step update and then to the next bound check.
- `break` exits the nearest enclosing loop.
### 3.15 `if` and `switch` conditional expressions
Rules:
- In `if cond { a } else { b }`, `cond` must have static type `bool`.
- Only the selected branch is evaluated at runtime.
- The branch expressions `a` and `b` must have the same static type, subject only to ordinary contextual typing already defined elsewhere in the language.
- The static result type of the `if` expression is that shared static type.
- In `switch selector { pattern: { ... }, ... }`, the selector expression is evaluated once.
- `switch` accepts enum selectors and literal-comparable scalar selectors; `error` selectors are invalid.
- Each non-wildcard `switch` arm pattern must be unique within the same `switch`.
- Each non-wildcard `switch` arm pattern must be type-compatible with the selector expression.
- Enum-case switch patterns must resolve to declared cases of the selector's enum type.
- Error labels are not valid switch patterns.
- `default` and `_` are equivalent wildcard spellings for `switch`.
- At most one wildcard arm may appear in a `switch`.
- A `switch` must not mix `default` and `_` in the same arm set.
- The blocks of all `switch` arms must have the same static type, subject only to ordinary contextual typing already defined elsewhere in the language.
- The static result type of the `switch` expression is that shared static type.
- A `switch` used as an `ExprStmt` is valid when the selected arm blocks evaluate to unit.
- A `switch` expression used in a value-required position must be exhaustive, either by a wildcard arm or by another statically proven exhaustive case set.
### 3.16 `optional` construction and extraction
Rules:
- `some(expr)` forms an `optional<P>` value where `P` is the static type of `expr`, unless an expected `optional<Q>` context is present and constrains `expr` to be compatible with `Q`.
- `some(expr)` is invalid when the payload normalizes to `void`.
- `none` is valid only when an expected `optional<P>` type is available from context.
- `opt else fallback` requires the left operand to have static type `optional<P>`.
- In `opt else fallback`, the `fallback` expression must be compatible with payload shape `P`.
- The static result type of `opt else fallback` is the carrier value type for single-slot payloads and the named tuple payload shape for multi-slot payloads.
- `opt else fallback` does not introduce implicit mutation or unwrapping side effects beyond normal expression evaluation.
### 3.17 `result<E>` return flow and handling
Rules:
- `return ok(expr);` is valid only inside a function whose declared return surface is `result<E> P`.
- In `return ok(expr);`, `expr` must be compatible with the declared success payload shape `P`.
- `return err(E.label);` is valid only inside a function whose declared return surface is `result<E> P`.
- In `return err(E.label);`, the error path must resolve to a declared case of the same error type `E`.
- `ok(...)` and `err(...)` do not denote ordinary value expressions in v1 core.
- `expr!` requires `expr` to have static type `result<E> P`.
- `expr!` is valid only when the enclosing function returns `result<E> Q` for the same error type `E`.
- The static result type of `expr!` is the extracted success payload shape `P`, collapsed to its carrier value when single-slot.
- `handle expr { ... }` requires `expr` to have static type `result<E1> P`.
- `handle expr { ... }` is valid only when the enclosing function returns `result<E2> Q` for some payload `Q`.
- Each non-wildcard `handle` arm must match a distinct declared case of `E1`.
- Each mapped error path on the right side of a `handle` arm must resolve to a declared case of `E2`.
- `handle` arms must be exhaustive over `E1`, either by naming all cases exactly once or by providing `_`.
- The static result type of `handle expr { ... }` is the extracted success payload shape `P`, collapsed to its carrier value when single-slot.
- On error, `handle` performs an immediate enclosing-function return with the mapped `err(...)`.
### 3.18 Required static diagnostics
At minimum, deterministic static diagnostics are required for:
- duplicate parameter names in `fn` declarations,
- duplicate declaration names in the same namespace/scope,
- duplicate output labels in named tuple returns,
- duplicate error case labels in `declare error`,
- duplicate enum case labels in `declare enum`,
- duplicate enum case identifiers in `declare enum`,
- invalid mixed implicit/explicit enum case identifiers,
- invalid `this` usage outside struct method, service method, or `ctor` body,
- invalid `Self` type usage outside struct method, service method, or `ctor` declarations,
- invalid struct method declaration shape,
- invalid service method declaration shape,
- invalid host declaration shape,
- invalid host method declaration shape,
- invalid attribute surface,
- invalid `Host` attribute target,
- invalid `BuiltinType` attribute target,
- invalid `BuiltinConst` attribute target,
- invalid `IntrinsicCall` attribute target,
- invalid `Slot` attribute target,
- duplicate `Host` attribute on one host method,
- missing required `Host` attribute on a reserved host method,
- malformed `Host(module=..., name=..., version=...)` argument set,
- invalid empty `Host.module` or `Host.name`,
- invalid non-positive `Host.version`,
- invalid builtin declaration shape,
- invalid builtin method declaration shape,
- missing required `BuiltinType` attribute on a reserved builtin declaration,
- malformed `BuiltinType(name=..., version=...)` argument set,
- invalid empty `BuiltinType.name`,
- invalid non-positive `BuiltinType.version`,
- malformed `IntrinsicCall(name=..., version=...)` argument set,
- invalid empty `IntrinsicCall.name`,
- invalid non-positive `IntrinsicCall.version`,
- malformed `BuiltinConst(target=..., name=..., version=...)` argument set,
- invalid empty `BuiltinConst.target` or `BuiltinConst.name`,
- invalid non-positive `BuiltinConst.version`,
- invalid builtin field `Slot(...)`,
- overlapping builtin field slot range,
- builtin field type not builtin-layout-admissible,
- duplicate canonical builtin type identity,
- duplicate canonical builtin intrinsic identity,
- duplicate canonical builtin constant identity,
- invalid `ctor` declaration shape,
- invalid `return` inside `ctor`,
- incomplete field initialization on a completing `ctor` path,
- duplicate `implements Contract for Owner` pair,
- `implements` declared outside the owner module of the struct or service,
- incompatible or missing contract method implementation,
- invalid contract coercion from concrete struct or service value,
- unresolved barrel function signature after label-insensitive matching,
- unresolved host barrel entry,
- unresolved callback barrel entry,
- invalid enum case path,
- invalid enum intrinsic member call,
- invalid named constructor target,
- unresolved named constructor overload,
- ambiguous named constructor overload,
- incompatible top-level `fn` assignment to callback type,
- ambiguous overloaded top-level `fn` assignment to callback type,
- attempted assignment of service method to callback type,
- attempted assignment of host method to callback type,
- use of `bind(...)` without an expected callback type,
- incompatible `bind(...)` context type for callback target,
- ambiguous overloaded top-level `fn` target in `bind(...)`,
- `apply` on a non-callable target,
- arity mismatch in `apply`,
- argument type mismatch in `apply`,
- `apply` chain with incompatible intermediate carrier/tuple shape,
- ambiguous overload resolution,
- unresolved callable application,
- possible fallthrough of plain non-unit function,
- non-boolean `while` condition,
- invalid `for` iteration type,
- incompatible `for` bound or step type,
- non-boolean `if` expression condition,
- incompatible `if` expression branch types,
- duplicate `switch` arm pattern,
- mixed `default` and `_` wildcard arms in `switch`,
- invalid `switch` selector type,
- selector-pattern type mismatch in `switch`,
- invalid enum case switch pattern,
- incompatible `switch` arm block types,
- non-exhaustive `switch` expression in value position,
- invalid mixed `optional`/`result` return surface,
- invalid payload-less `optional` type surface,
- invalid `optional void` type surface,
- invalid reuse of a builtin simple type name for a user-authored type declaration,
- missing explicit type annotation on `declare const`,
- missing initializer on non-builtin `declare const`,
- non-constant `declare const` initializer,
- incompatible `declare const` initializer type,
- cyclic dependency among `declare const` declarations,
- unresolved referenced `declare const` in constant evaluation,
- invalid `none` usage without expected optional type,
- invalid `else` extraction over non-optional operand,
- fallback type mismatch in `else` extraction,
- invalid `some(...)` construction form,
- use of `ok(...)` or `err(...)` outside `return`,
- invalid `ok(...)` construction form,
- invalid `err(...)` construction form,
- invalid error label in `err(...)`,
- invalid `!` propagation on non-result expression,
- mismatched error type in `!` propagation,
- invalid `handle` on non-result expression,
- non-exhaustive `handle` mapping,
- duplicate `handle` mapping arm,
- invalid mapped error label in `handle`,
- attempted use of a single-slot tuple literal where no such surface form exists,
- member access on a missing struct field,
- read access to an inaccessible private struct field,
- write access to an inaccessible or non-`pub mut` struct field,
- member access on a missing struct method,
- member access on a missing service method,
- member access on a missing host method,
- member access on a missing contract method,
- member access on a missing builtin projection field,
- member access on a missing builtin intrinsic member,
- bare method extraction from a struct, service, host, builtin, or contract value,
- member projection on a single-slot carrier value,
- invalid optional intrinsic member call,
- invalid builtin intrinsic member call,
- member projection on a missing named output label.
@@ -1,451 +0,0 @@
# PBS Manifest, Module, Stdlib, and SDK Resolution Specification
Status: Draft v2 (Normative)
Applies to: `prometeu.json`, project and module terminology, workspace dependency resolution, stdlib selection, reserved stdlib projects, interface-module loading, and compile-time SDK metadata
## 1. Purpose
This document defines the normative compile-time model for:
- project manifests,
- project and module identity,
- import resolution,
- stdlib selection,
- reserved stdlib project spaces,
- stdlib interface modules,
- and the compile-time lifecycle of SDK host-binding metadata.
This document is the authority for how the compiler discovers and loads:
- ordinary project modules,
- reserved stdlib modules such as `@sdk:gfx`,
- and compile-time-only host-binding metadata attached to those reserved modules.
This document does not define runtime load behavior.
PBX host-binding emission and loader-side syscall resolution are defined by the Host ABI Binding and Loader Resolution Specification.
## 2. Scope
This document defines:
- the role of `language` in `prometeu.json`,
- the role of `stdlib` in `prometeu.json`,
- the distinction between projects, modules, and imports,
- the distinction between ordinary project dependencies and the stdlib environment,
- root-project ownership of the effective stdlib line of a build,
- reserved project spaces such as `@sdk:*` and `@core:*`,
- the source model for stdlib interface modules,
- the compile-time role of reserved attributes such as `[Host(...)]`.
This document does not define:
- PBX binary layout,
- loader-side syscall resolution,
- cartridge capability policy,
- package registry protocol details,
- runtime reflection over attributes.
## 3. Core Terms
### 3.1 Project
A project is the unit described by `prometeu.json`.
Rules:
- A project has a `name`, `version`, `language`, `stdlib`, and `dependencies`.
- A project is the unit resolved by the workspace dependency graph.
- A project is the unit selected by a dependency declaration.
- A project is the unit published and versioned by ordinary dependency resolution.
- A project contains one or more modules.
### 3.2 Module
A module is the unit of source import inside a project.
Rules:
- Every `.pbs` source file belongs to exactly one module.
- Every module belongs to exactly one project.
- Imports select modules, not whole projects.
- A module is addressed by a project name plus a module path.
### 3.3 Canonical module address
The canonical PBS module address format is:
```text
@project:path/to/module
```
Rules:
- `project` identifies the owning project space.
- `path/to/module` identifies the module path inside that project.
- Module path segments are directory-style segments separated by `/`.
- The syntax is Java-like in organization and JavaScript-like in import surface.
Examples:
- `@game:player/state`
- `@physics:collision/shapes`
- `@sdk:gfx`
- `@core:math/vector`
### 3.4 Reserved project spaces
The following project spaces are reserved:
- `@sdk:*`
- `@core:*`
Rules:
- Reserved project spaces belong to the selected stdlib environment.
- Ordinary user-authored projects MUST NOT publish modules into reserved project spaces.
- Ordinary dependency resolution MUST NOT satisfy `@sdk:*` or `@core:*` imports from user projects.
- Reserved project spaces are resolved only from the selected stdlib environment.
## 4. `prometeu.json`
### 4.1 Required fields
The manifest format relevant to this document is:
```json
{
"name": "main",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"dependencies": [
{ "name": "dep1", "version": "1.0.0" }
]
}
```
Rules:
- `name` identifies the project.
- `version` identifies the project version.
- `language` identifies the frontend language.
- `stdlib` identifies the selected stdlib major line.
- `dependencies` declare ordinary project dependencies only.
### 4.2 `language`
Rules:
- `language` selects the compiler frontend.
- All projects in one resolved workspace MUST use the same `language`.
- Unknown `language` values are compile-time errors.
### 4.3 `stdlib`
Rules:
- `stdlib` is required in every manifest.
- `stdlib` uses major-only version syntax in v1.
- The manifest surface for `stdlib` is a string containing a positive decimal integer.
- Examples of valid values: `"1"`, `"2"`.
- Examples of invalid values: `"0"`, `"01"`, `"1.0"`, `"v1"`, `""`.
- Implementations SHOULD normalize `stdlib` internally to an integer major version.
Diagnostics:
- Missing `stdlib` is a manifest error.
- Invalid major-only format is a manifest error.
## 5. Ordinary Dependencies vs Stdlib Environment
### 5.1 Ordinary dependencies
Rules:
- `dependencies` model ordinary project relationships only.
- A dependency may be local or registry-based according to the compiler's dependency resolver.
- Dependencies contribute source projects, modules, and project-graph edges.
- `dependencies` do not declare stdlib projects.
### 5.2 Stdlib environment
Rules:
- The stdlib environment is not declared through `dependencies`.
- The stdlib environment is selected through `stdlib`.
- `@sdk:*` and `@core:*` imports resolve against the stdlib environment selected for the build.
- The presence of stdlib modules does not imply automatic visibility in source.
- User code MUST still import stdlib modules explicitly through ordinary import syntax.
Example:
```pbs
import { Gfx, color } from @sdk:gfx;
let c: color = color.red;
Gfx.draw_pixel(1, 1, c);
```
Rules:
- `Gfx` is not implicitly in scope.
- `Gfx` becomes visible only through `import`.
- The compiler accepts that import because the selected stdlib environment exposes `@sdk:gfx`.
## 6. Effective Stdlib of the Build
The root project owns the effective stdlib line of the build.
Rules:
- The resolved workspace has exactly one effective stdlib major version.
- The effective stdlib major version is taken from the root project manifest.
- All projects in the workspace compile under that same effective stdlib line.
- Dependency projects do not activate separate stdlib environments for themselves.
This means:
- `stdlib` on a dependency is a compatibility declaration,
- not an instruction to switch the compiler into another stdlib mode for that dependency.
## 7. Stdlib Compatibility Across Dependency Projects
Let:
- `R` be the root project's `stdlib` major,
- `D` be a dependency project's `stdlib` major.
Rules:
- If `D > R`, dependency resolution MUST fail with a deterministic compile-time error.
- If `D <= R`, dependency resolution MAY proceed.
- `D <= R` does not guarantee semantic compatibility of all APIs used by the dependency; it only means the dependency is not asking for a newer stdlib line than the root selected.
Rationale:
- the build target is chosen by the root project,
- dependency projects may target the same or an older stdlib line,
- dependency projects must not force the build to silently adopt a newer stdlib than the root requested.
Example:
- root `stdlib = "1"`, dependency `stdlib = "2"`: error.
- root `stdlib = "2"`, dependency `stdlib = "1"`: allowed.
- root `stdlib = "1"`, dependency `stdlib = "1"`: allowed.
## 8. Import Resolution
### 8.1 Resolution sources
The compiler resolves imports against exactly two sources:
1. the selected stdlib environment,
2. the resolved ordinary project dependency graph.
Rules:
- `@sdk:*` and `@core:*` are resolved only against the stdlib environment,
- all other `@project:*` imports are resolved only against the ordinary dependency graph,
- there is no fallback from reserved stdlib resolution to ordinary dependencies,
- there is no fallback from ordinary dependency resolution to reserved stdlib spaces.
### 8.2 Resolution algorithm
For an import:
```pbs
import { X } from @project:path/to/module;
```
the compiler MUST:
1. parse the project space and module path,
2. determine whether the project space is reserved,
3. if reserved, resolve the module from the selected stdlib environment,
4. otherwise, resolve the module from the root project or its dependency graph,
5. load the target module,
6. resolve the requested exported names from that module.
Failure at any step is a deterministic compile-time error.
## 9. Stdlib Interface Modules
### 9.1 Interface-module model
The selected stdlib environment MUST provide its modules as PBS-like interface modules.
Rules:
- Stdlib modules are `.pbs` modules loaded by the compiler.
- Stdlib interface modules use the same parser surface as ordinary PBS modules.
- Stdlib interface modules are interpreted in interface-module mode.
- Interface-module mode is non-executable and compile-time only.
- Interface modules participate in import resolution and type checking.
- Interface modules do not emit executable bytecode by themselves.
### 9.2 Allowed role
At minimum, an interface module may provide:
- exported names,
- types,
- enums,
- host owners,
- method signatures,
- compile-time metadata such as canonical host-binding attributes.
This list fixes the currently required declarative role of interface modules, but does not by itself freeze the final complete declaration set allowed in interface-module mode.
An interface module is not runtime code.
### 9.3 Interface-module restrictions
At minimum, an interface module MUST remain declarative.
Rules:
- Interface modules MUST NOT contain top-level executable statements.
- Interface modules MUST NOT require runtime initialization.
- Interface modules MUST NOT introduce executable method bodies that would emit bytecode.
- `declare host` is permitted only in reserved stdlib/toolchain interface modules.
- Reserved attributes such as `[Host(...)]` are permitted only where another specification explicitly allows them.
### 9.4 Example interface module
Illustrative stdlib interface module:
```pbs
declare enum color(red, green, blue);
declare host Gfx {
[Host(module = "gfx", name = "draw_pixel", version = 1)]
fn draw_pixel(x: int, y: int, c: color);
}
```
Rules:
- This module is valid only in a reserved stdlib/interface-module context.
- It contributes compile-time symbols and metadata.
- It does not produce executable bytecode by itself.
## 10. Compiler Loading of the Stdlib Environment
The compiler loads the stdlib environment from the stdlib line selected by the root project.
Required model:
1. Read the root `prometeu.json`.
2. Determine the effective stdlib major line.
3. Mount or select the matching stdlib environment.
4. Expose its reserved project spaces such as `@sdk:*` and `@core:*`.
5. Load interface modules from that environment on demand during import resolution.
6. Parse those modules with the ordinary PBS parser.
7. Validate them under interface-module semantic rules.
8. Populate the compiler's symbol graph from their exported declarations and attributes.
Rules:
- The compiler MUST behave as if it were loading real modules, not hardcoded symbol tables.
- The physical storage format of the stdlib environment is an implementation detail.
- The compiler MAY load the stdlib environment from disk, embedded resources, a virtual filesystem, or another implementation-defined source with equivalent behavior.
- For the Studio PBS frontend, embedding stdlib interface modules under frontend `resources` is a valid implementation strategy.
## 11. Reserved Attributes and Metadata Lifecycle
### 11.1 General rule
Attributes are compile-time metadata, not runtime objects.
Rules:
- Attributes are parsed as part of the source module.
- Attributes participate in declaration validation and compiler metadata extraction.
- Attributes are not exported as ordinary values, types, or runtime-reflectable objects.
- Attributes do not automatically survive into bytecode, PBX, or runtime metadata.
### 11.2 `Host` attribute
The canonical reserved host-binding attribute is:
```pbs
[Host(module = "gfx", name = "draw_pixel", version = 1)]
```
Rules:
- `Host` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body.
- `Host` provides the canonical host primitive identity used by compiler lowering.
- `module` and `name` are string literals.
- `version` is a positive integer literal.
- The attribute surface itself is compile-time only.
### 11.3 Lowering effect
Although the attribute syntax itself is compile-time only, its semantic effect may be lowered.
Rules:
- The compiler consumes `Host` metadata while resolving host-backed SDK members.
- The compiler uses that metadata to emit runtime-facing host-binding declarations as defined by the Host ABI Binding specification.
- The compiler does not export the raw `[Host(...)]` syntax into runtime as a source-level attribute object.
In other words:
- the attribute is compile-time metadata,
- the lowered host-binding declaration is runtime-facing artifact metadata,
- they are not the same thing.
## 12. Relationship to `declare host`
Rules:
- `declare host` remains reserved to SDK/toolchain-controlled modules.
- Ordinary user-authored project modules do not declare canonical host bindings directly.
- User code consumes SDK exports through normal imports.
- SDK-facing surfaces such as `Gfx.draw_pixel(...)` are resolved by the compiler against the selected stdlib environment.
- Canonical host identity comes from reserved host-binding metadata such as `[Host(...)]`, not from the source spelling of the imported owner.
## 13. Project Publication and Distribution
Rules:
- Ordinary publication and dependency resolution operate at project granularity.
- A published project version contains one or more modules.
- Imports consume modules from a resolved project.
- The stdlib environment is distributed separately from ordinary project dependencies.
- The stdlib environment is selected by `stdlib`, not by `dependencies`.
## 14. Non-Goals
- Making stdlib modules implicitly visible without `import`.
- Treating the stdlib as an ordinary dependency in the workspace graph.
- Allowing each dependency project to activate its own stdlib line.
- Hardcoding stdlib symbols directly into the compiler without a module model.
- Runtime reflection over source-level attributes.
## 15. Open Items Deferred
The following remain intentionally deferred:
1. Exact on-disk distribution format of stdlib environment packs.
2. Registry/publication protocol details for ordinary projects.
3. Final diagnostics catalog for all import-resolution failures.
4. Full list of declarations allowed inside interface modules beyond the already-fixed reserved host surfaces.
## 16. Current Decision Summary
The current PBS design direction is:
1. `prometeu.json` declares `language` and `stdlib` separately.
2. A project is the unit described by `prometeu.json` and selected by `dependencies`.
3. A module is the unit selected by `import`.
4. Canonical module addresses use `@project:path/to/module`.
5. `@sdk:*` and `@core:*` are reserved stdlib project spaces.
6. The root project selects the effective stdlib line for the whole build.
7. Dependency projects with a higher stdlib requirement than the root are rejected.
8. Stdlib modules are loaded as PBS-like interface modules, not as ordinary dependencies.
9. Interface modules are compile-time-only and do not emit executable bytecode.
10. `declare host` remains reserved to stdlib/toolchain interface modules.
11. Reserved attributes such as `[Host(...)]` are compile-time metadata, not runtime objects.
12. The compiler consumes `Host` metadata to produce runtime-facing host-binding artifacts defined elsewhere.
@@ -1,377 +0,0 @@
# VM-owned vs Host-backed
Status: Draft v1 (Temporary)
Applies to: ownership classification of PBS-visible operations, runtime boundary selection, and the normative distinction between VM-defined semantics and host-provided services
## 1. Purpose
This document defines the normative distinction between:
- VM-owned operations,
- host-backed operations,
- and user-defined program operations.
Its purpose is to prevent semantic drift between:
- builtin language behavior,
- VM execution behavior,
- host/platform integration,
- and source-level surfaces that may look similar while belonging to different ownership domains.
This document exists because PBS must distinguish at least three different kinds
of callable behavior:
- program-owned functions,
- VM-owned intrinsic behavior,
- host-backed services.
Without this distinction, the language would conflate:
- builtin semantics with syscalls,
- source-level shells with runtime authority,
- and VM contracts with host capability-gated services.
## 2. Scope
This document defines:
- the ownership model for callable behavior visible to PBS programs,
- the normative difference between VM-owned and host-backed operations,
- the runtime boundary crossed by each operation category,
- the relationship between ownership and lowering form,
- the relationship between ownership and determinism,
- the relationship between ownership and capability checks,
- the relationship between ownership and loader resolution,
- and the classification rule used to decide whether a surface belongs to the VM or to the host.
This document does not define:
- the full parser grammar for builtin declarations,
- the full intrinsic registry binary format,
- the final PBX section numbering for intrinsic metadata,
- subsystem-specific host APIs such as GFX or AUDIO,
- or the complete dynamic semantics of every builtin type.
## 3. Authority and Precedence
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
3. `1. Language Charter.md`
4. `3. Core Syntax Specification.md`
5. `4. Static Semantics Specification.md`
6. `5. Manifest, Stdlib, and SDK Resolution Specification.md`
7. `6.2. Host ABI Binding and Loader Resolution Specification.md`
8. This document
If a rule here conflicts with higher-precedence authority, the higher-precedence
authority wins.
## 4. Normative Inputs
This document depends on, at minimum:
- `1. Language Charter.md`
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `5. Manifest, Stdlib, and SDK Resolution Specification.md`
- `6.2. Host ABI Binding and Loader Resolution Specification.md`
## 5. Core Ownership Model
PBS distinguishes three ownership categories for callable behavior.
### 5.1 Program-owned function
A program-owned function is authored by the program and compiled from a PBS body.
Properties:
- semantic ownership belongs to the program,
- execution stays inside the VM,
- source definition includes an executable body,
- runtime dispatch uses ordinary function-call machinery,
- authority does not depend on host capability grants.
### 5.2 VM-owned operation
A VM-owned operation is part of the semantic contract of the PBS platform.
Properties:
- semantic ownership belongs to the VM platform,
- execution stays inside the VM,
- behavior is not defined by user-authored PBS bodies,
- behavior is not resolved against host registries,
- behavior is not granted or denied by host capabilities,
- and behavior is expected to remain semantically canonical across conforming implementations.
VM-owned operations include, at minimum:
- intrinsic operations over builtin types,
- compiler-recognized intrinsic method-call surfaces over core semantic forms,
- and other future VM-defined semantic helpers explicitly designated by spec.
### 5.3 Host-backed operation
A host-backed operation is provided by the runtime environment outside the VM's
closed semantic domain.
Properties:
- semantic authority belongs to the host platform,
- execution crosses the VM-to-host boundary,
- resolution uses canonical host identity,
- loader validation and capability checks are required before execution,
- and the final executable form is numeric host dispatch.
Host-backed operations are the domain of `declare host`, PBX `SYSC`, loader
resolution, and final `SYSCALL`.
## 6. The Boundary Question
The normative classification question is:
```text
Does this operation belong to the VM's semantic contract, or does it require a
service owned by the external host platform?
```
Rules:
- If the operation expresses builtin language or VM semantics, it is VM-owned.
- If the operation requires host-provided authority, devices, or platform services, it is host-backed.
- If the operation is implemented by ordinary source code in the current program, it is program-owned.
Heuristic:
- if the operation must still have a complete meaning in a host-minimal VM, it is VM-owned,
- if the operation loses meaning without external platform service, it is host-backed.
Examples:
- `Vec2.dot(other)` is VM-owned,
- `Color.rgb(r, g, b)` is VM-owned,
- `optional.hasSome()` is VM-owned,
- `enumValue.name()` is VM-owned,
- `Gfx.draw_pixel(x, y, c)` is host-backed,
- `Input.is_pressed(button)` is host-backed.
## 7. Runtime Boundary and Resolution Model
### 7.1 VM-owned operations
VM-owned operations do not cross the host boundary.
Rules:
- they do not resolve through the host syscall registry,
- they do not emit `SYSC`,
- they do not require loader-side capability checks,
- they are not represented by `declare host`,
- and they execute through VM-owned machinery such as intrinsic dispatch or other VM-defined execution paths.
### 7.2 Host-backed operations
Host-backed operations cross the VM boundary and require host authority.
Rules:
- they resolve by canonical host identity `(module, name, version)`,
- they are represented in source through reserved host-binding surfaces,
- they emit PBX host-binding metadata,
- they are validated against authoritative host metadata during load,
- and they execute in final form through `SYSCALL`.
## 8. Semantic Authority
The semantic owner of an operation is the layer that defines its normative
meaning.
### 8.1 VM-owned semantic authority
For VM-owned operations:
- the VM platform defines the operation's meaning,
- the frontend may expose shell declarations but does not define behavior,
- the host runtime must not redefine the operation's language-level semantics,
- and the HAL may consume produced values but must not own their semantic definition.
### 8.2 Host-backed semantic authority
For host-backed operations:
- the host platform defines the authoritative service identity and ABI,
- the frontend exposes a compile-time shell only,
- the loader resolves the shell's canonical identity against the host registry,
- and the VM executes only the numeric form after loader patching.
## 9. Determinism and Environmental Dependence
Determinism requirements differ by ownership category.
### 9.1 VM-owned operations
VM-owned operations must not derive meaning from host service behavior.
Rules:
- a VM-owned operation must not call the host as part of its semantic definition,
- a VM-owned operation must not require host capability grants,
- a VM-owned operation must not depend on wall-clock time unless a higher-precedence authority explicitly allows it,
- a VM-owned operation must not depend on frontend-generated helper algorithms for its canonical behavior,
- and the VM contract must be specific enough that conformance can test its behavior.
This does not require every VM-owned operation to be mathematically pure.
It does require the operation's meaning to be owned and specified by the VM
contract rather than delegated to the host.
### 9.2 Host-backed operations
Host-backed operations may depend on host state, devices, permissions, or
platform policy.
Rules:
- host-backed operations may be denied by capability policy,
- host-backed operations may vary by platform implementation within their ABI contract,
- and host-backed operations are not reclassified as VM-owned merely because the source surface resembles an ordinary method call.
## 10. Artifact Implications
Ownership classification determines artifact form.
### 10.1 Program-owned function artifact direction
Program-owned functions lower to ordinary program call machinery.
### 10.2 VM-owned artifact direction
VM-owned operations lower to VM-facing artifacts.
Illustrative forms:
- direct intrinsic ids such as `INTRINSIC <id>`,
- temporary intrinsic declaration tables plus pre-resolution callsites,
- or other VM-internal runtime forms explicitly defined by future spec.
Rules:
- VM-owned operations must not be encoded as host-binding metadata merely because they are not authored in user code,
- and VM-owned operations must not require host registry lookup.
### 10.3 Host-backed artifact direction
Host-backed operations lower to host-facing artifacts.
Rules:
- host-backed operations emit host-binding declarations into `SYSC`,
- host-backed callsites use `HOSTCALL <sysc_index>` before load,
- the loader resolves and patches those callsites,
- and final execution uses `SYSCALL <id>`.
## 11. Source Surface Similarity Does Not Collapse Ownership
Two source surfaces may look similar while belonging to different ownership
domains.
Examples:
- `Vec2.length()` may be VM-owned,
- `Gfx.clear(color)` may be host-backed,
- `value.name()` over an enum may be VM-owned,
- and `service.method()` may be program-owned or service-owned ordinary PBS behavior.
Rules:
- source-level method-call syntax does not determine ownership,
- declaration shape does not determine ownership,
- ownership is determined by semantic authority and runtime boundary,
- and toolchain metadata must classify the operation explicitly where ambiguity could arise.
## 12. Relationship to `declare host`
`declare host` is reserved exclusively for host-backed surfaces.
Rules:
- `declare host` must not be reused to model VM-owned builtin semantics,
- host attributes such as `Host(module, name, version)` must not be used to identify VM-owned intrinsic behavior,
- and a source surface that represents VM-owned behavior must use VM-specific metadata and lowering rules.
Rationale:
- `declare host` communicates external service ownership,
- host attributes communicate loader-facing canonical identity,
- and reusing them for VM-owned behavior would incorrectly imply host resolution, capability gating, and host semantic authority.
## 13. Relationship to Builtin Types and Intrinsics
Builtin types are VM-facing semantic types.
Rules:
- builtin types are not host APIs,
- builtin type operations that belong to the builtin domain are VM-owned,
- builtin constants, projections, constructors, and intrinsic methods are classified by VM semantics rather than by host service ownership,
- and builtin values may later be passed to host-backed operations without transferring semantic ownership of the type itself.
Example:
- `Color` is VM-owned as a semantic type,
- `Color.rgb(...)` is VM-owned,
- `Pixel` may contain `Color` in its builtin layout,
- `Gfx.draw_pixel(x, y, c)` is host-backed even when `c` has a VM-owned builtin type.
## 14. Relationship to `stdlib` and SDK Surfaces
`stdlib` and SDK packaging expose compile-time surfaces.
Rules:
- SDK or stdlib shells may expose both VM-owned and host-backed surfaces,
- shell placement alone does not determine runtime ownership,
- the runtime-facing artifact contract must preserve the true ownership category,
- and compile-time convenience must not collapse VM-owned and host-backed operations into the same runtime mechanism.
## 15. Classification Checklist
When introducing a new callable surface, the spec author or toolchain author
must answer at least these questions:
1. Who owns the semantic meaning of this operation?
2. Does the operation require host-provided authority, devices, or policy?
3. Must the loader resolve the operation against an external registry?
4. Can the operation be denied by capabilities?
5. Should the operation continue to exist with complete meaning in a host-minimal VM?
6. Is the operation part of builtin language semantics rather than platform service integration?
Classification rule:
- If answers 2, 3, or 4 are yes, the operation is host-backed.
- If answer 6 is yes and 2, 3, and 4 are no, the operation is VM-owned.
- Otherwise the operation is program-owned unless another spec defines a distinct category.
## 16. Conformance Expectations
Conforming implementations must preserve the ownership boundary.
Rules:
- an implementation must not lower VM-owned builtin semantics through the host syscall pipeline,
- an implementation must not treat host-backed operations as if they were VM-defined intrinsic semantics,
- an implementation must preserve the loader-facing host-binding contract for host-backed surfaces,
- and an implementation must preserve VM-facing semantic ownership for builtin and intrinsic operations.
## 17. Current Decision Summary
The current model is:
1. Program-authored functions are program-owned and execute through ordinary call machinery.
2. Builtin semantics and intrinsic behavior are VM-owned.
3. External platform services are host-backed.
4. VM-owned behavior must not be modeled as `declare host`.
5. Host-backed behavior must continue to use canonical host identity, `SYSC`, loader resolution, and final `SYSCALL`.
6. Ownership is determined by semantic authority and runtime boundary, not by source-level syntax resemblance.
@@ -1,555 +0,0 @@
# Intrinsics and Builtin Types Specification
Status: Draft v1 (Temporary)
Applies to: builtin type declarations, builtin constants, intrinsic member surfaces, builtin layout metadata, lowering direction, and artifact-facing intrinsic contracts
## 1. Purpose
This document defines the PBS-facing contract for:
- VM-owned builtin types,
- VM-owned intrinsic operations,
- and source-level shells that expose those features to PBS programs.
Its purpose is to let the frontend expose builtin semantic types such as
`Vec2`, `Color`, and `Pixel` as first-class language types while preserving
three invariants:
- semantic ownership remains with the VM,
- builtin values have canonical stack layout,
- and builtin domain behavior does not drift into host bindings or frontend helper code.
## 2. Scope
This document defines:
- the source-level shell model for `declare builtin type`,
- the canonical metadata carried by builtin type declarations,
- builtin constants declared through reserved metadata,
- builtin field layout and projection rules,
- admissible field types for builtin layouts,
- intrinsic member metadata and owner inheritance,
- lowering categories for builtin declarations and members,
- and the runtime-facing artifact direction for intrinsic operations.
This document does not define:
- the full final parser grammar integration into `3. Core Syntax Specification.md`,
- the final PBX section numbering for intrinsic declarations,
- the full VM intrinsic registry binary format,
- user-extensible builtin types,
- or heap-backed builtin layouts.
## 3. Authority and Precedence
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
3. `1. Language Charter.md`
4. `3. Core Syntax Specification.md`
5. `4. Static Semantics Specification.md`
6. `5. Manifest, Stdlib, and SDK Resolution Specification.md`
7. `6.2. Host ABI Binding and Loader Resolution Specification.md`
8. `6. VM-owned vs Host-backed.md`
9. This document
If a rule here conflicts with higher-precedence authority, the higher-precedence
authority wins.
## 4. Normative Inputs
This document depends on, at minimum:
- `1. Language Charter.md`
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `5. Manifest, Stdlib, and SDK Resolution Specification.md`
- `6.2. Host ABI Binding and Loader Resolution Specification.md`
- `6. VM-owned vs Host-backed.md`
- `12. IR and Lowering Specification.md`
- `15. Bytecode and PBX Mapping Specification.md`
## 5. Core Model
### 5.1 Builtin type
A builtin type is a VM-owned semantic type whose language-visible identity is
not authored by ordinary user code.
Properties:
- the type is first-class in the PBS type system,
- the type has canonical layout metadata,
- the type may expose field-like projection surfaces,
- the type may expose intrinsic member-call surfaces,
- and the type's semantic meaning is owned by the VM rather than by `stdlib`, SDK packaging, or the host.
### 5.2 Builtin declaration shell
`declare builtin type` is a reserved shell declaration.
Properties:
- it exists for binding, checking, lowering, and artifact emission,
- it has no user-authored executable body,
- and it does not transfer semantic ownership away from the VM registry.
### 5.3 Builtin constant
A builtin constant is a VM-owned named value exposed to source through a
reserved top-level `declare const` shell carrying builtin metadata.
### 5.4 Intrinsic operation
An intrinsic operation is a VM-owned callable behavior with canonical
definition in the VM contract.
## 6. Reserved Surface Forms
This document temporarily defines the intended source-level shell shape.
Final parser integration belongs to `3. Core Syntax Specification.md`.
### 6.1 Builtin type shell
Illustrative form:
```pbs
[BuiltinType(name="vec2", version=1)]
declare builtin type Vec2(
[Slot(0)] pub x: float,
[Slot(1)] pub y: float,
) {
[IntrinsicCall(name="dot")]
fn dot(other: Vec2) -> float;
[IntrinsicCall(name="length")]
fn length() -> float;
}
```
### 6.2 Builtin constant shell
Illustrative form:
```pbs
[BuiltinConst(target="vec2", name="zero", version=1)]
declare const ZERO: Vec2;
```
## 7. `BuiltinType` Metadata
`BuiltinType` declares the canonical VM-facing identity of a builtin type.
Required fields:
- `name`
- `version`
Rules:
- the declaration name after `declare builtin type` is the PBS-visible type name,
- `BuiltinType.name` is the canonical VM identity name,
- `BuiltinType.version` is the canonical semantic version of that builtin contract,
- the VM identity name need not equal the PBS-visible type name,
- and the pair `(name, version)` is the canonical builtin type identity in v1.
Example:
- source-visible name: `Vec2`
- canonical builtin identity: `("vec2", 1)`
## 8. Declaration Form and Structural Rules
`declare builtin type` uses a field-list surface similar to nominal aggregate
declarations.
Rules:
- `declare builtin type` is reserved to SDK/toolchain-controlled modules,
- ordinary user-authored modules must reject it,
- the declaration introduces a type name in the type namespace,
- the parenthesized member list declares builtin field projections,
- the body may contain signatures only,
- the body must not contain executable PBS statements,
- builtin members must not declare PBS bodies,
- and builtin declarations must not be used to encode ordinary user-defined structs.
This surface is intentionally shell-like.
The declaration is not the implementation authority for builtin behavior.
## 9. Builtin Fields Are Projections, Not Ordinary Storage Fields
The field-like entries in a builtin declaration describe named projections over a
canonical VM layout.
Rules:
- they are not ordinary user-defined struct fields,
- their names are visible for projection syntax such as `value.x`,
- they describe a canonical flattened layout order,
- and their meaning is projection over VM-owned builtin value representation.
Consequences:
- a builtin field declaration does not imply ordinary mutability semantics,
- a builtin field declaration does not imply that builtin values are structs,
- and a builtin field declaration does not allow user code to provide storage-level implementation bodies.
## 10. `Slot` Metadata
`Slot(n)` identifies the starting flattened slot offset of a builtin field within
the enclosing builtin layout.
Rules:
- `n` is zero-based,
- `Slot(n)` refers to the starting slot offset after flattening nested builtin-layout-admissible fields,
- slot offsets must be unique,
- slot offsets must match the declaration's canonical flattened layout,
- and overlapping slot ranges are invalid.
`Slot` exists to make canonical layout explicit.
Future grammar may allow offset inference by declaration order, but explicit slot
metadata is valid and authoritative in this temporary contract.
## 11. Builtin Layout Admissibility
Builtin field types are restricted.
A type is builtin-layout-admissible when it has:
- fixed width in slots,
- finite flattened layout,
- stack-only representation in this feature set,
- and canonical VM-owned layout metadata.
In v1 temporary scope, builtin-layout-admissible types are:
- predeclared builtin scalar types whose runtime contract defines fixed slot width,
- and declared builtin types whose own layout is fixed, finite, and stack-only.
The following are not builtin-layout-admissible unless a future spec explicitly
changes the rule:
- user-declared structs,
- services,
- contracts,
- callbacks,
- `optional`,
- `result`,
- and any type with runtime-variable or heap-defined width.
## 12. Nested Builtin Layout and Flattening
Builtin fields may refer to other builtin-layout-admissible types.
Rules:
- nested builtin field types flatten recursively into the enclosing layout,
- the enclosing builtin layout is the concatenation of its fields' flattened layouts in slot order,
- a nested field retains its nominal field identity for projection purposes,
- and verifier-facing slot widths are computed from the fully flattened layout.
Example:
```pbs
[BuiltinType(name="color", version=1)]
declare builtin type Color(
[Slot(0)] pub raw: int,
);
[BuiltinType(name="pixel", version=1)]
declare builtin type Pixel(
[Slot(0)] pub x: int,
[Slot(1)] pub y: int,
[Slot(2)] pub color: Color,
);
```
Canonical semantic layout:
```text
Pixel -> [int, int, Color]
```
Canonical flattened slot layout:
```text
Pixel -> [int, int, int]
```
## 13. Member Categories
Builtin members belong to one of the following semantic categories:
1. projection surface,
2. builtin constant surface,
3. layout-only constructor or factory surface,
4. intrinsic call surface.
This document normatively defines projection, builtin constants, and intrinsic
call surfaces.
Layout-only constructors may be introduced by future syntax or by existing
constructor lowering rules, but their implementation remains VM-facing rather
than host-backed.
## 14. `IntrinsicCall` Metadata
`IntrinsicCall` identifies a VM-owned callable member over builtin semantics.
Required fields:
- `name`
Optional fields:
- `version`
Rules:
- `IntrinsicCall` is valid only on method signatures declared inside a `declare builtin type` body,
- the enclosing `BuiltinType` provides the default intrinsic owner identity,
- `IntrinsicCall.name` is the canonical intrinsic operation name within that owner,
- if `IntrinsicCall.version` is omitted, it inherits the enclosing builtin type version,
- if `IntrinsicCall.version` is present, it overrides only the operation version,
- and `IntrinsicCall` must not be interpreted as host-binding metadata.
Canonical intrinsic identity in v1 is:
```text
(owner, name, version)
```
where:
- `owner` is inherited from `BuiltinType.name`,
- `name` is taken from `IntrinsicCall.name`,
- and `version` is inherited or overridden as above.
Example:
```pbs
[BuiltinType(name="vec2", version=1)]
declare builtin type Vec2(
[Slot(0)] pub x: float,
[Slot(1)] pub y: float,
) {
[IntrinsicCall(name="dot")]
fn dot(other: Vec2) -> float;
}
```
declares canonical intrinsic identity:
```text
("vec2", "dot", 1)
```
## 15. `BuiltinConst` Metadata
`BuiltinConst` identifies a VM-owned named constant surface.
Required fields:
- `target`
- `name`
- `version`
Rules:
- `BuiltinConst` is valid only on reserved top-level `declare const` shells,
- `target` identifies the canonical builtin owner name,
- `name` identifies the canonical constant name within that builtin owner,
- `version` identifies the constant contract version,
- the declared PBS constant name is source-visible and may differ from the canonical constant name,
- and builtin constants are VM-owned declarations, not host bindings.
Example:
```pbs
[BuiltinConst(target="vec2", name="zero", version=1)]
declare const ZERO: Vec2;
```
declares a source-visible constant `ZERO` whose canonical builtin constant
identity is:
```text
("vec2", "zero", 1)
```
## 16. Static Semantics
The following static rules apply.
### 16.1 Namespace rules
Rules:
- `declare builtin type` introduces a nominal type name in the type namespace,
- builtin type names participate in visibility and import rules like other reserved type declarations,
- ordinary user-authored type declarations must not redeclare visible builtin type names in the same scope,
- and builtin constants declared through `declare const` introduce names in the value namespace.
### 16.2 Member lookup rules
Rules:
- `expr.field` is valid when `expr` has a builtin type declaring a projection field named `field`,
- the projected type is the field's declared type,
- `expr.method()` is valid when the builtin type declares a matching intrinsic member surface,
- and missing builtin fields or members are compile-time errors.
### 16.3 Body restrictions
Rules:
- builtin declarations have no executable member bodies,
- builtin methods are signature-only shells,
- builtin constants are declaration-only shells,
- and ordinary user code must not implement builtin semantics in PBS bodies.
## 17. Lowering Model
Builtin shells guide lowering; they do not supply executable implementation.
### 17.1 Projection lowering
Projection over builtin fields lowers to canonical projection over flattened
layout.
Rules:
- field projection does not imply host interaction,
- field projection does not emit `SYSC`,
- field projection may lower to direct stack projection, reshaping operations, or another VM-owned form,
- and the projected semantics are determined by builtin layout metadata.
### 17.2 Builtin constant lowering
Builtin constants lower to VM-owned constant materialization.
Rules:
- builtin constants must not lower through host binding resolution,
- builtin constants may lower to direct value materialization, VM-owned constant pool lookup, or intrinsic-like constant fetch,
- and the canonical constant identity determines which VM-owned value is materialized.
### 17.3 Intrinsic method lowering
Intrinsic methods lower to VM-owned intrinsic call behavior.
Rules:
- intrinsic methods must not lower through `SYSC`,
- intrinsic methods must not emit `HOSTCALL`,
- intrinsic method identities lower from `(owner, name, version)` metadata,
- and the runtime-facing call form is VM-facing rather than host-facing.
## 18. Artifact Direction
This feature requires a distinct intrinsic artifact path.
Illustrative final executable form:
```text
INTRINSIC <id>
```
Illustrative optional pre-resolution form:
```text
INTRCALL <decl_index>
```
with declaration metadata carrying:
```text
(owner, name, version)
```
Rules:
- implementations may emit final `INTRINSIC <id>` directly when intrinsic ids are stable for the targeted VM contract,
- implementations may emit declaration-based intrinsic callsites when a preload resolution step is desired,
- any such intrinsic declaration path remains VM-facing and must not reuse host-binding metadata,
- and intrinsic artifacts are distinct from `SYSC`, `HOSTCALL`, and `SYSCALL`.
## 19. Verifier Obligations
The verifier must treat intrinsics and builtin layouts as first-class structural
facts.
Rules:
- each builtin type has a known flattened slot width,
- each intrinsic has known argument and result layouts,
- verifier stack effects are computed from flattened layouts rather than only from source spellings,
- and verifier reasoning must preserve nominal builtin type identity even when two builtin layouts occupy the same slot width.
Example:
```text
Vec2.dot(Vec2, Vec2) -> float
```
If `Vec2` flattens to two float-width slots, the verifier-facing stack effect is:
```text
pop 4, push 1
```
## 20. Determinism and Ownership Rules
Builtin and intrinsic semantics are VM-owned.
Rules:
- builtin operations must not rely on host registry resolution,
- builtin operations must not require runtime capability grants,
- builtin operations must not be specified merely as frontend helper code,
- and builtin operations must remain within the VM-owned category defined by `6. VM-owned vs Host-backed.md`.
## 21. Relationship to `stdlib` and SDK Packaging
`stdlib` and SDK packaging may expose builtin declarations as compile-time
surfaces.
Rules:
- packaging location does not make builtin semantics host-backed,
- source modules may import builtin shells from reserved stdlib surfaces,
- the shell remains descriptive rather than semantically authoritative,
- and the VM contract remains the owner of builtin identities, layouts, constants, and intrinsic behavior.
## 22. Deterministic Static Errors
At minimum, a conforming implementation must reject:
1. `declare builtin type` in an ordinary user-authored module,
2. missing required `BuiltinType` metadata on a builtin declaration,
3. duplicate builtin field names within one declaration,
4. duplicate or overlapping slot assignments,
5. builtin field types that are not builtin-layout-admissible,
6. `IntrinsicCall` used outside a builtin declaration body,
7. `BuiltinConst` used outside a reserved top-level `declare const` shell,
8. duplicate canonical builtin type identities in the same compilation environment,
9. duplicate intrinsic canonical identities within the same builtin owner and version line,
10. mismatched declared field slot metadata versus flattened layout,
11. executable member bodies inside builtin declarations,
12. any lowering that routes VM-owned builtin operations through the host-binding pipeline.
## 23. Current Decision Summary
The current temporary contract is:
1. Builtin types are VM-owned semantic types exposed through reserved shell declarations.
2. `BuiltinType(name, version)` maps source-visible type names to canonical VM builtin identities.
3. Builtin fields describe projection surfaces over canonical flattened layout.
4. Builtin field types must be builtin-layout-admissible and stack-only in this feature set.
5. Builtin types may contain other builtin-layout-admissible types, including nested builtin composition such as `Pixel` containing `Color`.
6. `IntrinsicCall(name, version?)` identifies VM-owned intrinsic member behavior and inherits owner identity from the enclosing builtin type.
7. `BuiltinConst(target, name, version)` exposes VM-owned builtin constants through reserved top-level `declare const` shells.
8. Builtin projections, constants, and intrinsic calls must not lower through `SYSC`, `HOSTCALL`, or `SYSCALL`.
9. Runtime-facing intrinsic artifacts are distinct from host-binding artifacts.
@@ -1,426 +0,0 @@
# Host ABI Binding and Loader Resolution Specification
Status: Draft v1 (Temporary)
Applies to: PBX host-binding metadata, cartridge load, canonical syscall resolution, and loader-side capability gating
## 1. Purpose
This document defines the current contract between:
- the PBS compiler/toolchain,
- the PBX program artifact,
- the cartridge loader,
- and the host syscall registry.
Its purpose is to let compiler and runtime work in parallel without diverging on the most critical boundary:
how host-backed SDK calls become load-time-resolved numeric syscalls.
This document is intentionally narrower than a full PBX or VM specification.
It focuses on loader behavior and the minimum artifact contract the loader must consume.
## 2. Scope
This document defines:
- the canonical identity of a host binding,
- the relationship between `declare host` and canonical host bindings,
- the minimum PBX metadata required for load-time host resolution,
- the pre-load opcode form used for host-backed call sites,
- the required loader algorithm,
- the required loader patching step from pre-load host callsites to numeric syscalls,
- the division of responsibility between loader-side ABI checks and verifier-side stack checks,
- capability checks required during load,
- deterministic loader failures for malformed or unauthorized host usage,
- the requirement that VM execution remains numeric-only.
This document does not define:
- the full PBX module format,
- the exact in-memory patching strategy used by the loader,
- the publication format of stdlib SDK packs,
- the semantics of individual subsystems such as GFX or AUDIO.
## 3. Normative Inputs
This document follows two prior decisions:
1. Canonical host identity is defined by the hardware ABI as `(module, name, version)`.
2. User code does not declare host bindings directly; SDK/toolchain-controlled modules expose reserved `declare host` surfaces and the compiler lowers those usages into PBX host-binding metadata.
This document therefore treats:
- `declare host Gfx { fn draw_pixel(...); }`
as compile-time surface only, and treats:
- `("gfx", "draw_pixel", 1)`
as the normative runtime-facing identity.
## 4. Core Model
The host-binding pipeline is:
1. User code imports SDK surfaces such as `Gfx` from `@sdk:gfx`.
2. The compiler resolves those surfaces against the selected stdlib line.
3. The compiler maps each host-backed SDK member to a canonical identity `(module, name, version)`.
4. The compiler emits those required canonical identities into the PBX `SYSC` table.
5. The compiler emits pre-load host call sites as `HOSTCALL <sysc_index>`.
6. At cartridge load time, the loader resolves `SYSC` entries against the host syscall registry.
7. The loader verifies ABI compatibility and capabilities before execution starts.
8. The loader rewrites every `HOSTCALL <sysc_index>` into `SYSCALL <id>`.
9. The VM executes only numeric syscall identifiers.
The loader never resolves host bindings from source-level names such as `Gfx.draw_pixel`.
It resolves only canonical identities declared in the PBX.
## 5. Canonical Host Binding Identity
Every host binding is identified by the triple:
```text
(module, name, version)
```
Rules:
- `module` is the canonical host subsystem namespace, such as `gfx` or `audio`.
- `name` is the canonical host operation name within that module.
- `version` is the canonical ABI version of that host operation.
- This identity is stable across source languages and SDK naming styles.
- This identity is the only identity used by the loader for host resolution.
Source-level owners such as `Gfx` are SDK-facing aliases.
They are not loader-facing identities.
## 6. Relationship to `declare host`
`declare host` is a reserved SDK/toolchain surface used to expose host-backed APIs to source programs.
Rules:
- User-authored project modules do not declare canonical host bindings directly.
- `declare host` exists to define compile-time interface shape, not executable PBS bodies.
- The compiler is responsible for mapping each host-backed member to its canonical host identity.
- The PBX must not depend on source spellings such as `Gfx` for runtime resolution.
Example:
```pbs
import { Gfx, color } from @sdk:gfx;
let c: color = color.red;
Gfx.draw_pixel(1, 1, c);
```
The source-level call may originate from an SDK declaration such as:
```pbs
declare host Gfx {
[Host(module = "gfx", name = "draw_pixel", version = 1)]
fn draw_pixel(x: int, y: int, c: color);
}
```
but the PBX-facing declaration is canonical, for example:
```text
("gfx", "draw_pixel", 1)
```
## 7. PBX Host Binding Section
### 7.1 Temporary section contract
Until the full PBX host-binding format is stabilized elsewhere, the loader contract uses a dedicated PBX section for declared host bindings.
Temporary section identifier:
- `SYSC`
Meaning:
- the list of canonical host bindings required by the program.
This section is metadata only.
It does not define the executable opcode stream itself.
### 7.2 Temporary binary layout
The current temporary layout is:
```text
u32 count
repeat count times:
u16 module_len
[module_len bytes UTF-8]
u16 name_len
[name_len bytes UTF-8]
u16 version
u16 arg_slots
u16 ret_slots
```
Rules:
- strings are UTF-8,
- `module_len` and `name_len` are byte lengths,
- `arg_slots` is the slot count the compiler expects the host binding to consume,
- `ret_slots` is the slot count the compiler expects the host binding to produce,
- duplicate `(module, name, version)` entries are invalid,
- malformed lengths or invalid UTF-8 are load errors.
The `SYSC` table is:
- unique per program,
- deduplicated by canonical identity,
- ordered by first occurrence in the compiled program.
The loader MUST preserve the table order as emitted.
### 7.3 Presence requirements
The `SYSC` section is mandatory for every valid PBX artifact.
Rules:
- every valid `program.pbx` MUST contain a `SYSC` section,
- the loader MUST inspect `SYSC` before execution begins,
- an empty `SYSC` section is valid and means the program requires no host bindings,
- absence of `SYSC` is a deterministic load error,
- malformed or duplicate `SYSC` declarations are deterministic load errors.
Rationale:
- the Prometeu runtime is always host-aware,
- PBX structural uniformity is preferred over optional host-binding metadata,
- loader simplicity and deterministic testability take priority over omitting an empty section.
## 8. Loader Resolution Algorithm
The loader must perform host-binding resolution before VM execution starts.
Required algorithm:
1. Read the PBX header and section table.
2. Locate and parse the `SYSC` section before launching the VM.
3. Decode the declared canonical identities in source order.
4. Reject duplicate identities.
5. Resolve each identity against the host syscall registry.
6. For each resolved entry, verify that declared `arg_slots` and `ret_slots` match the authoritative host metadata.
7. Verify that the granted capability set covers every resolved binding.
8. Scan the executable bytecode for every `HOSTCALL <sysc_index>` instruction.
9. Reject any `HOSTCALL` whose `sysc_index` is out of bounds.
10. Reject any `SYSC` entry that is never referenced by a `HOSTCALL`.
11. Rewrite every `HOSTCALL <sysc_index>` into `SYSCALL <syscall_id>`.
12. Reject the loaded image if any `HOSTCALL` remains after the rewrite pass.
13. Produce the final executable program image.
14. Abort load deterministically if any step fails.
The loader must not defer canonical-name resolution until the first call site executes.
## 9. Host Registry Resolution
The host maintains a canonical syscall registry:
```text
(module, name, version) -> syscall_id + metadata
```
That metadata includes, at minimum:
- numeric syscall identifier,
- canonical identity,
- argument slot count,
- return slot count,
- required capabilities.
Rules:
- the loader resolves only against this canonical registry,
- unknown identities are load errors,
- successful resolution yields numeric syscall identifiers and associated metadata,
- the resolved metadata is authoritative for capability gating and later runtime verification.
## 10. Pre-Load Callsite Form
The compiler emits host-backed call sites in pre-load form as:
```text
HOSTCALL <sysc_index>
```
Rules:
- `sysc_index` is a zero-based index into the program's `SYSC` table,
- every host-backed call site in PBX code must use `HOSTCALL`, not `SYSCALL`,
- `HOSTCALL` exists only in the pre-load artifact form,
- `HOSTCALL` must not remain in the final executable image passed to the VM.
Rationale:
- the compiler does not know final numeric syscall identifiers,
- the loader resolves by canonical identity and materializes the numeric form,
- the verifier and VM can stay numeric-only after the patch step.
## 11. Loader-Side ABI Validation
Load-time ABI validation is mandatory.
Rules:
- every `SYSC` entry declares `arg_slots` and `ret_slots`,
- the loader resolves the entry to authoritative host metadata,
- the loader MUST reject the image if declared `arg_slots` differs from host metadata,
- the loader MUST reject the image if declared `ret_slots` differs from host metadata.
This validation is not a replacement for bytecode verification.
It exists to detect mismatches between:
- the compiler's emitted host-binding contract,
- and the host registry contract actually present in the runtime.
## 12. Capability Gating
Capability gating is mandatory during load.
Rules:
- every resolved host binding declares required capabilities,
- the cartridge manifest declares requested capabilities using a nominal capability list,
- the loader derives or receives the granted capability set from the cartridge/platform policy environment,
- if a required capability is not granted, load fails,
- the loader must fail before the program begins execution.
The compiler may infer which capabilities are required by the emitted `SYSC` table, but it does not grant authority.
Authority belongs to the cartridge/platform loading environment.
Runtime capability checks may still exist defensively in the VM, but they do not replace mandatory load-time validation.
## 13. Verifier Interaction
The loader and the verifier validate different layers of the contract.
Loader responsibilities:
- validate canonical host identity resolution,
- validate `SYSC`-declared ABI shape against host metadata,
- validate capabilities,
- patch `HOSTCALL <sysc_index>` into `SYSCALL <id>`.
Verifier responsibilities:
- run on the already-patched executable image,
- validate stack safety and control-flow safety,
- treat `SYSCALL <id>` exactly like any other final numeric instruction,
- derive stack effects from authoritative runtime syscall metadata.
This is intentional and not considered harmful duplication:
- the loader checks interface compatibility,
- the verifier checks structural correctness of the final program.
## 14. Execution Model After Load
After successful load:
- the VM executes numeric syscall identifiers only,
- runtime dispatch must not depend on canonical strings,
- canonical names exist only in PBX metadata and loader-side resolution,
- the runtime-facing execution form remains `SYSCALL <id>`.
This preserves the hardware contract:
- canonical identity is used for declaration and linking,
- numeric identity is used for execution.
## 15. Deterministic Loader Errors
The loader must fail deterministically for at least the following cases:
1. missing `SYSC` section,
2. malformed `SYSC` payload,
3. invalid UTF-8 in canonical names,
4. duplicate `(module, name, version)` declarations,
5. unknown canonical identity,
6. ABI mismatch between `SYSC` declaration and host registry metadata,
7. capability mismatch,
8. `HOSTCALL` references an out-of-bounds `sysc_index`,
9. a declared `SYSC` entry is unused by all `HOSTCALL` instructions,
10. a `HOSTCALL` remains in the executable image after loader patching,
11. any internal inconsistency between parsed host-binding metadata and the loader's host registry contract.
Diagnostics should identify the failing canonical identity whenever available.
## 16. Relationship to `stdlib`
`stdlib` selection is a compile-time concern that determines which SDK surfaces and host-backed declarations the compiler may use.
Rules:
- the loader does not resolve source imports such as `@sdk:gfx`,
- the loader only consumes canonical host-binding metadata emitted into the PBX,
- `stdlib` affects the loader indirectly through what the compiler emitted,
- the loader must not attempt to reconstruct SDK/module semantics from the PBX.
In other words:
- `stdlib` selects the compile-time SDK contract,
- `SYSC` carries the runtime-facing host-binding contract.
## 17. Relationship to Cartridge Manifest Capabilities
The cartridge manifest is the current declarative source for requested runtime capabilities.
Rules:
- cartridge capability declarations are external to `program.pbx`,
- capability declarations are serializable nominal identifiers such as `gfx` or `audio`,
- the loader converts that nominal declaration into the internal capability flag set used by the runtime,
- the loader MUST NOT infer granted authority solely from the presence of `SYSC` entries.
This keeps authority separate from code generation:
- PBX declares what the program needs,
- cartridge packaging declares what the cartridge requests,
- the loader/runtime environment decides what is granted.
## 18. Current Implementation Direction
This document aligns with the current Prometeu direction:
- SDK/toolchain-controlled `declare host` surfaces define host-backed APIs,
- the compiler emits canonical host-binding declarations into PBX `SYSC`,
- the compiler emits `HOSTCALL <sysc_index>` in pre-load code,
- the loader resolves those declarations at cartridge load,
- the loader patch-rewrites host calls to numeric syscalls,
- the VM continues to execute numeric syscalls only.
## 19. Open Items Deferred
The following remain deferred:
1. final PBX section numbering and chunk registry policy,
2. exact binary opcode allocation for `HOSTCALL`,
3. whether the loader patches bytecode in place or rebuilds a fresh executable image buffer,
4. final cartridge policy model when platform-level grants differ from manifest requests,
5. final chunk numbering and binary compatibility policy for PBX versions that predate mandatory `SYSC`,
6. final integration shape with `ProgramImage` or another loaded-program container.
## 20. Current Decision Summary
The current temporary contract is:
1. Host bindings are identified canonically by `(module, name, version)`.
2. `declare host` is reserved to SDK/toolchain modules and is compile-time surface only.
3. The compiler emits a unique, deduplicated `SYSC` table ordered by first occurrence.
4. Each `SYSC` entry carries `module`, `name`, `version`, `arg_slots`, and `ret_slots`.
5. The compiler emits host-backed call sites as `HOSTCALL <sysc_index>`.
6. The loader parses `SYSC` before execution.
7. The loader resolves canonical identities against the host registry during load.
8. The loader validates `arg_slots` and `ret_slots` against authoritative host metadata.
9. The loader enforces capability gating during load.
10. The loader rejects out-of-bounds and unused `SYSC` references.
11. The loader rewrites every `HOSTCALL <sysc_index>` into `SYSCALL <id>`.
12. The verifier runs after patching and validates the final numeric program.
13. The VM executes numeric syscall identifiers only.
@@ -1,246 +0,0 @@
# Cartridge Manifest and Runtime Capabilities Specification
Status: Draft v1 (Temporary)
Applies to: `manifest.json` in Prometeu cartridges, runtime capability declaration, and loader capability input
## 1. Purpose
This document defines the current cartridge manifest contract relevant to runtime loading.
Its purpose is to stabilize:
- the JSON surface consumed by the cartridge loader,
- the declaration of cartridge-requested runtime capabilities,
- the boundary between cartridge packaging and loader authority,
- the conversion from manifest-facing capability names to runtime capability flags.
This document is intentionally temporary and limited.
It does not define cartridge publishing, signing, or store policy.
## 2. Scope
This document defines:
- the role of `manifest.json` in cartridge loading,
- the current required manifest fields,
- the new `capabilities` field,
- the nominal capability enumeration used in JSON,
- the mapping from nominal capabilities to runtime `CapFlags`,
- the role of the loader when combining manifest capabilities with PBX `SYSC`.
This document does not define:
- the full package format beyond the current directory cartridge contract,
- policy UI or permission prompts,
- cartridge signing or trust chains,
- final platform grant policy when the host wants to reduce requested capabilities.
## 3. Current Cartridge Manifest Role
The cartridge manifest is an external load-time descriptor for a cartridge.
It is not compiled from PBS source directly.
It is produced by cartridge packaging tooling and consumed by the runtime loader.
The manifest currently carries:
- cartridge identity and metadata,
- app entry information,
- asset metadata,
- preload metadata.
This document adds runtime capability declaration to that same manifest.
## 4. Manifest Shape
The current manifest shape relevant to this document is:
```json
{
"magic": "PMTU",
"cartridge_version": 1,
"app_id": 1001,
"title": "Example",
"app_version": "1.0.0",
"app_mode": "game",
"entrypoint": "main",
"capabilities": ["gfx", "input"],
"asset_table": [],
"preload": []
}
```
Rules:
- `magic` identifies a Prometeu cartridge manifest,
- `cartridge_version` identifies the cartridge manifest format line,
- `entrypoint` identifies the runtime entrypoint,
- `capabilities` declares the cartridge's requested runtime capabilities,
- `asset_table` and `preload` remain separate concerns.
## 5. `capabilities`
### 5.1 General rules
`capabilities` is a manifest-facing nominal list.
Rules:
- `capabilities` is optional,
- when omitted, it behaves as an empty list,
- capability names are canonical lowercase identifiers,
- duplicate entries are invalid,
- unknown capability names are manifest errors.
### 5.2 Nominal capability set
The current nominal capability set is:
- `system`
- `gfx`
- `input`
- `audio`
- `fs`
- `log`
- `asset`
- `bank`
These names are the normative manifest-facing representation.
## 6. Relationship to Runtime `CapFlags`
The runtime may continue to represent capabilities internally as a bitflag set.
That internal representation is an implementation detail.
The normative external model is:
- a nominal capability enum in the manifest,
- deterministic conversion by the loader into runtime flags.
Canonical mapping:
- `system` -> `SYSTEM`
- `gfx` -> `GFX`
- `input` -> `INPUT`
- `audio` -> `AUDIO`
- `fs` -> `FS`
- `log` -> `LOG`
- `asset` -> `ASSET`
- `bank` -> `BANK`
This means the recommended runtime design is:
1. deserialize `capabilities` into a nominal enum or equivalent validated representation,
2. convert that validated set into internal `CapFlags`,
3. use those flags during host-binding resolution.
## 7. Loader Semantics
The loader consumes both:
- the cartridge manifest,
- and the PBX `SYSC` table.
Required behavior:
1. parse `manifest.json`,
2. parse `capabilities`,
3. convert the nominal capability list to internal capability flags,
4. parse `program.pbx`,
5. resolve each `SYSC` entry against the host registry,
6. obtain required capabilities from resolved syscall metadata,
7. fail if required capabilities are not granted by the manifest/policy environment.
The manifest alone does not make a program valid.
The manifest must be consistent with the actual syscalls required by the PBX.
## 8. Requested vs Granted Authority
The manifest declares requested cartridge capabilities.
The loader/runtime environment is the authority that decides what is granted.
Current direction:
- in the initial runtime model, the manifest may act as the immediate source of granted capabilities,
- a future platform policy layer may reduce or deny requested capabilities before final load.
Normative rule:
- the compiler does not grant capabilities,
- the PBX does not grant capabilities,
- cartridge/runtime loading is the authority boundary.
## 9. Relationship to Compiler and Packer
Responsibilities are split as follows:
Compiler:
- compiles source to PBX,
- emits `SYSC`,
- emits `HOSTCALL <sysc_index>`,
- does not grant authority.
Packer:
- produces the cartridge manifest,
- declares requested runtime capabilities,
- packages `manifest.json`, `program.pbx`, and assets.
Loader:
- reads the manifest,
- derives or receives granted capability flags,
- validates those capabilities against PBX host requirements.
## 10. Validation Rules
The cartridge manifest must fail validation if:
1. `capabilities` contains an unknown name,
2. `capabilities` contains duplicates,
3. `capabilities` is not an array of strings or nominal enum values under the chosen serialization form.
Cartridge load must fail if:
1. the manifest omits a capability required by a resolved `SYSC` entry,
2. a future platform policy denies a capability required by a resolved `SYSC` entry.
## 11. Serialization Guidance
The recommended manifest-facing model is a nominal enum list, not numeric masks.
Recommended JSON:
```json
{
"capabilities": ["gfx", "input", "audio"]
}
```
Rejected as normative surface:
- raw integer bitmasks,
- hex masks,
- unnamed positional arrays.
Rationale:
- nominal capability names are readable,
- manifest diffs remain understandable,
- packer and tooling validation is straightforward,
- runtime may still use bitflags internally after conversion.
## 12. Current Decision Summary
The current temporary contract is:
1. `manifest.json` is the cartridge-facing load descriptor.
2. `capabilities` is declared in `manifest.json`, not in `prometeu.json`.
3. `capabilities` uses nominal canonical names such as `gfx` and `audio`.
4. The runtime may keep using internal `CapFlags`.
5. The loader converts nominal manifest capabilities into internal flags.
6. PBX `SYSC` declares required host bindings, not authority.
7. Loader validation fails if PBX host requirements exceed granted cartridge capabilities.
@@ -1,251 +0,0 @@
# PBS Stdlib Environment Packaging and Loading Specification
Status: Draft v1 (Temporary)
Applies to: Studio PBS frontend stdlib packaging, stdlib environment discovery, reserved stdlib project spaces, and compiler-side stdlib loading abstractions
## 1. Purpose
This document defines a practical packaging and loading model for the PBS stdlib environment inside the Studio compiler frontend.
Its purpose is to make the stdlib:
- available to the compiler without hardcoded symbol tables,
- structured as real PBS interface modules,
- versioned by stdlib major line,
- and loadable through explicit compiler abstractions.
This document complements the normative language-level model in:
- [5. Manifest, Stdlib, and SDK Resolution Specification.md](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/studio/docs/specs/pbs/5.%20Manifest,%20Stdlib,%20and%20SDK%20Resolution%20Specification.md)
## 2. Scope
This document defines:
- the recommended Studio packaging layout for stdlib interface modules,
- the logical mapping between stdlib line, reserved project space, and module path,
- the minimum compiler abstractions required to load stdlib modules,
- the relationship between `resources` packaging and the logical stdlib environment.
This document does not define:
- runtime loader behavior,
- PBX emission,
- registry publication of stdlib packs,
- final external distribution of stdlib outside Studio.
## 3. Core Model
The compiler must load stdlib modules as real interface modules, not as hardcoded built-ins.
Rules:
- the stdlib is selected by the root project's `stdlib` major,
- each stdlib line defines one stdlib environment,
- a stdlib environment exposes reserved project spaces such as `@sdk:*` and `@core:*`,
- each reserved project space contains one or more modules,
- each module is represented as PBS source plus `mod.barrel`.
## 4. Recommended Studio Packaging Layout
The recommended Studio layout is:
```text
prometeu-compiler/frontends/prometeu-frontend-pbs/
src/main/resources/
stdlib/
1/
sdk/
gfx/
main.pbs
mod.barrel
audio/
main.pbs
mod.barrel
core/
math/
main.pbs
mod.barrel
```
Interpretation:
- `stdlib/1` selects stdlib major line `1`,
- `sdk` and `core` are reserved project spaces,
- `gfx`, `audio`, `math` are module paths within those reserved spaces,
- `main.pbs` and `mod.barrel` form the interface module contents.
## 5. Logical Mapping
The compiler must treat the physical layout as a logical stdlib environment.
Required mapping:
- `stdlib/<N>/sdk/gfx` -> `@sdk:gfx`
- `stdlib/<N>/sdk/audio` -> `@sdk:audio`
- `stdlib/<N>/core/math` -> `@core:math`
- `stdlib/<N>/core/math/vector` -> `@core:math/vector`
Rules:
- physical storage is an implementation detail,
- logical module identity is authoritative,
- callers of the resolver should work with logical addresses such as `@sdk:gfx`, not resource paths.
## 6. Module File Convention
For the Studio implementation, each stdlib module should follow the same structural convention as ordinary PBS modules:
- one or more `.pbs` files,
- exactly one `mod.barrel`.
Recommended minimum convention:
- `main.pbs`
- `mod.barrel`
Rules:
- `main.pbs` is a convention, not a language-level requirement,
- the module remains an ordinary PBS module from the parser's perspective,
- it is interpreted under interface-module semantics because it lives in a reserved stdlib project space.
## 7. Required Compiler Abstractions
The compiler should not reach directly into `resources` paths throughout the frontend.
At minimum, the PBS frontend should define abstractions equivalent to:
### 7.1 `StdlibEnvironment`
Responsibility:
- represent the selected stdlib line for one compilation,
- expose reserved project spaces,
- provide access to interface modules by logical module address.
Minimum operations:
- select stdlib major line,
- answer whether a reserved project space exists,
- open a module by logical address.
### 7.2 `StdlibModuleResolver`
Responsibility:
- resolve logical imports in reserved project spaces,
- map `@sdk:*` and `@core:*` imports to concrete interface module sources,
- reject unknown stdlib modules deterministically.
Minimum operations:
- `resolve(@sdk:gfx)`
- `resolve(@core:math/vector)`
### 7.3 `StdlibModuleSource`
Responsibility:
- represent the source files of one stdlib module,
- provide access to the module's `.pbs` files and `mod.barrel`,
- hide whether content came from disk, `resources`, or another source.
Minimum contents:
- module address
- list of `.pbs` source texts or streams
- `mod.barrel` source text or stream
### 7.4 `InterfaceModuleLoader`
Responsibility:
- parse a stdlib module source using the normal PBS parser,
- validate it in interface-module mode,
- return compiler-facing symbols and metadata.
Minimum outputs:
- exported symbols
- declared types
- host owners
- host method signatures
- reserved attribute metadata such as `[Host(...)]`
## 8. Loading Algorithm
The recommended Studio compiler flow is:
1. read the root `prometeu.json`,
2. parse and normalize `stdlib`,
3. construct `StdlibEnvironment` for that stdlib major,
4. create a `StdlibModuleResolver`,
5. when an import targets a reserved project space, resolve it through the stdlib resolver,
6. obtain a `StdlibModuleSource`,
7. parse the module with the standard PBS parser,
8. validate it under interface-module semantic rules,
9. cache the resulting interface module graph for the duration of the compilation.
Rules:
- reserved stdlib modules must not be handled through ordinary dependency resolution,
- ordinary dependency modules must not be handled through the stdlib resolver,
- a failed stdlib import is a deterministic compile-time error.
## 9. Attributes and Interface Metadata
Stdlib interface modules may contain reserved compile-time attributes such as:
```pbs
declare host Gfx {
[Host(module = "gfx", name = "draw_pixel", version = 1)]
fn draw_pixel(x: int, y: int, c: color);
}
```
Rules:
- the parser reads the attribute as part of the interface module source,
- the interface-module loader validates that the attribute is legal in that position,
- the compiler stores the extracted metadata in its interface graph,
- the raw attribute surface is not treated as a runtime object,
- later lowering stages may consume the extracted metadata to produce PBX host-binding declarations.
## 10. Resources as an Implementation Strategy
For the Studio PBS frontend, packaging stdlib interface modules in frontend `resources` is a valid implementation strategy.
Rules:
- `resources` packaging is implementation-level, not language-level,
- the compiler should still access stdlib modules through `StdlibEnvironment` and related abstractions,
- code outside the stdlib loader should not depend on resource path layout directly.
Rationale:
- `resources` gives a simple bootstrap path,
- stdlib evolves as real source artifacts,
- the frontend avoids hardcoded built-ins,
- the implementation remains replaceable later.
## 11. Caching and Reuse
The compiler may cache stdlib interface modules within one compilation or across compilations.
Rules:
- caching must not change observable semantics,
- cache keys should include at least the stdlib major line and logical module address,
- cached modules must preserve the same parsed declarations and attribute metadata as uncached loads.
## 12. Current Decision Summary
The current Studio direction is:
1. the stdlib environment is loaded as real PBS interface modules,
2. the initial implementation may live under frontend `resources`,
3. the logical model remains `stdlib line -> reserved project space -> module path`,
4. the compiler should use explicit abstractions such as `StdlibEnvironment` and `StdlibModuleResolver`,
5. stdlib interface modules are parsed with the normal PBS parser and validated in interface-module mode,
6. reserved attributes such as `[Host(...)]` are extracted as compile-time metadata for later lowering.
@@ -1,133 +0,0 @@
# PBS Dynamic Semantics Specification
Status: Draft v0 (Skeleton)
Applies to: runtime-observable behavior of PBS core programs
## 1. Purpose
This document will define the normative dynamic semantics of PBS core.
Its purpose is to make runtime behavior convergent across implementations by fixing:
- execution ordering,
- runtime evaluation of expressions and statements,
- abrupt completion and trap propagation,
- runtime behavior of effect surfaces such as `optional` and `result`,
- the execution boundary between ordinary PBS code, callbacks, contract calls, and host-backed calls.
## 2. Scope
This document is intended to define:
- the observable execution model of PBS core,
- evaluation order for expressions, statements, and blocks,
- runtime branch selection for `if` and `switch`,
- runtime application behavior for `apply`, call sugar, methods, contracts, callbacks, and host-backed call surfaces,
- runtime behavior of `optional`, `result<E>`, `else`, `!`, and `handle`,
- abrupt completion (`return`, `break`, `continue`) and trap propagation,
- determinism requirements that affect execution behavior.
This document does not define:
- static typing or overload resolution rules,
- GC algorithm internals,
- exact IR shape or lowering passes,
- diagnostics catalog wording,
- the full PBX binary format.
## 3. Authority and Precedence
Normative precedence:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
3. `3. Core Syntax Specification.md`
4. `4. Static Semantics Specification.md`
5. This document
If a rule here conflicts with higher authority, it is invalid.
## 4. Normative Inputs
This document depends on, at minimum:
- `1. Language Charter.md`
- `3. Core Syntax Specification.md`
- `4. Static Semantics Specification.md`
- `5. Manifest, Stdlib, and SDK Resolution Specification.md`
- `6.2. Host ABI Binding and Loader Resolution Specification.md`
This document is expected to be closed using decisions from:
- `docs/agendas/Dynamic Semantics - Execution Model Agenda.md`
- `docs/agendas/Dynamic Semantics - Effect Surfaces Agenda.md`
- `docs/agendas/Heap Model - Agenda.md`
- `docs/agendas/Memory and Lifetime - Agenda.md`
## 5. Already-Settled Inputs
The following inputs are already fixed elsewhere and must not be contradicted here:
- PBS prioritizes determinism and compatibility over ergonomics when the two conflict.
- `FRAME_SYNC`-based execution semantics remain preserved.
- No non-deterministic async execution model is part of PBS v1.
- Function application is defined on the canonical `apply` surface, with call sugar desugaring to `apply`.
- `bind(context, fn_name)` evaluates the `context` expression once at bind time.
- `switch` evaluates its selector expression once.
- `optional T` function fallthrough yields `none`.
- `result<E>` function fallthrough is a compile-time error.
- `ok(...)` and `err(...)` are not ordinary first-class runtime constructors in v1 core.
## 6. Initial Section Targets
At minimum, the completed document should contain normative sections for:
1. execution model and runtime state,
2. evaluation order by construct,
3. block execution and abrupt completion,
4. runtime semantics of `optional`,
5. runtime semantics of `result<E>`,
6. runtime semantics of `apply`, call sugar, and callable categories,
7. branching semantics for `if` and `switch`,
8. traps, determinism, and host-call interaction.
## 7. A Ver
The following items remain to be closed in agenda discussion before this document can be considered complete.
### 7.1 `Dynamic Semantics - Execution Model Agenda.md`
- Exact observable execution model for PBS v1.
- Normative evaluation order for receivers, callees, arguments, selectors, and nested `apply`.
- Exact abrupt-completion model for `return`, `break`, `continue`, `!`, and trap propagation.
- Deterministic safepoint interaction around host calls, allocation-heavy operations, and loop back-edges.
### 7.2 `Dynamic Semantics - Effect Surfaces Agenda.md`
- Runtime value model of `optional` and `result<E>`.
- Eagerness and single-evaluation guarantees for `some(...)`, `else`, `handle`, and `!`.
- Runtime artifact and cost model of `bind(context, fn_name)`.
- Exact runtime boundary between explicit status values and true traps.
### 7.3 `Heap Model - Agenda.md` and `Memory and Lifetime - Agenda.md`
- Which dynamic-semantic costs are observable and later diagnosable.
- Which constructs may allocate, copy, retain, or cross the host-memory boundary during ordinary execution.
- Which memory and safepoint facts belong in this document versus `Memory and Lifetime Specification.md`.
## 8. Non-Goals
- Reopening grammar or static typing unless current text is impossible to execute normatively.
- Defining exact GC collection strategy.
- Designing future async, actor, or scheduler models.
- Specifying backend optimization policy.
## 9. Exit Criteria
This document is ready to move beyond skeleton status only when:
1. every runtime-observable core construct has a deterministic evaluation model,
2. trap versus status-value behavior is explicit for every effect-bearing construct,
3. host-call interaction rules are stated without relying on informal prose elsewhere,
4. the document can drive runtime conformance tests without requiring agenda backfill,
5. the document no longer depends on unresolved `A Ver` items for core v1 behavior.
@@ -1,144 +0,0 @@
# PBS - Compatibility and Evolution Policy v1 (Draft)
Status: Draft (Normative policy for language/runtime evolution)
Scope: Compatibility contract for PBS features across hardware/runtime updates
Language: English
## 1. Purpose
This document defines how PBS remains stable while the logical hardware evolves.
Goals:
- preserve existing cartridge behavior across updates,
- allow additive platform growth without silent regressions,
- keep evolution deterministic and verifier-friendly,
- define explicit upgrade/rejection rules for toolchains and firmware.
## 2. Authority and precedence
Normative precedence order:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
3. `PBS - Language Syntax Specification v0.md`
4. `PBS - Game Language Profile v1 (Draft).md`
5. `PBS - Game Profile Syntax Specification v1 (Draft).md`
6. This document
7. Legacy references (`docs/specs/pbs_old/*`)
If any rule here conflicts with higher authority, this document is invalid for that rule.
## 3. Core stability model
### 3.1 Frozen core contract
The following contracts MUST remain stable once released in a major line:
- frame synchronization semantics (`FRAME_SYNC` as deterministic safepoint),
- trap and verifier invariants,
- stack/call/return discipline for valid bytecode,
- deterministic scheduling and host-call contract rules.
Behavioral changes to frozen core contracts require a new major line.
### 3.2 Additive extension rule
New features SHOULD be additive by default.
Existing valid programs MUST keep their previous behavior unless they explicitly target a newer incompatible major.
## 4. Primitive and host API versioning
### 4.1 Canonical identity
Host-call primitives MUST be versioned by canonical identity:
`(module, name, version)`
An incompatible change MUST create a new `version`.
The old version MUST remain resolvable during its supported compatibility window.
### 4.2 No semantic retcon
Implementations MUST NOT silently change semantics of an existing canonical identity.
If semantics must change incompatibly, publish a new identity version and deprecate the old one by policy.
## 5. Cartridge target contract
Each cartridge/app manifest MUST declare, at minimum:
- target VM/runtime major (or compatible range),
- language profile and profile version,
- required canonical host-call identities and versions,
- required capabilities.
Loader behavior MUST be deterministic:
- load and run when all requirements resolve,
- reject with explicit diagnostic when requirements are missing or incompatible.
Implicit fallback to a different major/version is forbidden.
## 6. Evolution policy (major/minor)
### 6.1 Minor updates
Minor updates MUST be backward compatible.
Allowed examples:
- adding new host-call identities,
- adding optional metadata/diagnostics,
- adding syntax/features gated behind explicit profile selection.
### 6.2 Major updates
Major updates MAY introduce incompatible changes.
When this happens, maintainers MUST provide:
- explicit migration notes,
- compatibility window policy for prior majors,
- deterministic loader diagnostics for unsupported targets.
## 7. Compatibility layer policy
Runtime/firmware SHOULD provide compatibility shims for older identity versions for a defined window.
If shims are provided:
- shim behavior MUST be deterministic,
- shim scope and support horizon MUST be documented,
- shim removal MUST occur only in a new major line.
## 8. Toolchain requirements
Compiler/linker/tooling MUST:
- resolve host calls by canonical identity and declared version,
- fail deterministically on unresolved identities,
- emit target/profile metadata in output artifacts,
- avoid emitting instructions/features not supported by selected target contracts.
## 9. Conformance and replay guarantees
Each release MUST pass compatibility conformance suites that include:
- bytecode verifier invariants,
- host-call resolution checks by version,
- deterministic replay checks under fixed input/event traces.
For supported target contracts, the same cartridge plus the same input/event sequence MUST produce the same observable behavior.
## 10. Deprecation policy
Deprecation MUST be explicit and non-breaking during its support window.
Required stages:
1. Mark as deprecated (tooling warning + documentation).
2. Maintain compatibility through declared window.
3. Remove only in a subsequent major line.
## 11. Non-goals
- Defining subsystem-specific syscall tables.
- Defining game-stdlib API surfaces.
- Replacing runtime authority with PBS-layer policy.
@@ -1,106 +0,0 @@
# PBS - Game Language Profile v1 (Draft)
Status: Draft (Language/Product direction)
Scope: PBS game-first language contract for 2D workloads
Language: English
## 1. Purpose
This document defines the language-level direction for PBS as a game-first scripting language.
The profile targets:
- intuitive onboarding for beginners,
- predictable frame behavior for real-time 2D games,
- explicit performance/cost surfaces for advanced developers,
- strict compatibility with a closed VM and its bytecode/runtime authority.
This document is language-contract oriented. It does not define bytecode encoding details.
## 2. Authority and compatibility
Normative precedence order:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
3. `PBS - Language Syntax Specification v0.md`
4. This document (Game Profile direction and requirements)
5. Legacy references (`docs/specs/pbs_old/*`)
If any rule here conflicts with runtime or bytecode authority, this document is invalid for that rule.
## 3. Design constraints
- The VM is a closed execution target.
- Language features must lower to supported VM/bytecode behavior.
- Determinism and frame synchronization are non-negotiable.
- GC is the baseline memory strategy.
## 4. Ten normative rules
### Rule 1 - Frame-first semantics
PBS game-facing language features MUST preserve deterministic frame execution.
Language constructs MUST NOT imply hidden asynchronous callbacks or preemptive execution.
### Rule 2 - Closed-VM compatibility
PBS MUST only define features that can be represented by the closed VM contract.
Language design MUST NOT require custom allocators, hidden host threads, or runtime behaviors outside VM authority.
### Rule 3 - GC-first memory model
PBS MUST treat GC-managed heap semantics as the default and beginner path.
Any future lifetime tools (such as pools/arena-like workflows) MUST be additive at API/library level unless runtime authority changes.
### Rule 4 - Explicit cost surfaces
PBS SHOULD make high-cost operations visible to users through language diagnostics and tooling contracts.
At minimum, allocation pressure, frequent host calls, and hot-loop risk points SHOULD be reportable in deterministic diagnostics.
### Rule 5 - 2D game-native type surface
PBS SHOULD provide a first-class game-oriented type surface through core language + standard library alignment.
The profile MUST support fluent expression of common 2D tasks (positions, velocities, bounds, colors, sprite/tile identifiers, frame counters).
### Rule 6 - Service boundary as gameplay architecture
`service` MUST remain the primary executable boundary for gameplay systems.
Language guidance SHOULD promote service-oriented decomposition for input, simulation, rendering orchestration, audio, and UI flows.
### Rule 7 - Typed host contract boundary
Host interactions MUST remain typed and explicit at language level.
Language constructs for host-facing APIs MUST preserve capability checks and syscall determinism from runtime authority.
### Rule 8 - Frame-based event and timer model
Game-facing event/timer language patterns MUST be frame-based and deterministic.
Language evolution MUST NOT reintroduce interrupt-like user execution semantics.
### Rule 9 - Progressive complexity in one language
PBS MUST support both beginner and advanced developers without forking into separate languages.
The beginner path MUST keep defaults simple and safe; advanced control MUST be explicit and opt-in.
### Rule 10 - Fluency for game loops
PBS syntax and standard patterns SHOULD optimize for high-frequency game-loop code:
- concise state updates,
- clear system boundaries,
- predictable data flow across update/render stages,
- minimal boilerplate for frame-driven logic.
## 5. Non-goals for this draft
- Defining new bytecode opcodes.
- Replacing runtime GC with a new mandatory memory subsystem.
- Adding language-level async callbacks or non-deterministic host behavior.
## 6. Planned follow-up specs
1. Game Profile syntax additions (if needed), layered on top of v0 Core.
2. Game-oriented standard library contract (collections, timers, ECS-adjacent utilities).
3. Tooling diagnostics spec for frame-cost visibility.
4. Host API declaration surface aligned with capability and syscall metadata.
@@ -1,186 +0,0 @@
# PBS - Game Profile Syntax Specification v1 (Draft)
Status: Draft (Normative for Game Profile parser/lowering work)
Scope: Syntax delta over `PBS - Language Syntax Specification v0.md`
Language: English
## 1. Purpose
This document defines the parser-facing syntax additions for the PBS Game Profile.
Goals:
- keep beginner usage fluid for 2D game construction,
- preserve deterministic/frame-oriented execution,
- remain compatible with closed VM + bytecode/runtime authority,
- avoid introducing hidden runtime behavior in language syntax.
## 2. Authority and precedence
Normative precedence order:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
3. `PBS - Language Syntax Specification v0.md`
4. This document
5. Legacy references (`docs/specs/pbs_old/*`)
If a rule here conflicts with higher authority, the rule is invalid.
## 3. Profile activation
Game Profile syntax is enabled by toolchain profile selection (`game` profile).
Without this profile, v0 Core syntax rules remain in effect.
## 4. Lexical delta (keywords)
### 4.1 Newly active keywords in Game Profile
- `host`
- `while`
- `break`
- `continue`
### 4.2 Still reserved in this draft
- `alloc`, `borrow`, `mutate`, `peek`, `take`, `weak`
- `spawn`, `yield`, `sleep`
- `handle`
This draft does not activate heap-specialized syntax or coroutine syntax.
## 5. Top-level grammar delta
Game Profile extends top-level declarations with host function declarations.
```ebnf
TopDecl ::= TypeDecl | ServiceDecl | FunctionDecl | HostFnDecl
HostFnDecl ::= 'host' 'fn' Identifier ParamList ReturnType? ';'
```
Rules:
- `host fn` declares a host-provided call surface only (no body).
- Calling `host fn` lowers to syscall-linked call sites.
- Host functions are callable entities, never first-class function values.
- Service-shaped facades over host functions belong to stdlib design, not to host syntax.
Examples:
```pbs
host fn input_state(): (int, int, int);
host fn gfx_present();
```
## 6. Statement grammar delta
Game Profile adds imperative loop/control and assignment statements.
```ebnf
Stmt ::= LetStmt
| AssignStmt
| ReturnStmt
| IfStmt
| ForStmt
| WhileStmt
| BreakStmt
| ContinueStmt
| ExprStmt
WhileStmt ::= 'while' Expr Block
BreakStmt ::= 'break' ';'
ContinueStmt ::= 'continue' ';'
AssignStmt ::= LValue AssignOp Expr ';'
AssignOp ::= '=' | '+=' | '-=' | '*=' | '/=' | '%='
LValue ::= Identifier LValueSuffix*
LValueSuffix ::= '.' Identifier | '[' Expr ']'
```
Rules:
- `break` and `continue` are valid only inside `for`/`while`.
- Assignment is a statement, not an expression.
- `LValue` cannot contain function calls.
- Compound assignments are semantic sugar over read/compute/write.
## 7. Expression grammar delta
Game Profile adds postfix member/index access chains for fluent gameplay code.
```ebnf
UnaryExpr ::= ('!' | '-') UnaryExpr | PostfixExpr
PostfixExpr ::= PrimaryExpr PostfixSuffix*
PostfixSuffix ::= CallSuffix | MemberSuffix | IndexSuffix
CallSuffix ::= '(' ArgList? ')'
MemberSuffix ::= '.' Identifier
IndexSuffix ::= '[' Expr ']'
```
This replaces the v0 Core `CallExpr` chain and enables expressions such as:
```pbs
gfx_present();
player.transform.position.x;
tiles[i].id;
```
## 8. Determinism and lowering constraints
Game Profile syntax additions MUST preserve:
- deterministic control flow,
- verifier-friendly stack effects,
- explicit host call boundaries.
Lowering requirements:
- `host` call sites map to resolved syscall identities.
- `while`/`break`/`continue` lower to structured jumps compatible with verifier rules.
- Member/index read-write operations must lower to deterministic, type-checked access paths.
## 9. Diagnostics requirements (parser + early semantic phase)
Implementations MUST produce deterministic diagnostics for:
- `break`/`continue` outside loops,
- invalid `LValue` targets,
- duplicate host signatures in the same scope,
- unresolved host declarations at link/resolve stage,
- use of still-reserved keywords as active syntax.
## 10. Minimal canonical examples
### 10.1 Frame loop style with while
```pbs
host fn gfx_present();
fn run(): int {
let running = true;
while running {
update_world();
render_world();
gfx_present();
}
return 0;
}
```
### 10.2 Assignment and member/index access
```pbs
fn integrate(p: Vec2, v: Vec2): Vec2 {
let out = p;
out.x += v.x;
out.y += v.y;
return out;
}
```
## 11. Non-goals of this syntax draft
- Defining pool/arena memory syntax.
- Enabling `alloc/borrow/mutate` in surface syntax.
- Defining coroutine syntax (`spawn/yield/sleep`) before bytecode/runtime profile activation.
@@ -1,373 +0,0 @@
# PBS - Language Syntax Specification v0
Status: Draft (Normative for FE rewrite)
Scope: PBS v0 Core syntax (lexer + parser contract)
Language: English only
## 1. Goals
This document defines the canonical PBS v0 Core syntax.
It is designed to:
- be deterministic to parse,
- be stable for tests and tooling,
- align with runtime authority,
- provide a clear baseline for frontend rewrite.
This document defines syntax only. Runtime behavior, bytecode encoding, scheduling, and GC internals are out of scope.
## 2. Authority and precedence
Normative precedence order:
1. Runtime authority (`docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`)
2. Bytecode authority (`docs/specs/bytecode/ISA_CORE.md`)
3. This syntax specification
4. Legacy references (`docs/specs/pbs_old/*`)
If a syntax rule from legacy material conflicts with runtime or bytecode authority, that rule is invalid.
## 3. Source model
- Source encoding: UTF-8.
- Line terminators: `\n` and `\r\n` are both valid.
- Whitespace is insignificant except as separator.
- A source file is a declaration unit; top-level executable statements are forbidden.
## 4. Lexical specification
### 4.1 Tokens
The lexer must produce at least:
- identifiers,
- keywords,
- numeric literals,
- string literals,
- punctuation,
- operators,
- comments,
- EOF.
Each token must carry a source span (byte offsets).
### 4.2 Comments
- Line comment: `// ...` until line end.
- Block comments are not part of v0 Core.
### 4.3 Identifiers
Identifier:
- starts with `_` or alphabetic character,
- continues with `_`, alphabetic, or digit characters.
Keywords cannot be used as identifiers.
### 4.4 Keywords
Active keywords in `.pbs` files (v0 Core):
- `import`, `from`, `as`
- `service`, `fn`
- `declare`, `struct`, `contract`, `error`
- `let`
- `if`, `else`, `when`, `for`, `in`, `return`
- `true`, `false`
Barrel-only keywords:
- `pub`, `mod`
- `type`
Reserved (not active in `.pbs` v0 Core grammar, but reserved):
- `host`, `handle`
- `alloc`, `borrow`, `mutate`, `peek`, `take`, `weak`
- `spawn`, `yield`, `sleep`
### 4.5 Literals
Numeric literals:
- `IntLit`: decimal integer (`0`, `42`, `1000`)
- `FloatLit`: decimal float with dot (`3.14`, `0.5`)
- `BoundedLit`: decimal integer with `b` suffix (`0b`, `255b`)
String literals:
- delimited by `"`.
- support escapes: `\\`, `\"`, `\n`, `\r`, `\t`.
Booleans:
- `true`, `false`.
## 5. Module and barrel model
### 5.1 Required files
A module is valid only if it contains:
- one or more `.pbs` source files,
- exactly one `mod.barrel` file.
Missing `mod.barrel` is a compile-time error.
### 5.2 Barrel responsibility
`mod.barrel` is the only place where module visibility is defined.
Visibility levels:
- `mod`: visible across files in the same module.
- `pub`: visible to other modules through imports.
Any top-level declaration not listed in `mod.barrel` is file-private.
Using `mod` or `pub` as top-level declaration modifiers in `.pbs` files is a syntax error.
### 5.3 Barrel grammar
```ebnf
BarrelFile ::= BarrelItem* EOF
BarrelItem ::= BarrelVisibility BarrelKind Identifier ';'
BarrelVisibility ::= 'mod' | 'pub'
BarrelKind ::= 'fn' | 'type' | 'service'
```
Rules:
- `mod.barrel` cannot declare aliases.
- Barrel item order has no semantic meaning.
- The same symbol cannot appear more than once in `mod.barrel`.
- Each barrel item must resolve to an existing top-level declaration in the module.
- Alias syntax is allowed only in `import` declarations.
- Importing modules may only import symbols marked as `pub` in the target module barrel.
Examples:
```barrel
mod fn clamp;
pub fn sum;
pub type Vector;
mod service Audio;
```
## 6. File and declaration grammar
EBNF conventions used:
- `A?` optional
- `A*` zero or more
- `A+` one or more
- terminals in single quotes
### 6.1 File
```ebnf
File ::= ImportDecl* TopDecl* EOF
```
### 6.2 Imports
Imports must target modules, never files.
```ebnf
ImportDecl ::= 'import' ( ModuleRef | '{' ImportList '}' 'from' ModuleRef ) ';'
ImportList ::= ImportItem (',' ImportItem)*
ImportItem ::= Identifier ('as' Identifier)?
ModuleRef ::= '@' Identifier ':' ModulePath
ModulePath ::= Identifier ('/' Identifier)*
```
Examples:
```pbs
import @core:math;
import { Vector, Matrix as Mat } from @core:math;
```
### 6.3 Top-level declarations
```ebnf
TopDecl ::= TypeDecl | ServiceDecl | FunctionDecl
```
Top-level `let` and top-level statements are not allowed.
### 6.4 Type declarations
```ebnf
TypeDecl ::= 'declare' TypeKind Identifier TypeBody
TypeKind ::= 'struct' | 'contract' | 'error'
TypeBody ::= '{' TypeMember* '}'
TypeMember ::= FieldDecl | FnSigDecl
FieldDecl ::= Identifier ':' TypeRef ';'
FnSigDecl ::= 'fn' Identifier ParamList ReturnType? ';'
```
### 6.5 Services
```ebnf
ServiceDecl ::= 'service' Identifier (':' Identifier)? ServiceBody
ServiceBody ::= '{' ServiceMember* '}'
ServiceMember ::= 'fn' Identifier ParamList ReturnType? Block
```
### 6.6 Functions
```ebnf
FunctionDecl ::= 'fn' Identifier ParamList ReturnType? ElseFallback? Block
ParamList ::= '(' Param (',' Param)* ')'
Param ::= Identifier ':' TypeRef
ReturnType ::= ':' TypeRef
ElseFallback ::= 'else' Expr
```
## 7. Type syntax
```ebnf
TypeRef ::= TypePrimary
TypePrimary ::= SimpleType | GenericType | TupleType
SimpleType ::= Identifier
GenericType ::= Identifier '<' TypeRef (',' TypeRef)* '>'
TupleType ::= '(' TypeRef ',' TypeRef (',' TypeRef){0,4} ')'
```
Runtime alignment:
- Tuple type arity in v0 Core is 2..6.
- This aligns with runtime multi-return slot limits.
## 8. Statements and blocks
```ebnf
Block ::= '{' Stmt* TailExpr? '}'
Stmt ::= LetStmt | ReturnStmt | IfStmt | ForStmt | ExprStmt
TailExpr ::= Expr
LetStmt ::= 'let' Identifier (':' TypeRef)? '=' Expr ';'
ReturnStmt ::= 'return' Expr? ';'
ExprStmt ::= Expr ';'
IfStmt ::= 'if' Expr Block ('else' (IfStmt | Block))?
ForStmt ::= 'for' Identifier 'in' RangeExpr Block
RangeExpr ::= '[' Expr? '..' Expr? ']'
```
Notes:
- `if` is a statement in v0 Core.
- `when` is an expression.
- `break` and `continue` are deferred from v0 Core syntax.
## 9. Expression grammar and precedence
Assignment is not an expression in v0 Core.
```ebnf
Expr ::= WhenExpr
WhenExpr ::= 'when' OrExpr 'then' Expr 'else' Expr | OrExpr
OrExpr ::= AndExpr ('||' AndExpr)*
AndExpr ::= EqualityExpr ('&&' EqualityExpr)*
EqualityExpr ::= CompareExpr (('==' | '!=') CompareExpr)?
CompareExpr ::= CastExpr (('<' | '<=' | '>' | '>=') CastExpr)?
CastExpr ::= AddExpr ('as' TypeRef)*
AddExpr ::= MulExpr (('+' | '-') MulExpr)*
MulExpr ::= UnaryExpr (('*' | '/' | '%') UnaryExpr)*
UnaryExpr ::= ('!' | '-') UnaryExpr | CallExpr
CallExpr ::= PrimaryExpr ('(' ArgList? ')')*
ArgList ::= Expr (',' Expr)*
Literal ::= IntLit | FloatLit | BoundedLit | StringLit | BoolLit
BoolLit ::= 'true' | 'false'
PrimaryExpr ::= Literal | Identifier | GroupExpr | Block
GroupExpr ::= '(' Expr ')'
```
Non-associative constraints:
- `a < b < c` is invalid.
- `a == b == c` is invalid.
## 10. Runtime authority alignment constraints
These are hard constraints for frontend and syntax decisions:
- Runtime is deterministic and frame-synchronized.
- `FRAME_SYNC` is runtime safepoint and not surface syntax.
- Heap semantics are GC-based at runtime authority level.
- Host interaction is via `SYSCALL` in bytecode and host ABI mapping.
- Syscalls are callable but not first-class.
Syntax implications for v0 Core:
- No RC/HIP/gate-specific syntax is active.
- No closure literal syntax in v0 Core.
- No coroutine syntax (`spawn`, `yield`, `sleep`) in v0 Core.
## 11. Deferred syntax (explicitly out of v0 Core)
Deferred for later profiles:
- heap-specialized syntax: `alloc`, `borrow`, `mutate`, `peek`, `take`, `weak`
- first-class closure/lambda surface syntax
- coroutine surface syntax
- pattern matching
- macro system
These words stay reserved so later profiles do not break source compatibility.
## 12. Conformance requirements for frontend rewrite
A v0 Core frontend is conformant if:
- tokenization follows this lexical spec,
- barrel parsing and validation follows Section 5,
- parsing follows this grammar and precedence,
- parser is deterministic,
- each token and AST node keeps stable spans,
- forbidden constructs produce deterministic diagnostics.
## 13. Minimal canonical examples
### 13.1 Function
```pbs
fn sum(a: int, b: int): int {
return a + b;
}
```
### 13.2 Local function + barrel visibility
```pbs
fn clamp(x: int, lo: int, hi: int): int {
if x < lo {
return lo;
}
if x > hi {
return hi;
}
return x;
}
```
```barrel
mod fn clamp;
```
### 13.3 Imports
```pbs
import @core:math;
import { Vec2 as V2 } from @core:math;
```
-24
View File
@@ -1,24 +0,0 @@
# PBS Specifications (Current)
This directory contains the current PBS specifications for frontend and language work.
## Authority model
- Runtime authority: `docs/specs/hardware/topics/chapter-2.md`, `chapter-3.md`, `chapter-9.md`, `chapter-12.md`, `chapter-16.md`.
- Bytecode authority: `docs/specs/bytecode/ISA_CORE.md`.
- Legacy reference only: `docs/specs/pbs_old/*`.
When a rule conflicts with runtime or bytecode authority, runtime and bytecode authority win.
## Purpose
- Define a stable syntax contract for PBS.
- Support a full frontend rewrite (lexer, parser, AST, lowering).
- Keep grammar deterministic and implementation-friendly.
## Files
- `PBS - Language Syntax Specification v0.md`: normative syntax and grammar for PBS v0 Core profile, including mandatory `mod.barrel` visibility rules.
- `PBS - Game Language Profile v1 (Draft).md`: game-first language direction for 2D workloads, defining ten normative design rules aligned with the closed VM and GC-first baseline.
- `PBS - Game Profile Syntax Specification v1 (Draft).md`: parser/lowering syntax delta for Game Profile over v0 Core (host `fn` declarations, assignment, while/break/continue, member/index postfix access).
- `PBS - Compatibility and Evolution Policy v1 (Draft).md`: compatibility contract for PBS across logical hardware updates (frozen core rules, canonical versioning, target manifests, major/minor policy, replay/conformance guarantees).
@@ -1,359 +0,0 @@
# PBS v0 Canonical Addenda
> **Purpose:** eliminate ambiguity for Junie and for golden tests.
>
> This document is **normative** for PBS Frontend v0 and complements:
>
> * **PBS Frontend Spec v0 — Implementer Edition**
> * **Junie PR Plan**
>
> These addenda define:
>
> 1. operator precedence & associativity
> 2. canonical AST JSON shape (v0)
> 3. canonical diagnostic codes (v0)
---
## 1) Operator Precedence and Associativity (v0)
### 1.1 Guiding rule
PBS v0 prioritizes **minimal ambiguity** and **easy parsing**.
* Most operators are **left-associative**.
* Assignment is **not** an expression in v0 (no `=` operator expressions).
* Member access and indexing are not part of v0 surface syntax unless already defined elsewhere.
### 1.2 Precedence table
From **highest** to **lowest**:
1. **Primary**
* literals (`10`, `3.14`, `"text"`, `none`, `some(x)`, `ok(x)`, `err(e)`)
* identifiers (`foo`)
* parenthesized expression (`(expr)`)
* block expression (`{ ... }`) (when allowed as `Expr`)
2. **Call** (left-associative)
* `callee(arg1, arg2, ...)`
3. **Unary prefix** (right-associative)
* `-expr`
* `!expr`
* `as` casts are **not unary**; see level 6.
4. **Multiplicative** (left-associative)
* `*`, `/`, `%`
5. **Additive** (left-associative)
* `+`, `-`
6. **Cast** (left-associative)
* `expr as Type`
7. **Comparison** (non-associative)
* `<`, `<=`, `>`, `>=`
8. **Equality** (non-associative)
* `==`, `!=`
9. **Logical AND** (left-associative)
* `&&`
10. **Logical OR** (left-associative)
* `||`
11. **Control expressions** (special)
* `if ... { ... } else { ... }` (expression form only if your v0 allows it; otherwise statement)
* `when { ... }` (expression)
### 1.3 Non-associative rule
Comparison and equality are **non-associative**:
* `a < b < c` is an error
* `a == b == c` is an error
Diagnostic: `E_PARSE_NON_ASSOC`.
### 1.4 Notes on `when`
`when` binds weaker than all binary operators.
Example:
```pbs
let x = a + b when { ... };
```
Parses as:
```
let x = (a + b) when { ... };
```
---
## 2) Canonical AST JSON (v0)
### 2.1 Canonicalization goals
Canonical AST JSON is used for:
* golden tests
* frontend determinism validation
* diff-friendly debugging
Rules:
* JSON keys are **stable** and **ordered** (when writing JSON)
* All nodes include `kind` and `span`
* Spans are byte offsets into the file content
### 2.2 Span encoding
```json
{"file":"main.pbs","start":12,"end":18}
```
Where:
* `start` is inclusive
* `end` is exclusive
### 2.3 Root
```json
{
"kind": "File",
"span": {"file":"...","start":0,"end":123},
"imports": [ ... ],
"decls": [ ... ]
}
```
### 2.4 Import node
```json
{
"kind": "Import",
"span": {"file":"...","start":0,"end":20},
"spec": {"kind":"ImportSpec","path":["Foo","Bar"]},
"from": "./lib.pbs"
}
```
`ImportSpec.path` is an array of identifiers.
### 2.5 Declarations
#### 2.5.1 Service
```json
{
"kind": "ServiceDecl",
"span": {"file":"...","start":0,"end":50},
"vis": "pub",
"name": "Audio",
"extends": null,
"members": [ ... ]
}
```
A service member (method signature only in v0):
```json
{
"kind": "ServiceFnSig",
"span": {"file":"...","start":0,"end":10},
"name": "play",
"params": [ {"name":"sound","ty": {"kind":"TypeName","name":"Sound"}} ],
"ret": {"kind":"TypeName","name":"void"}
}
```
#### 2.5.2 Function
```json
{
"kind": "FnDecl",
"span": {"file":"...","start":0,"end":80},
"name": "main",
"params": [],
"ret": null,
"else": null,
"body": {"kind":"Block", ... }
}
```
#### 2.5.3 TypeDecl (struct/contract/error)
```json
{
"kind": "TypeDecl",
"span": {"file":"...","start":0,"end":100},
"vis": "pub",
"typeKind": "struct",
"name": "Vector",
"body": {"kind":"TypeBody","members":[ ... ]}
}
```
### 2.6 Blocks and statements
Block:
```json
{
"kind": "Block",
"span": {"file":"...","start":0,"end":20},
"stmts": [ ... ],
"tail": null
}
```
* `stmts` are statements.
* `tail` is an optional final expression (only if your parser supports expression blocks).
Statement kinds (v0 minimum):
* `LetStmt`
* `ExprStmt`
* `ReturnStmt`
Let:
```json
{
"kind": "LetStmt",
"span": {"file":"...","start":0,"end":20},
"name": "x",
"isMut": false,
"ty": null,
"init": {"kind":"IntLit", "value": 10, "span": ...}
}
```
Return:
```json
{
"kind": "ReturnStmt",
"span": {"file":"...","start":0,"end":10},
"expr": null
}
```
### 2.7 Expressions
All expressions include `kind` and `span`.
Minimal v0 expression node kinds:
* `IntLit` `{ value: i64 }`
* `FloatLit` `{ value: f64 }`
* `BoundedLit` `{ value: u32 }`
* `StringLit` `{ value: string }`
* `Ident` `{ name: string }`
* `Call` `{ callee: Expr, args: Expr[] }`
* `Unary` `{ op: "-"|"!", expr: Expr }`
* `Binary` `{ op: string, left: Expr, right: Expr }`
* `Cast` `{ expr: Expr, ty: TypeRef }`
* `IfExpr` `{ cond: Expr, then: Block, els: Block }` (if expression is supported)
* `WhenExpr` `{ arms: WhenArm[] }`
Type references:
```json
{"kind":"TypeName","name":"int"}
```
Generics:
```json
{"kind":"TypeApp","base":"optional","args":[{"kind":"TypeName","name":"int"}]}
```
### 2.8 Canonical JSON ordering
When writing AST JSON, always order fields as:
1. `kind`
2. `span`
3. semantic fields (stable order)
This makes diffs deterministic.
---
## 3) Diagnostic Codes (v0)
### 3.1 Diagnostic format
All diagnostics must be serializable to canonical JSON:
```json
{
"severity": "error",
"code": "E_PARSE_UNEXPECTED_TOKEN",
"message": "Unexpected token '}'",
"span": {"file":"main.pbs","start":12,"end":13}
}
```
Severity is one of: `error`, `warning`.
### 3.2 Parse/Lex errors (E_PARSE_*)
* `E_LEX_INVALID_CHAR` — invalid character
* `E_LEX_UNTERMINATED_STRING` — string literal not closed
* `E_PARSE_UNEXPECTED_TOKEN` — token not expected in current context
* `E_PARSE_EXPECTED_TOKEN` — missing required token
* `E_PARSE_NON_ASSOC` — chained comparison/equality (non-associative)
### 3.3 Symbol/Resolve errors (E_RESOLVE_*)
* `E_RESOLVE_UNDEFINED` — undefined identifier
* `E_RESOLVE_DUPLICATE_SYMBOL` — duplicate symbol in same namespace
* `E_RESOLVE_NAMESPACE_COLLISION` — name exists in both type and value namespaces
* `E_RESOLVE_VISIBILITY` — symbol not visible from this scope/module
* `E_RESOLVE_INVALID_IMPORT` — import spec/path invalid
### 3.4 Type errors (E_TYPE_*)
* `E_TYPE_MISMATCH` — type mismatch
* `E_TYPE_UNKNOWN_TYPE` — unknown type name
* `E_TYPE_MUTABILITY` — mutability violation
* `E_TYPE_RETURN_PATH` — not all paths return a value
* `E_TYPE_INVALID_CAST` — invalid cast
### 3.5 Lowering errors (E_LOWER_*)
* `E_LOWER_UNSUPPORTED` — feature not supported in v0 lowering
### 3.6 Warnings (W_*)
Warnings are allowed in v0 but should be used sparingly.
* `W_UNUSED_LET` — unused local binding
* `W_SHADOWING` — local shadows another binding
---
## Implementation Notes (Non-normative)
* Keep these addenda in `spec/` in the repo.
* Use them to drive golden tests for AST and diagnostics.
* If a future change alters canonical AST, bump a version and regenerate goldens deliberately.
@@ -1,321 +0,0 @@
# Prometeu PBS v0 — Unified Project, Module, Linking & Execution Specification
> **Status:** Canonical / Replaces all previous module & linking specs
>
> This document **fully replaces**:
>
> * "PBS – Module and Linking Model"
> * Any partial or implicit module/linking descriptions in earlier PBS documents
>
> After this document, there must be **no parallel or competing spec** describing project structure, modules, imports, or linking for PBS v0.
---
## 1. Purpose
This specification defines the **single authoritative model** for how a Prometeu PBS v0 program is:
1. Organized as a project
2. Structured into modules
3. Resolved and linked at compile time
4. Emitted as one executable bytecode blob
5. Loaded and executed by the Prometeu Virtual Machine
The primary objective is to **eliminate ambiguity** by enforcing a strict separation of responsibilities:
* **Compiler / Tooling**: all symbolic, structural, and linking work
* **Runtime / VM**: verification and execution only
---
## 2. Core Principles
### 2.1 Compiler Finality Principle
All operations involving **names, symbols, structure, or intent** must be completed at compile time.
The VM **never**:
* Resolves symbols or names
* Loads or links multiple modules
* Applies relocations or fixups
* Interprets imports or dependencies
### 2.2 Single-Blob Execution Principle
A PBS v0 program is executed as **one fully linked, self-contained bytecode blob**.
At runtime there is no concept of:
* Projects
* Modules
* Imports
* Dependencies
These concepts exist **only in the compiler**.
---
## 3. Project Model
### 3.1 Project Root
A Prometeu project is defined by a directory containing:
* `prometeu.json` — project manifest (required)
* One or more module directories
### 3.2 `prometeu.json` Manifest
The project manifest is mandatory and must define:
```json
{
"name": "example_project",
"version": "0.1.0",
"dependencies": {
"core": "../core",
"input": "../input"
}
}
```
#### Fields
* `name` (string, required)
* Canonical project identifier
* `version` (string, required)
* `dependencies` (map, optional)
* Key: dependency project name
* Value: filesystem path or resolver hint
Dependency resolution is **purely a compiler concern**.
---
## 4. Module Model (Compile-Time Only)
### 4.1 Module Definition
* A module is a directory inside a project
* Each module contains one or more `.pbs` source files
### 4.2 Visibility Rules
Visibility is enforced **exclusively at compile time**:
* `file`: visible only within the same source file
* `mod`: visible within the same module
* `pub`: visible to importing modules or projects
The VM has **zero awareness** of visibility.
---
## 5. Imports & Dependency Resolution
### 5.1 Import Syntax
Imports reference **projects and modules**, never files:
```
import @core:math
import @input:pad
```
### 5.2 Resolution Pipeline
The compiler performs the following phases:
1. Project dependency graph resolution (via `prometeu.json`)
2. Module discovery
3. Symbol table construction
4. Name and visibility resolution
5. Type checking
Any failure aborts compilation and **never reaches the VM**.
---
## 6. Linking Model (Compiler Responsibility)
### 6.1 Link Stage
After semantic validation, the compiler executes a **mandatory link stage**.
The linker:
* Assigns final `func_id` indices
* Assigns constant pool indices
* Computes final `code_offset` and `code_len`
* Resolves all jumps and calls
* Merges all module bytecode into one contiguous code segment
### 6.2 Link Output Format
The output of linking is a **Linked PBS Program** with the following layout:
```text
[ Header ]
[ Constant Pool ]
[ Function Table ]
[ Code Segment ]
```
All references are:
* Absolute
* Final
* Fully resolved
No relocations or fixups remain.
---
## 7. Runtime Execution Contract
### 7.1 VM Input Requirements
The Prometeu VM accepts **only linked PBS blobs**.
It assumes:
* All function references are valid
* All jumps target instruction boundaries
* No unresolved imports exist
### 7.2 VM Responsibilities
The VM is responsible for:
1. Loading the bytecode blob
2. Structural and control-flow verification
3. Stack discipline verification
4. Deterministic execution
The VM **must not**:
* Perform linking
* Resolve symbols
* Modify code offsets
* Load multiple modules
---
## 8. Errors and Runtime Traps
### 8.1 Compile-Time Errors
Handled exclusively by the compiler:
* Unresolved imports
* Visibility violations
* Type errors
* Circular dependencies
These errors **never produce bytecode**.
### 8.2 Runtime Traps
Runtime traps represent **deterministic execution faults**, such as:
* Stack underflow
* Invalid local access
* Invalid syscall invocation
* Explicit `TRAP` opcode
Traps are part of the **execution model**, not debugging.
---
## 9. Versioning and Scope
### 9.1 PBS v0 Guarantees
PBS v0 guarantees:
* Single-blob execution
* No runtime linking
* Deterministic behavior
### 9.2 Out of Scope for v0
The following are explicitly excluded from PBS v0:
* Dynamic module loading
* Runtime imports
* Hot reloading
* Partial linking
---
## 10. Canonical Ownership Summary
| Concern | Owner |
| ----------------- | ------------- |
| Project structure | Compiler |
| Dependencies | Compiler |
| Modules & imports | Compiler |
| Linking | Compiler |
| Bytecode format | Bytecode spec |
| Verification | VM |
| Execution | VM |
> **Rule of thumb:**
> If it requires names, symbols, or intent → compiler.
> If it requires bytes, slots, or PCs → VM.
---
## 11. Final Note
After adoption of this document:
* Any existing or future document describing PBS modules or linking **must defer to this spec**
* Any behavior conflicting with this spec is considered **non-compliant**
* The Prometeu VM is formally defined as a **pure executor**, not a linker
---
## Addendum — `prometeu.json` and Dependency Management
This specification intentionally **does not standardize the full dependency resolution algorithm** for `prometeu.json`.
### Scope Clarification
* `prometeu.json` **defines project identity and declared dependencies only**.
* **Dependency resolution, fetching, version selection, and conflict handling are responsibilities of the Prometeu Compiler**, not the VM and not the runtime bytecode format.
* The Virtual Machine **never reads or interprets `prometeu.json`**.
### Compiler Responsibility
The compiler is responsible for:
* Resolving dependency sources (`path`, `git`, registry, etc.)
* Selecting versions (exact, range, or `latest`)
* Applying aliasing / renaming rules
* Detecting conflicts and incompatibilities
* Producing a **fully linked, closed-world Program Image**
After compilation and linking:
* All symbols are resolved
* All function indices are fixed
* All imports are flattened into the final bytecode image
The VM consumes **only the resulting bytecode blob** and associated metadata.
### Separate Specification
A **dedicated specification** will define:
* The complete schema of `prometeu.json`
* Dependency version semantics
* Resolution order and override rules
* Tooling expectations (compiler, build system, CI)
This addendum exists to explicitly state the boundary:
> **`prometeu.json` is a compiler concern; dependency management is not part of the VM or bytecode execution model.**
@@ -1,268 +0,0 @@
# Prometeu.json — Project Manifest Specification
## Status
Draft · Complementary specification to the PBS Linking & Module Model
## Purpose
`prometeu.json` is the **project manifest** for Prometeu-based software.
Its role is to:
* Identify a Prometeu project
* Declare its dependencies
* Provide **input metadata to the compiler and linker**
It is **not** consumed by the Virtual Machine.
---
## Design Principles
1. **Compiler-owned**
* Only the Prometeu Compiler reads `prometeu.json`.
* The VM and runtime never see this file.
2. **Declarative, not procedural**
* The manifest declares *what* the project depends on, not *how* to resolve it.
3. **Closed-world output**
* Compilation + linking produce a single, fully resolved bytecode blob.
4. **Stable identity**
* Project identity is explicit and versioned.
---
## File Location
`prometeu.json` must be located at the **root of the project**.
---
## Top-level Structure
```json
{
"name": "my_project",
"version": "0.1.0",
"kind": "app",
"dependencies": {
"std": {
"git": "https://github.com/prometeu/std",
"version": ">=0.2.0"
}
}
}
```
---
## Fields
### `name`
**Required**
* Logical name of the project
* Used as the **default module namespace**
Rules:
* ASCII lowercase recommended
* Must be unique within the dependency graph
Example:
```json
"name": "sector_crawl"
```
---
### `version`
**Required**
* Semantic version of the project
* Used by the compiler for compatibility checks
Format:
```
MAJOR.MINOR.PATCH
```
---
### `kind`
**Optional** (default: `app`)
Defines how the project is treated by tooling.
Allowed values:
* `app` — executable program
* `lib` — reusable module/library
* `system` — firmware / system component
---
### `dependencies`
**Optional**
A map of **dependency aliases** to dependency specifications.
```json
"dependencies": {
"alias": { /* spec */ }
}
```
#### Alias semantics
* The **key** is the name by which the dependency is referenced **inside this project**.
* It acts as a **rename / namespace alias**.
Example:
```json
"dependencies": {
"gfx": {
"path": "../prometeu-gfx"
}
}
```
Internally, the dependency will be referenced as `gfx`, regardless of its original project name.
---
## Dependency Specification
Each dependency entry supports the following fields.
### `path`
Local filesystem dependency.
```json
{
"path": "../std"
}
```
Rules:
* Relative paths are resolved from the current `prometeu.json`
* Absolute paths are allowed but discouraged
---
### `git`
Git-based dependency.
```json
{
"git": "https://github.com/prometeu/std",
"version": "^0.3.0"
}
```
The compiler is responsible for:
* Cloning / fetching
* Version selection
* Caching
---
### `version`
Optional version constraint.
Examples:
* Exact:
```json
"version": "0.3.1"
```
* Range:
```json
"version": ">=0.2.0 <1.0.0"
```
* Latest:
```json
"version": "latest"
```
Semantics are defined by the compiler.
---
## Resolution Model (Compiler-side)
The compiler must:
1. Load root `prometeu.json`
2. Resolve all dependencies recursively
3. Apply aliasing rules
4. Detect:
* Cycles
* Version conflicts
* Name collisions
5. Produce a **flat module graph**
6. Invoke the linker to generate a **single Program Image**
---
## Interaction with the Linker
* `prometeu.json` feeds the **module graph**
* The linker:
* Assigns final function indices
* Fixes imports/exports
* Emits a closed bytecode image
After linking:
> No module boundaries or dependency information remain at runtime.
---
## Explicit Non-Goals
This specification does **not** define:
* Lockfiles
* Registry formats
* Caching strategies
* Build profiles
* Conditional dependencies
These may be added in future specs.
---
## Summary
* `prometeu.json` is the **single source of truth for project identity and dependencies**
* Dependency management is **compiler-owned**
* The VM executes **only fully linked bytecode**
This file completes the boundary between **project structure** and **runtime execution**.
@@ -1,446 +0,0 @@
# Prometeu Base Script (PBS)
## Frontend Spec v0 — Implementer Edition
> **Normative specification for building a PBS frontend (lexer, parser, AST, resolver, typechecker) targeting the Prometeu Fantasy Console runtime.**
>
> This document is **not** a user guide.
> It exists to make PBS *implementable*, *deterministic*, and *testable*.
---
## 0. Scope and Non‑Goals
### 0.1 Scope
This specification defines:
* lexical structure (tokens)
* grammar and parsing rules
* canonical AST shapes
* frontend phases and their responsibilities
* name resolution and visibility rules
* type system rules
* desugaring and lowering rules
* diagnostic categories (errors vs warnings)
* required guarantees for runtime integration
The goal is that **two independent frontends** built from this spec:
* accept the same programs
* reject the same programs
* produce equivalent ASTs
* emit equivalent diagnostics
### 0.2 Non‑Goals
This spec does **not** define:
* runtime performance characteristics
* bytecode layout
* JIT or interpreter design
* editor tooling or IDE features
Those are explicitly out of scope.
---
## 1. Frontend Pipeline Overview
A PBS frontend **must** be structured as the following pipeline:
```
Source Text
↓
Lexer
↓
Parser
↓
Raw AST
↓
Symbol Collection
↓
Resolver
↓
Typed AST
↓
Desugaring / Lowering
↓
Runtime‑ready IR / AST
```
Each stage has **strict responsibilities**.
No stage may perform work assigned to a later stage.
---
## 2. Lexical Structure
### 2.1 Tokens
A PBS lexer must recognize at minimum the following token classes:
* identifiers
* keywords
* numeric literals
* string literals
* punctuation
* operators
* comments
Whitespace is insignificant except as a separator.
---
### 2.2 Keywords (Reserved)
The following keywords are **reserved** and may not be used as identifiers:
```
import
pub
mod
service
fn
let
mut
declare
struct
contract
host
error
optional
result
some
none
ok
err
if
else
when
for
in
return
handle
borrow
mutate
peek
take
alloc
weak
as
```
---
### 2.3 Literals
#### Numeric Literals
* `int` — decimal digits
* `float` — decimal with `.`
* `bounded` — decimal digits suffixed with `b`
Examples:
```pbs
10
42
3.14
0b
255b
```
#### String Literals
* delimited by `"`
* UTF‑8 encoded
* immutable
---
### 2.4 Comments
* line comment: `// until end of line`
* block comments are **not supported** in v0
---
## 3. Grammar (EBNF‑style)
> This grammar is **normative** but simplified for readability.
> Implementers may refactor internally as long as semantics are preserved.
### 3.1 File Structure
```
File ::= Import* TopLevelDecl*
Import ::= 'import' ImportSpec 'from' StringLiteral
TopLevelDecl::= TypeDecl | ServiceDecl | FnDecl
```
---
### 3.2 Type Declarations
```
TypeDecl ::= Visibility? 'declare' TypeKind Identifier TypeBody
TypeKind ::= 'struct' | 'contract' | 'error'
```
---
### 3.3 Services
```
ServiceDecl ::= Visibility 'service' Identifier (':' Identifier)? Block
```
Visibility is mandatory for services.
---
### 3.4 Functions
```
FnDecl ::= Visibility? 'fn' Identifier ParamList ReturnType? ElseFallback? Block
```
Top‑level `fn` are `mod` or `file-private` (default). They cannot be `pub`.
---
### 3.5 Expressions (Partial)
```
Expr ::= Literal
| Identifier
| CallExpr
| Block
| IfExpr
| WhenExpr
| ForExpr
| ReturnExpr
```
Expression grammar is intentionally restricted in v0.
---
## 4. Canonical AST
The frontend **must** produce a canonical AST.
### 4.1 AST Invariants
* AST nodes are immutable after creation
* Parent pointers are optional
* Source spans must be preserved for diagnostics
---
### 4.2 Core Node Kinds
Minimal required node kinds:
* `FileNode`
* `ImportNode`
* `ServiceNode`
* `FunctionNode`
* `StructDeclNode`
* `ContractDeclNode`
* `BlockNode`
* `LetNode`
* `CallNode`
* `IfNode`
* `WhenNode`
* `ForNode`
* `ReturnNode`
Implementers may add internal nodes but must normalize before later phases.
---
## 5. Symbol Collection Phase
### 5.1 Purpose
Symbol Collection builds **module‑level symbol tables** without resolving bodies.
Collected symbols:
* `pub` and `mod` type declarations
* `pub` and `mod` services
Excluded:
* function bodies
* expressions
* local bindings
---
### 5.2 Namespaces
PBS has **two namespaces**:
* Type namespace
* Value namespace
Rules:
* A name may not exist in both namespaces
* Violations are compile‑time errors
---
## 6. Resolver Phase
### 6.1 Responsibilities
Resolver must:
* resolve all identifiers
* enforce visibility rules
* bind references to symbols
Resolution order (per namespace):
1. local bindings
2. file‑private declarations
3. module symbols
4. imported symbols
---
### 6.2 Visibility Rules (Normative)
* file‑private: visible only in the same file
* `mod`: visible within the module
* `pub`: visible across modules via import
Violations are errors.
---
## 7. Type Checking
### 7.1 Type Categories
Frontend must support:
* primitive types
* struct value types
* `optional<T>`
* `result<T, E>`
* gate‑backed types (opaque at frontend level)
---
### 7.2 Mutability Rules
* mutability belongs to bindings, not types
* `mut` is part of binding metadata
* mutability violations are compile‑time errors
---
### 7.3 Function Checking
Rules:
* all paths must return a value unless `else` fallback exists
* `optional<T>` may implicitly return `none`
* `result<T,E>` must return explicitly
---
## 8. Desugaring and Lowering
### 8.1 Purpose
Lowering transforms surface syntax into a minimal core language.
Examples:
* `take x.push(v)` → `mutate x as t { t.push(v) }`
* `when` → conditional expression node
* implicit `return none` for `optional<T>`
Lowered AST must contain **no syntactic sugar**.
---
## 9. Diagnostics Model
Diagnostics are first‑class frontend outputs.
### 9.1 Categories
* Error — compilation must fail
* Warning — compilation may continue
---
### 9.2 Required Errors
Examples:
* unresolved identifier
* visibility violation
* type mismatch
* mutability violation
* invalid gate conversion
---
## 10. Runtime Interface Assumptions
Frontend assumes:
* host‑bound contracts map to runtime syscalls
* allocation primitives exist (`alloc`)
* reference counting is handled by runtime
Frontend must **not** assume GC or heap layout.
---
## 11. Determinism Guarantees
A valid PBS frontend **must guarantee**:
* deterministic parsing
* deterministic name resolution
* deterministic type checking
* deterministic diagnostics
No frontend stage may depend on execution order or host state.
---
## 12. Conformance Criteria
A frontend is PBS‑v0‑conformant if:
* it implements all rules in this document
* it produces canonical ASTs
* it rejects all invalid programs defined herein
This document is the **source of truth** for PBS v0 frontend behavior.
---
## 13. Future Evolution (Non‑Normative)
Future versions may add:
* pattern matching
* richer type inference
* macros
No v0 frontend is required to support these.
---
## End of Spec
@@ -1,175 +0,0 @@
# Runtime Traps v0 — Prometeu VM Specification
> **Status:** Proposed (requires explicit owner approval)
>
> **Scope:** Prometeu VM / PBS v0 execution model
---
## 1. Motivation
Prometeu aims to be a **deterministic, industrial-grade virtual machine**.
To achieve this, execution errors that are:
* caused by **user programs**,
* predictable by the execution model,
* and recoverable at the tooling / host level,
must be **explicitly represented** and **ABI-stable**.
This specification introduces **Runtime Traps** as a *formal concept*, consolidating behavior that already existed implicitly in the VM.
---
## 2. Definition
A **Runtime Trap** is a **controlled interruption of program execution** caused by a semantic violation detected at runtime.
A trap:
* **terminates the current execution frame** (or program, depending on host policy)
* **does not corrupt VM state**
* **returns structured diagnostic information** (`TrapInfo`)
* **is deterministic** for a given bytecode + state
A trap is **not**:
* a debugger breakpoint
* undefined behavior
* a VM panic
* a verifier/load-time error
---
## 3. Trap vs Other Failure Modes
| Category | When | Recoverable | ABI-stable | Example |
| ------------------ | ---------------------- | ----------- | ---------- | -------------------------------- |
| **Verifier error** | Load-time | ❌ | ❌ | Stack underflow, bad CFG join |
| **Runtime trap** | Execution | ✅ | ✅ | OOB access, invalid local |
| **VM panic** | VM invariant violation | ❌ | ❌ | Handler returns wrong slot count |
| **Breakpoint** | Debug only | ✅ | ❌ | Developer inspection |
---
## 4. Trap Information (`TrapInfo`)
All runtime traps must produce a `TrapInfo` structure with the following fields:
```text
TrapInfo {
code: u32, // ABI-stable trap code
opcode: u16, // opcode that triggered the trap
pc: u32, // program counter (relative to module)
message: String, // human-readable explanation (non-ABI)
}
```
### ABI Guarantees
* `code`, `opcode`, and `pc` are ABI-relevant and stable
* `message` is diagnostic only and may change
---
## 5. Standard Trap Codes (v0)
### 5.1 Memory & Bounds
| Code | Name | Meaning |
| -------------------- | ------------- | ------------------------------ |
| `TRAP_OOB` | Out of bounds | Access beyond allowed bounds |
| `TRAP_INVALID_LOCAL` | Invalid local | Local slot index out of bounds |
### 5.2 Execution & Types
| Code | Name | Meaning |
| ------------------------- | -------------------- | ------------------------------------------------------ |
| `TRAP_ILLEGAL_INSTRUCTION`| Illegal instruction | Unknown/invalid opcode encountered |
| `TRAP_TYPE` | Type violation | Type mismatch for operation or syscall argument types |
| `TRAP_DIV_ZERO` | Divide by zero | Division/modulo by zero |
| `TRAP_INVALID_FUNC` | Invalid function | Function index not present in function table |
| `TRAP_BAD_RET_SLOTS` | Bad return slots | Stack height mismatch at return |
### 5.3 System
| Code | Name | Meaning |
| ---------------------- | --------------- | --------------------------------------- |
| `TRAP_INVALID_SYSCALL` | Invalid syscall | Unknown syscall ID |
| `TRAP_STACK_UNDERFLOW` | Stack underflow | Missing arguments for syscall or opcode |
> This list is **closed for PBS v0** unless explicitly extended.
---
## 6. Trap Semantics
### 6.1 Execution
When a trap occurs:
1. The current instruction **does not complete**
2. No partial side effects are committed
3. Execution stops and returns `TrapInfo` to the host
### 6.2 Stack & Frames
* Operand stack is left in a **valid but unspecified** state
* Call frames above the trapping frame are not resumed
### 6.3 Host Policy
The host decides:
* whether the trap terminates the whole program
* whether execution may be restarted
* how the trap is surfaced to the user (error, log, UI, etc.)
---
## 7. Verifier Interaction
The verifier **must prevent** traps that are statically provable, including:
* stack underflow
* invalid control-flow joins
* invalid syscall IDs
* incorrect return slot counts
If a verifier rejects a module, **no runtime traps should occur for those causes**.
---
## 8. What Is *Not* a Trap
The following are **VM bugs or tooling errors**, not traps:
* handler returns wrong number of slots
* opcode implementation violates `OpcodeSpec`
* verifier and runtime disagree on stack effects
These must result in **VM panic**, not a trap.
---
## 9. Versioning Policy
* Trap codes are **ABI-stable within a major version** (v0)
* New trap codes may only be added in a **new major ABI version** (v1)
* Removing or reinterpreting trap codes is forbidden
---
## 10. Summary
Runtime traps are:
* an explicit part of the Prometeu execution model
* deterministic and ABI-stable
* reserved for **user-program semantic errors**
They are **not** debugging tools and **not** VM panics.
This spec formalizes existing behavior and freezes it for PBS v0.
---
File diff suppressed because it is too large Load Diff
@@ -1,359 +0,0 @@
# Prometeu VM Memory Model v0
> **Status:** v0 (normative, implementer-facing)
>
> **Purpose:** define the runtime memory model required to execute PBS programs with stable bytecode.
>
> This specification describes the four memory regions and their interactions:
>
> 1. **Constant Pool** (read-only)
> 2. **Stack** (SAFE)
> 3. **Heap** (HIP storage bytes/slots)
> 4. **Gate Pool** (HIP handles, RC, metadata)
---
## 1. Design Goals
1. **Bytecode stability**: instruction meanings and data formats must remain stable across versions.
2. **Deterministic behavior**: no tracing GC; reclamation is defined by reference counts and safe points.
3. **Explicit costs**: HIP allocation and aliasing are explicit via gates.
4. **PBS alignment**: SAFE vs HIP semantics match PBS model.
---
## 2. Memory Regions Overview
### 2.1 Constant Pool (RO)
A program-wide immutable pool containing:
* integers, floats, bounded ints
* strings
* (optional in future) constant composite literals
Properties:
* read-only during execution
* indexed by `ConstId`
* VM bytecode uses `PUSH_CONST(ConstId)`
---
### 2.2 Stack (SAFE)
The **stack** contains:
* local variables (by slot)
* operand stack values for instruction evaluation
SAFE properties:
* values are copied by value
* no aliasing across variables unless the value is a gate handle
* stack values are reclaimed automatically when frames unwind
---
### 2.3 Heap (HIP storage)
The **heap** is a contiguous array of machine slots (e.g., `Value` slots), used only as **storage backing** for HIP objects.
Heap properties:
* heap cells are not directly addressable by bytecode
* heap is accessed only via **Gate Pool resolution**
The heap may implement:
* bump allocation (v0)
* free list (optional)
* compaction is **not** required in v0
---
### 2.4 Gate Pool (HIP handles)
The **gate pool** is the authoritative table mapping a small integer handle (`GateId`) to a storage object.
Gate Pool entry (conceptual):
```text
GateEntry {
alive: bool,
base: HeapIndex,
slots: u32,
strong_rc: u32,
weak_rc: u32, // optional in v0; may be reserved
type_id: TypeId, // required for layout + debug
flags: GateFlags,
}
```
Properties:
* `GateId` is stable during the lifetime of an entry
* `GateId` values may be reused only after an entry is fully reclaimed (v0 may choose to never reuse)
* any invalid `GateId` access is a **runtime trap** (deterministic)
---
## 3. SAFE vs HIP
### 3.1 SAFE
SAFE is stack-only execution:
* primitives
* structs / arrays as **value copies**
* temporaries
SAFE values are always reclaimed by frame unwinding.
### 3.2 HIP
HIP is heap-backed storage:
* storage objects allocated with `alloc`
* accessed through **gates**
* aliasing occurs by copying a gate handle
HIP values are reclaimed by **reference counting**.
---
## 4. Value Representation
### 4.1 Stack Values
A VM `Value` type must minimally support:
* `Int(i64)`
* `Float(f64)`
* `Bounded(u32)`
* `Bool(bool)`
* `String(ConstId)` or `StringRef(ConstId)` (strings live in const pool)
* `Gate(GateId)` ← **this is the only HIP pointer form in v0**
* `Unit`
**Rule:** any former `Ref` pointer type must be reinterpreted as `GateId`.
---
## 5. Allocation (`alloc`) and Gate Creation
### 5.1 Concept
PBS `alloc` creates:
1. heap backing storage (N slots)
2. a gate pool entry
3. returns a gate handle onto the stack
### 5.2 Required inputs
Allocation must be shape-explicit:
* `TypeId` describing the allocated storage type
* `slots` describing the storage size
### 5.3 Runtime steps (normative)
On `ALLOC(type_id, slots)`:
1. allocate `slots` contiguous heap cells
2. create gate entry:
* `base = heap_index`
* `slots = slots`
* `strong_rc = 1`
* `type_id = type_id`
3. push `Gate(gate_id)` to stack
### 5.4 Example
PBS:
```pbs
let v: Box<Vector> = box(Vector.ZERO);
```
Lowering conceptually:
* compute value `Vector.ZERO` (SAFE)
* `ALLOC(TypeId(Vector), slots=2)` → returns `Gate(g0)`
* store the two fields into heap via `STORE_GATE_FIELD`
---
## 6. Gate Access (Read/Write)
### 6.1 Access Principle
Heap is never accessed directly.
All reads/writes go through:
1. gate validation
2. gate → (base, slots)
3. bounds check
4. heap read/write
### 6.2 Read / Peek
`peek` copies from HIP storage to SAFE value.
* no RC changes
* no aliasing is created
### 6.3 Borrow (read-only view)
Borrow provides temporary read-only access.
* runtime may enforce with a borrow stack (debug)
* v0 may treat borrow as a checked read scope
### 6.4 Mutate (mutable view)
Mutate provides temporary mutable access.
* v0 may treat mutate as:
* read into scratch (SAFE)
* write back on `EndMutate`
Or (preferred later):
* direct heap writes within a guarded scope
---
## 7. Reference Counting (RC)
### 7.1 Strong RC
Strong RC counts how many **live gate handles** exist.
A `GateId` is considered live if it exists in:
* a stack slot
* a global slot
* a heap storage cell (HIP) (future refinement)
### 7.2 RC operations
When copying a gate handle into a new location:
* increment `strong_rc`
When a gate handle is removed/overwritten:
* decrement `strong_rc`
**Rule:** RC updates are required for any VM instruction that:
* assigns locals/globals
* stores into heap cells
* pops stack values
### 7.3 Release and Reclamation
When `strong_rc` reaches 0:
* gate entry becomes **eligible for reclamation**
* actual reclamation occurs at a **safe point**
Safe points (v0):
* end of frame
* explicit `FRAME_SYNC` (if present)
Reclamation:
1. mark gate entry `alive = false`
2. optionally add heap region to a free list
3. gate id may be recycled (optional)
**No tracing GC** is performed.
---
## 8. Weak Gates (Reserved / Optional)
v0 may reserve the field `weak_rc` but does not require full weak semantics.
If implemented:
* weak handles do not keep storage alive
* upgrading weak → strong requires a runtime check
---
## 9. Runtime Traps (Deterministic)
The VM must trap deterministically on:
* invalid `GateId`
* accessing a dead gate
* out-of-bounds offset
* type mismatch in a typed store/load (if enforced)
Traps must include:
* opcode
* span (if debug info present)
* message
---
## 10. Examples
### 10.1 Aliasing via gates
```pbs
let a: Box<Vector> = box(Vector.ZERO);
let b: Box<Vector> = a; // copy handle, RC++
mutate b {
it.x += 10;
}
let v: Vector = unbox(a); // observes mutation
```
Explanation:
* `a` and `b` are `GateId` copies
* mutation writes to the same heap storage
* `unbox(a)` peeks/copies storage into SAFE value
### 10.2 No HIP for strings
```pbs
let s: string = "hello";
```
* string literal lives in constant pool
* `s` is a SAFE value referencing `ConstId`
---
## 11. Conformance Checklist
A VM is conformant with this spec if:
* it implements the four memory regions
* `GateId` is the only HIP pointer form
* `ALLOC(type_id, slots)` returns `GateId`
* heap access is only via gate resolution
* RC increments/decrements occur on gate copies/drops
* reclamation happens only at safe points
---
## Appendix A — Implementation Notes (Non-normative)
* Start with bump-alloc heap + never-reuse GateIds (simplest v0)
* Add free list later
* Add borrow/mutate enforcement later as debug-only checks