change ir to ir_vm and make it feature frozen

This commit is contained in:
Nilton Constantino
2026-01-29 16:45:02 +00:00
parent 4174d01a43
commit c34166435f
12 changed files with 197 additions and 331 deletions
+124 -258
View File
@@ -1,357 +1,223 @@
# PBS Compiler — Junie PR Plan
# PBS ⇄ VM Alignment — Junie PRs (HIP Semantics Hardening)
> **Purpose:** this document defines a sequence of small, focused Pull Requests to be implemented by *Junie*, one at a time.
> **Purpose:** fix semantic mismatches between the PBS frontend (Core IR) and the VM **before** any VM heap/gate implementation.
>
> **Audience:** compiler implementer (AI or human).
> These PRs are **surgical**, **mandatory**, and **non-creative**.
> Junie must follow them **exactly**.
> **Context:**
>
> **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`.
> * VM IR is frozen: new opcodes are forbidden unless explicitly planned in a PR titled “VM Instruction Set Change” with a full rationale + golden bytecode tests.
> * PBS frontend is implemented and produces Core IR.
> * Bytecode stability is a hard requirement.
> * VM currently has stack + const pool; heap exists but is unused.
> * HIP semantics (gates/storage) are currently **incorrectly lowered**.
> * `ir_vm` is feature-frozen at the moment. we are going to validate only `ir_core`
> * Lowering is the only place `ir_core` and `ir_vm` touch each other.
> - VM IR is never imported from Core IR.
> - Core IR never imports VM IR.
---
## Global Architectural Direction (Non-negotiable)
## Global Rules (Read Before Any PR)
* 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.
1. **No new features.** Only semantic correction.
2. **No new VM opcodes yet.** VM changes come later.
3. **No fallback values** (e.g. `FunctionId(0)`). Fail with diagnostics.
4. **Every PR must include tests** (golden or unit).
5. **Core IR is the source of semantic truth.**
---
# PR-01 — ProjectConfig and Frontend Selection
# PR-20 — Core IR: Make HIP Semantics Explicit (No Handle Loss)
### Goal
Introduce a project-level configuration that selects the frontend and entry file explicitly.
Fix the Core IR so HIP operations never lose the destination gate.
### Motivation
### Problem (Current Bug)
The compiler must not hardcode entry points or languages. PBS will be the first frontend, others may return later.
Current lowering evaluates a gate, reads storage, stores the result in a local, and later attempts to write back **without having the gate anymore**.
### Scope
This violates PBS semantics: storage access must always be mediated by the **original gate**.
* Add `ProjectConfig` (serde-deserializable) loaded from `prometeu.json`
* Fields (v0):
### Required Changes
* `script_fe: "pbs"`
* `entry: "main.pbs"`
* Refactor compiler entry point to:
#### 1. Extend Core IR instructions
* load config
* select frontend by `script_fe`
* resolve entry path relative to project root
Add explicit HIP instructions:
### Files Likely Touched
```rust
enum CoreInstr {
// existing …
* `compiler/mod.rs`
* `compiler/driver.rs`
* `common/config.rs` (new)
Alloc { ty: TypeId, slots: u32 },
### Tests (mandatory)
BeginPeek { gate: ValueId },
BeginBorrow { gate: ValueId },
BeginMutate { gate: ValueId },
* unit test: load valid `prometeu.json`
* unit test: invalid frontend → diagnostic
* integration test: project root + entry resolution
EndPeek,
EndBorrow,
EndMutate,
}
```
### Notes to Junie
Rules:
Do **not** add PBS parsing yet. This PR is infrastructure only.
* `Begin*` instructions **do not consume** the gate.
* Gate identity must remain available until the matching `End*`.
#### 2. Remove any lowering that copies HIP storage into locals
* No `ReadGate → SetLocal` pattern.
* Storage views are **not locals**.
### Tests (Mandatory)
* Golden Core IR test showing `BeginMutate(gate)` … `EndMutate` wrapping body
* Test asserting gate is still live at `EndMutate`
---
# PR-02 — Core IR Skeleton (PBS-first)
# PR-21 — Distinguish `peek`, `borrow`, and `mutate` in Core IR
### Goal
Introduce a **Core IR** layer independent from the VM IR.
Restore the semantic distinction mandated by PBS.
### Motivation
### Required Semantics
PBS semantics must be represented before lowering to VM instructions.
| Operation | Effect |
| --------- | ------------------------------- |
| `peek` | Copy storage → stack value |
| `borrow` | Temporary read-only view |
| `mutate` | Temporary mutable view + commit |
### Scope
### Required Changes
* Add new module: `ir_core`
* Define minimal structures:
* Lower PBS `peek` → `BeginPeek` / `EndPeek`
* Lower PBS `borrow` → `BeginBorrow` / `EndBorrow`
* Lower PBS `mutate` → `BeginMutate` / `EndMutate`
* `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
These **must not** share the same lowering path.
### Tests
* construct Core IR manually in tests
* snapshot test (JSON) for deterministic shape
* PBS snippet with all three operations
* Assert distinct Core IR instruction sequences
---
# PR-03 — Constant Pool and IDs
# PR-22 — Make Allocation Shape Explicit in Core IR
### Goal
Introduce a stable constant pool shared by Core IR and VM IR.
Stop implicit / guessed heap layouts.
### Scope
### Required Changes
* Add `ConstPool`:
* Replace any shape-less `Alloc` with:
* strings
* numbers
* Replace inline literals in VM IR with `ConstId`
* Update existing VM IR to accept `PushConst(ConstId)`
```rust
Alloc { ty: TypeId, slots: u32 }
```
Rules:
* `TypeId` comes from frontend type checking
* `slots` is derived deterministically (struct fields / array size)
### Tests
* const pool deduplication
* deterministic ConstId assignment
* IR snapshot stability
* Allocating storage struct emits correct `slots`
* Allocating array emits correct `slots`
---
# PR-04 — VM IR Cleanup (Stabilization)
# PR-23 — Eliminate Invalid Call Fallbacks
### Goal
Stabilize VM IR as a **lowering target**, not a language IR.
Prevent invalid bytecode generation.
### Scope
### Required Changes
* Replace string-based calls with `FunctionId`
* Ensure locals are accessed via slots
* Remove or internalize `PushScope` / `PopScope`
* Remove **all** fallbacks to `FunctionId(0)` or equivalent
* On unresolved symbols during lowering:
* Emit canonical diagnostic (`E_RESOLVE_UNDEFINED` or `E_LOWER_UNSUPPORTED`)
* Abort lowering
### Tests
* golden VM IR tests
* lowering smoke test (Core IR → VM IR)
* PBS program calling missing function → compile error
* No Core IR or VM IR emitted
---
# PR-05 — Core IR → VM IR Lowering Pass
# PR-24 — Validate Contract Calls in Frontend (Arity + Types)
### Goal
Implement the lowering pass from Core IR to VM IR.
Move contract validation to compile time.
### Scope
### Required Changes
* New module: `lowering/core_to_vm.rs`
* Lowering rules:
* During PBS type checking:
* Core blocks → labels
* Core calls → VM calls
* Host calls preserved
* No PBS frontend yet
* Validate argument count against contract signature
* Validate argument types
* Lower only validated calls to `HostCall`
### Tests
* lowering correctness
* instruction ordering
* label resolution
* Wrong arity → `E_TYPE_MISMATCH`
* Correct call lowers to Core IR `HostCall`
---
# PR-06 — PBS Frontend: Lexer
# PR-25 — Core IR Invariants Test Suite
### Goal
Implement PBS lexer according to the spec.
Lock in correct semantics before touching the VM.
### Scope
### Required Invariants
* Token kinds
* Keyword table
* Span tracking
* Every `Begin*` has a matching `End*`
* Gate passed to `Begin*` is available at `End*`
* No storage writes without `BeginMutate`
* No silent fallbacks
### Tests
* tokenization tests
* keyword vs identifier tests
* bounded literals
* Property-style tests or golden IR assertions
---
# PR-07 — PBS Frontend: Parser (Raw AST)
## STOP POINT
### Goal
After PR-25:
Parse PBS source into a raw AST.
* Core IR correctly represents PBS HIP semantics
* Lowering is deterministic and safe
* VM is still unchanged
### Scope
**Only after this point may VM PRs begin.**
* Imports
* Top-level declarations
* Blocks
* Expressions (calls, literals, control flow)
### Tests
* valid programs
* syntax error recovery
Any VM work before this is a hard rejection.
---
# PR-08 — PBS Frontend: Symbol Collection and Resolver
## Instruction to Junie
### Goal
If any rule in this document is unclear:
Resolve names, modules, and visibility.
* Stop
* Add a failing test
* Document the ambiguity
### Scope
Do not invent behavior.
* 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.
This document is binding.