Files
prometeu-runtime/docs/specs/runtime/02-vm-instruction-set.md
T

15 KiB
Raw Blame History

Prometeu Virtual Machine (PVM)

Domain: VM subsystem overview Function: normative

This chapter defines the VM as an execution subsystem inside the PROMETEU machine.

It is intentionally narrower than the broader machine specs:

  • execution model;
  • opcode families;
  • verifier boundary;
  • relationship between the VM and adjacent specs.

For the bytecode-level instruction contract, see ../virtual-machine/ISA_CORE.md.

1 Scope

The PVM is a deterministic, stack-based VM designed for a fantasy console environment with fixed frame timing and explicit hardware-facing services.

This chapter does not fully restate:

  • detailed value and calling semantics;
  • heap/gate/GC internals;
  • single-context continuation internals;
  • host ABI policy.

Those now live in focused companion specs:

2 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 and explicit safepoints.
  3. Safe memory model: heap access is mediated by validated handles.
  4. Simple compilation target: stack-based bytecode with verified control flow.
  5. Stable ABI: calls and syscalls follow fixed slot-based contracts.
  6. First-class functions: user function values are represented through closures.

3 Execution Model

The PVM executes bytecode inside the PROMETEU frame loop.

Each frame:

  1. 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, the VM reaches the primary safepoint for threshold GC and host handoff;
  4. control returns to firmware/runtime orchestration.

FRAME_SYNC is the primary VM synchronization point. It is the boundary where the machine can safely account for:

  • GC opportunity;
  • logical frame handoff;
  • frame-completion semantics;
  • deterministic return to firmware.

4 Instruction Families

The public VM instruction surface is documented at the bytecode level in Core ISA. At the machine/spec level, the instruction families are:

  • execution control:
    • NOP, HALT, JMP, JMP_IF_FALSE, JMP_IF_TRUE, TRAP, FRAME_SYNC
  • stack manipulation:
    • PUSH_CONST, literal pushes, POP, POP_N, DUP, SWAP
  • arithmetic and logic:
    • numeric, comparison, boolean, and bitwise operations
  • variable access:
    • globals and locals
  • function calls:
    • CALL, RET, CALL_TRAIT
  • function values:
    • MAKE_CLOSURE, CALL_CLOSURE, GET_CAPTURE
  • VM/host boundary:
    • HOSTCALL, SYSCALL, INTRINSIC

Former coroutine numbers 0x54–0x56 are reserved. SPAWN, YIELD and SLEEP reject during loading, including unreachable code, and cannot be emitted by the assembler.

The machine-level rule is simple:

  • opcodes define explicit behavior;
  • there are no hidden execution paths;
  • timing-sensitive behavior is exposed through frame and safepoint semantics.

5 Verifier Boundary

Before execution, bytecode must pass the verifier.

The verifier ensures, at minimum:

  1. valid instruction decoding;
  2. valid jump targets;
  3. consistent stack depth across control-flow joins;
  4. valid call/return shape;
  5. closure call safety rules;
  6. patched syscall and intrinsic validity.

The verifier is structural. It does not replace runtime validation of dynamic values.

6 Relationship to Adjacent Specs

7 Summary

The PVM is:

  • stack-based;
  • deterministic;
  • frame-synchronized;
  • verifier-gated;
  • closure-capable;
  • single execution context; retired SPAWN/YIELD/SLEEP are rejected;
  • embedded inside the larger PROMETEU console model, not equal to it.

Program Registry integration

Program Registry and PBX v0 defines typed immediate domains, opcodes 0x0090–0x0096, complete multi-slot groups and conservative type-flow verification. Unknown facts require runtime validation and do not alone reject an otherwise valid join. Opcode bytes remain u16; TypeId immediates are u32 little-endian.

Typed Collection Instructions

These instructions require a validated Program Registry. Opcodes are u16 little-endian; TypeId and field immediates are u32 little-endian. T is the receiver descriptor, F its declared field type, E its Array element type. Stack order below is bottom to top; groups retain Registry component order.

