Co-authored-by: Nilton Constantino <nilton.constantino@visma.com>
Reviewed-on: #8
This commit is contained in:
2026-03-24 13:40:22 +00:00
co-authored by Nilton Constantino
parent 05838d10b0
commit f9120e740b
128 changed files with 19414 additions and 4567 deletions
@@ -0,0 +1,321 @@
# 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.**
+268
View File
@@ -0,0 +1,268 @@
# 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**.
-357
View File
@@ -1,357 +0,0 @@
# PBS Compiler — Junie PR Plan
> **Purpose:** this document defines a sequence of small, focused Pull Requests to be implemented by *Junie*, one at a time.
>
> **Audience:** compiler implementer (AI or human).
>
> **Scope:** PBS-first compiler architecture. TS and Lua frontends are assumed **removed**.
>
> **Hard rules:**
>
> * Each PR must compile and pass tests.
> * Each PR must include tests.
> * No speculative features.
> * Follow the `Prometeu Base Script (PBS) - Implementation Spec`.
---
## Global Architectural Direction (Non-negotiable)
* PBS is the **primary language**.
* Frontend is implemented **before** runtime integration.
* Architecture uses **two IR layers**:
* **Core IR** (PBS-semantic, typed, resolved)
* **VM IR** (stack-based, backend-friendly)
* VM IR remains simple and stable.
* Lowering is explicit and testable.
---
# PR-01 — ProjectConfig and Frontend Selection
### Goal
Introduce a project-level configuration that selects the frontend and entry file explicitly.
### Motivation
The compiler must not hardcode entry points or languages. PBS will be the first frontend, others may return later.
### Scope
* Add `ProjectConfig` (serde-deserializable) loaded from `prometeu.json`
* Fields (v0):
* `script_fe: "pbs"`
* `entry: "main.pbs"`
* Refactor compiler entry point to:
* load config
* select frontend by `script_fe`
* resolve entry path relative to project root
### Files Likely Touched
* `compiler/mod.rs`
* `compiler/driver.rs`
* `common/config.rs` (new)
### Tests (mandatory)
* unit test: load valid `prometeu.json`
* unit test: invalid frontend → diagnostic
* integration test: project root + entry resolution
### Notes to Junie
Do **not** add PBS parsing yet. This PR is infrastructure only.
---
# PR-02 — Core IR Skeleton (PBS-first)
### Goal
Introduce a **Core IR** layer independent from the VM IR.
### Motivation
PBS semantics must be represented before lowering to VM instructions.
### Scope
* Add new module: `ir_core`
* Define minimal structures:
* `Program`
* `Module`
* `Function`
* `Block`
* `Instr`
* `Terminator`
* IDs only (no string-based calls):
* `FunctionId`
* `ConstId`
* `TypeId`
### Constraints
* Core IR must NOT reference VM opcodes
* No lowering yet
### Tests
* construct Core IR manually in tests
* snapshot test (JSON) for deterministic shape
---
# PR-03 — Constant Pool and IDs
### Goal
Introduce a stable constant pool shared by Core IR and VM IR.
### Scope
* Add `ConstPool`:
* strings
* numbers
* Replace inline literals in VM IR with `ConstId`
* Update existing VM IR to accept `PushConst(ConstId)`
### Tests
* const pool deduplication
* deterministic ConstId assignment
* IR snapshot stability
---
# PR-04 — VM IR Cleanup (Stabilization)
### Goal
Stabilize VM IR as a **lowering target**, not a language IR.
### Scope
* Replace string-based calls with `FunctionId`
* Ensure locals are accessed via slots
* Remove or internalize `PushScope` / `PopScope`
### Tests
* golden VM IR tests
* lowering smoke test (Core IR → VM IR)
---
# PR-05 — Core IR → VM IR Lowering Pass
### Goal
Implement the lowering pass from Core IR to VM IR.
### Scope
* New module: `lowering/core_to_vm.rs`
* Lowering rules:
* Core blocks → labels
* Core calls → VM calls
* Host calls preserved
* No PBS frontend yet
### Tests
* lowering correctness
* instruction ordering
* label resolution
---
# PR-06 — PBS Frontend: Lexer
### Goal
Implement PBS lexer according to the spec.
### Scope
* Token kinds
* Keyword table
* Span tracking
### Tests
* tokenization tests
* keyword vs identifier tests
* bounded literals
---
# PR-07 — PBS Frontend: Parser (Raw AST)
### Goal
Parse PBS source into a raw AST.
### Scope
* Imports
* Top-level declarations
* Blocks
* Expressions (calls, literals, control flow)
### Tests
* valid programs
* syntax error recovery
---
# PR-08 — PBS Frontend: Symbol Collection and Resolver
### Goal
Resolve names, modules, and visibility.
### Scope
* Type namespace vs value namespace
* Visibility rules
* Import resolution
### Tests
* duplicate symbols
* invalid imports
* visibility errors
---
# PR-09 — PBS Frontend: Type Checking
### Goal
Validate PBS semantics.
### Scope
* Primitive types
* Structs
* `optional<T>` and `result<T, E>`
* Mutability rules
* Return path validation
### Tests
* type mismatch
* mutability violations
* implicit `none` behavior
---
# PR-10 — PBS Frontend: Semantic Lowering to Core IR
### Goal
Lower typed PBS AST into Core IR.
### Scope
* ID-based calls
* ConstPool usage
* Control flow lowering
* SAFE vs HIP effects represented explicitly
### Tests
* PBS → Core IR snapshots
* semantic correctness
---
# PR-11 — Host-bound Contracts and Syscall Mapping
### Goal
Connect PBS host-bound contracts to runtime syscalls (without executing them).
### Scope
* Contract registry
* Mapping: contract.method → syscall id
* Core IR host call nodes
### Tests
* invalid contract calls
* correct syscall mapping
---
# PR-12 — Diagnostics Canonicalization
### Goal
Standardize diagnostics output.
### Scope
* Error codes (`E_*`, `W_*`)
* Stable messages
* Span accuracy
### Tests
* golden diagnostics
---
# PR-13 — Backend Integration (VM IR → Bytecode)
### Goal
Reconnect the pipeline to the Prometeu runtime backend.
### Scope
* VM IR → bytecode emission
* No PBS semantics here
### Tests
* bytecode emission smoke test
---
# PR-14 — End-to-End PBS Compile Test
### Goal
Prove the full pipeline works.
### Scope
* Sample PBS project
* Compile → bytecode
* Diagnostics only (no execution)
### Tests
* golden bytecode snapshot
---
## Final Note to Junie
Do **not** skip PRs.
Do **not** merge multiple PRs together.
If the spec is unclear, create a failing test and document the ambiguity.
This plan is the authoritative roadmap for PBS frontend implementation.
@@ -203,10 +203,10 @@ Visibility is mandatory for services.
### 3.4 Functions
```
FnDecl ::= 'fn' Identifier ParamList ReturnType? ElseFallback? Block
FnDecl ::= Visibility? 'fn' Identifier ParamList ReturnType? ElseFallback? Block
```
Top‑level `fn` are always file‑private.
Top‑level `fn` are `mod` or `file-private` (default). They cannot be `pub`.
---
+173
View File
@@ -0,0 +1,173 @@
# 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 Heap / Gate
| Code | Name | Meaning |
| ------------------- | -------------- | -------------------------- |
| `TRAP_INVALID_GATE` | Invalid gate | Non-existent gate handle |
| `TRAP_DEAD_GATE` | Dead gate | Gate with refcount = 0 |
| `TRAP_TYPE` | Type violation | Heap or gate type mismatch |
### 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.
---
@@ -59,6 +59,8 @@ Import resolution:
* The import prefix `@project:` is resolved relative to `{root}/src/main/modules`.
* Any path after `@project:` is interpreted as a **module path**, not a file path.
* `project` is declared into `prometeu.json` as the project name. and int the case of
missing it we should use `{root}` as project name.
If `{root}/src/main/modules` does not exist, compilation fails.
@@ -200,7 +202,7 @@ The **value namespace** contains executable and runtime-visible symbols.
Symbols in the value namespace are introduced by:
* `service`
* top-level `fn` - always file-private.
* top-level `fn` — `mod` or `file-private` (default).
* top-level `let` are not allowed.
Rules:
@@ -358,9 +360,9 @@ Top-level `fn` declarations define reusable executable logic.
Rules:
* A top-level `fn` is always **file-private**.
* A top-level `fn` cannot be declared as `mod` or `pub`.
* A top-level `fn` is visible only within the file where it is declared.
* A top-level `fn` is always **mod** or **file-private**.
* A top-level `fn` cannot be declared as `pub`.
* `fn` defaults to **file-private** visibility.
Example (VALID):
@@ -1388,6 +1390,23 @@ This avoids overloading the meaning of `TypeName.member`.
### 8.7 Summary of Struct Rules
Full example of `struct`:
```pbs
declare struct Vector(x: float, y: float)
[
(): (0.0, 0.0) as default { }
(a: float): (a, a) as square { }
]
[[
ZERO: default()
]]
{
pub fn len(self: this): float { ... }
pub fn scale(self: mut this): void { ... }
}
```
* Structs are declared with `declare struct`.
* Fields are private and cannot be accessed directly.
* Constructor aliases exist only inside the type and are called as `Type.alias(...)`.
+359
View File
@@ -0,0 +1,359 @@
# 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
@@ -0,0 +1,10 @@
# PRs for Junie — Compiler Dependency Resolution & Linking Pipeline
> Goal: Move dependency resolution + linking orchestration into **prometeu_compiler** so that the compiler produces a **single fully-linked bytecode blob**, and the VM/runtime only **loads + executes**.
## Non-goals (for this PR set)
* No lockfile format (yet)
* No registry (yet)
* No advanced SAT solver: first iteration is deterministic and pragmatic
* No incremental compilation (yet)