Instruction Code Immediate Bytes Stack effect Full attempt cycles
STRUCT_NEW T 0x00A0 T 6 [] → ref 8 + sum(w(fields))
STRUCT_GET type=T, field=f 0x00A1 T, f 10 ref → slots(F) 3 + w(F)
STRUCT_SET type=T, field=f 0x00A2 T, f 10 ref, slots(F) → [] 4 + w(F)
ARRAY_NEW T 0x00A3 T 6 length:Int64 → ref 8 + N*w(E), valid N; otherwise 8
ARRAY_LEN T 0x00A4 T 6 ref → length:Int64 3
ARRAY_GET T 0x00A5 T 6 ref, index:Int64 → slots(E) 3 + w(E)
ARRAY_SET T 0x00A6 T 6 ref, index:Int64, slots(E) → [] 4 + w(E)

w is the resolved execution-slot width: scalar, String, color and concrete references use one; vec2, Trait and Dynamic use two; pixel uses three. Reference width never traverses referenced instances. The Struct construction sum is cached during bounded Registry resolution, with no PBX schema change. OpCode::cycles() supplies only the base component for these instructions.

STRUCT operations require a Struct descriptor; ARRAY operations require an Array descriptor, never its element TypeId or BuiltinId. Fields are immediate owner-local indices in declaration order. Every operation may trap; none branches, terminates or constitutes a safepoint. All instructions, including unreachable ones, undergo bounded structural verification and exact Registry height analysis. Finite type/group facts converge before proven conflicts are rejected. Unknown facts retain runtime checking; locals have no permanent type.

After charging the attempt, incomplete temporary operands trap with STACK_UNDERFLOW. Instance operations check receiver carrier, absence, liveness/generation, category, Registry and exact TypeId first; array access then checks exact Int64 index and bounds; SET checks the complete value group last. There is no numeric, Trait or Dynamic coercion. Negative lengths or indices and indices at/above length trap with OOB (0x03); wrong carriers/types/groups trap with TYPE (0x04); absent receivers with NULL_REFERENCE (0x0E); invalid/dead/stale handles with INVALID_HANDLE (0x0F). Positive lengths above u32, checked size/cost overflow, resource quotas and recoverable allocation failures trap with RESOURCE_LIMIT (0x10), preserving resource reason/requested/limit. Static invalid TypeIds/categories/fields produce LOAD_INVALID_REFERENCE; proven stack/type conflicts produce LOAD_INVALID_CODE. Runtime TrapInfo preserves the attempted PC, opcode and available source span.

Publication and ownership follow typed collection memory; charging follows time and cycles. See the producer handoff for independent byte oracles and construction examples. Production consumers must enter through the validated PBX v0 image boundary described in Program Registry.

Typed callable instructions are MAKE_CLOSURE (FunctionId,FnTypeId), CALL_CLOSURE (FnTypeId), GET_CAPTURE (index) and CALL_TRAIT (TraitTypeId,method_index). Their groups, encodings and attempted costs are defined in the Fn contract. Numbers 0x54–0x56 stay reserved and reject anywhere at load.

Random core integration

INTRINSIC also dispatches the VM-owned random operations, IDs 0x4000–0x4003. NEW cannot construct Random. TRAP_RANDOM_REJECTION_LIMIT is 0x00000015.

Logical guards and atomic storage publication

The core includes the following generic operations, with u16 opcodes and little-endian u32 immediates. They introduce no new Registry category, syscall, source-language collection or ambient transaction. Operand order below is bottom to top; all integer operands are Int64.

Opcode Immediate Stack operands consumed
INDEX_GUARD 0xA7 none index, exclusive limit
ARRAY_CHECK_LENGTH 0xA8 Array TypeId length
ARRAY_COPY 0xA9 Array TypeId source, sourceStart, target, targetStart, count
STORAGE_PUBLISH 0xAA Array TypeId, Struct TypeId, first field, second field source, sourceStart, target, targetStart, count, fillStart, fillCount, element group, owner, first field group, second field group

All operations return no values. INDEX_GUARD accepts exactly 0 <= index < limit, otherwise TRAP_OOB. It does not use physical storage length. ARRAY_CHECK_LENGTH accepts zero through u32::MAX without allocating. Negative lengths produce TRAP_OOB; values above u32::MAX produce the same resource SizeOverflow failure as ARRAY_NEW. This check does not reserve future allocation.

ARRAY_COPY and STORAGE_PUBLISH require exact Array receiver identities and complete stored groups. Every range must have nonnegative start/count and fit its physical array; an empty range may start at length. Invalid ranges produce TRAP_OOB, never clamping or truncation. Copy reads the pre-attempt source sequence, including for overlapping source/target ranges. Presence tags, immutable boxes, native owners and object identities are preserved without payload unpacking or repacking.

STORAGE_PUBLISH first copies the selected source range, then fills the selected target range with the supplied element group, then writes the two selected fields on the supplied Struct owner. Fields must be distinct valid indices on that Struct; their types and widths come from the immutable Registry. Source code/producer owns selection of every range, value, owner and field. The VM implements these generic ordered effects and does not select collection algorithms.

Loading validates all immediate identities/categories/fields even in unreachable code. Verification requires complete typed operands. ARRAY_COPY consumes five slots; STORAGE_PUBLISH consumes 8 + elementWidth + firstWidth + secondWidth. INDEX_GUARD consumes two slots and ARRAY_CHECK_LENGTH consumes one.

Execution validates all receivers, lengths/ranges, supplied groups and source groups, and reserves the complete charged copy scratch before writing. Validation, quota or host allocation refusal leaves all input operands and destinations unchanged, including both fields and native owners. Scratch uses TemporaryBytes, is refunded on success/refusal and does not relax any resource ceiling. Existing operands remain roots during preparation. There is no GC, callback, scheduler or other interleaving inside this single instruction. Commit uses already validated complete groups, performs no fallible allocation and consumes operands only after all selected effects have been published. No prepared token escapes the attempt.

Base cycle costs are 2 for either guard, 4 for ARRAY_COPY and 6 for STORAGE_PUBLISH. Copy adds 2 * count * elementWidth; publication additionally adds fillCount * elementWidth + firstWidth + secondWidth. Work arithmetic is checked before mutation. A refused preparation still charges the attempted work. Neither operation is a safepoint. Consumers must prepare any potentially failing return carrier and all call operands before publication; a series of ordinary stores is not a substitute for whole-operation safety.

Atomic publication of multiple Struct instances

FIELDS_PUBLISH (0xAB) has one little-endian u32 schema TypeId immediate. The schema MUST be a Registry Struct whose ordered field types are all Struct types. Names are descriptive only. The schema is declarative metadata; no request object, new Registry category or preparation token is allocated or exposed.

For each schema entry, the operand stack supplies one nullable destination reference followed by every destination field's complete typed value group, in field declaration order. The stack effect is the sum, over entries, of one plus the destination instance's initialization-slot count; no results are produced. Null skips that destination, but every supplied field group is still validated. Non-null destinations require exact concrete Struct identity and a live reference of the current session/generation. Array, Trait, Fn and builtin schema entries are invalid, including in unreachable instructions. The full schema and exact stack height/groups are checked under normal Registry admission/work limits.

Validate all destinations and value groups before any shared write or operand consumption. The original operands remain roots throughout preparation. Then write all fields in schema order, without allocation, fallible validation, callbacks, GC or scheduler interleaving, and consume the entire input. Input values are captured before publication; repeated destinations use ordered last-write semantics. Complete multi-slot/native/reference groups retain identity and normal ownership. A failed attempt preserves every destination and the operand stack.

The operation allocates no publication scratch or guest object. Operand/frame and source value preparation remain normally charged and may fail before publication. Base cost is 6 cycles. After the stack-height check, precharge one cycle per schema entry and one per destination field execution slot for the complete declared attempt, including skipped destinations. Quotas are unchanged. This is a generic typed storage mechanism; collection algorithms and node topology remain source-owned, with no collection-specific VM instruction or syscall.

Identity and value hashing

Identity and value hashing defines REF_IDENTITY_HASH 0x0097 and REF_IDENTITY_EQ 0x0098, complete typed source groups, one/two TypeId immediates, exact attempted costs and operand-preserving faults. It also defines intrinsics 0x4100–0x4102 and their shared bounded invocation profile. Old EQ and REF_* categories retain their contracts.