0XVM // DOCS VMIM V2 · SOURCE OF TRUTH

Everything the machine promises.

The contract, the assembly language, the Lua subset, and the implementation notes — browsable in one place, straight from docs/.

← Showcase
docs / Design Language

0xvm Visual Language & House Style Guide#

Status: House Guide (Opinionated Convention) Scope: 0xvm official hosts, built-in system ROMs (boot, monitor / inspector), and first-party ROMs Compatibility: Non-enforced for third-party ROMs (third-party creators may use custom palettes, layouts, fonts, and drawing styles)


1. Purpose & Boundary#

This document defines the house visual language for 0xvm in the spirit of uxn. It is a design guide for first-party hosts, system tools, and personal ROMs—not a rigid restriction on third-party ROM authors.

VM Contract vs. House Guide#

LayerEnforced by VM?Role in 0xvm
Video Device & Palette RegistersYesCore hardware/device interface allowing ROMs to draw and configure colors cleanly.
Asset Formats (.icn / .chr)Optional / HelperReference binary tile formats supported by helper tools; ROMs may use any data layout.
8 × 8 Grid, House Font & UI PrimitivesNo (House Guide)Shared visual grammar for first-party tools, system ROMs, and personal ROMs.
Host Themes (theme.cfg)Host-controlledApplies consistent colors across hosts and default ROMs unless a ROM explicitly sets its own palette.

Third-Party Styling Freedom#

  • Palette overrides: ROMs may set their own palette values when desired, falling back to the active host theme when left at default/unset.
  • Layout & typography freedom: Third-party ROMs are not restricted to 8 × 8 grid alignment, the house bitmap font, or house UI widgets.
  • Minimal host chrome: Hosts should avoid imposing heavy borders or intrusive framing that clashes with full-bleed or custom-styled ROMs.

2. Core Aesthetic Principles#

  1. Constraint breeds cohesion: Keep first-party visuals anchored to a 4-color palette rather than unconstrained RGB styling.
  2. Grid-first geometry: Align first-party UI elements to an 8 × 8 pixel cell (tile) with crisp pixel edges and no fractional coordinates or smooth drop shadows.
  3. Zero-chrome windowing: Keep OS-level chrome minimal; place menus, status readouts, and controls inside the ROM/system viewport when appropriate.
  4. Data is visual: Render memory, stack, and register views using the same tile and pixel primitives used by interactive programs and games.

3. Virtual Screen & Palette Convention#

Display & Layer Model#

  • Tile Unit: 8 × 8 pixels.
  • Reference Resolution: 320 × 200 pixels (40 × 25 tiles) or 256 × 256 pixels (32 × 32 tiles), chosen to scale cleanly at integer multipliers and map to terminal cell/sub-pixel renderers.
  • Layers:
    • Background (BG): Persistent surface for static panels, text, and grids.
    • Foreground (FG): Overlay surface (index 0 transparent) for cursors, active highlights, sprites, and tooltips.

4-Color Palette Slots (0–3)#

First-party tools and ROMs assign consistent semantic meaning to the 4 palette indices while allowing hosts to load themes (theme.cfg):

IndexSemantic RoleDefault ("Deep Ink")Alternate ("Paper")
0Canvas / Background / Transparent (FG)#060907#FBFCF8
1Primary Ink / Text / Active Borders#F2F6F0#0B100C
2Structural Accent / Muted Frames / Grids#2A352C#C7D0C6
3Highlight / Cursor / Focus / Alert / Pale Green Accent#B9E5AD#4E8B5A
  • Contrast & Accent Discipline: Keep body text high-contrast (index 1 on 0, or inverted 0 on 1). The default theme is intentionally extreme: a near-black canvas with near-white ink. The pale-green accent keeps its hue in both themes; the light theme uses a deeper green variant to preserve contrast. Reserve index 3 for focus states, active cursors, key indicators, and primary controls rather than large background fills.

4. Binary Tile Formats (.icn & .chr)#

  • .icn (1-bit tile — 8 bytes): 8 rows of 8 bits (0 or 1). Suitable for monochrome bitmap fonts, icons, borders, and dither patterns.
  • .chr (2-bit tile — 16 bytes): Two 8-byte bitplanes (plane_low followed by plane_high), producing 2-bit values (0–3) per pixel for shaded sprites and emblems.

5. Typography & UI Primitives#

House Bitmap Font (0xfont.icn)#

  • Cell Size: 8 × 8 pixels per glyph, with clear visual separation for hex characters (0–9, A–F) and unambiguous punctuation/brackets.
  • Control / UI Glyphs: Reserve low control slots for compact icons (arrows, close/check marks, folder/file/ROM markers, play/pause, and pointer indicators).

Standard House UI Primitives#

  1. Hairline Box: 1-pixel border in color 2 with crisp corners or subtle 1-pixel corner chamfers.
  2. Header Strip: Single 8px row with inverted styling (index 0 on 1) showing title/mode on the left and status/address/state on the right.
  3. Buttons & Toggles: Flat rectangles with square corners. Idle controls use color 2 as fill with color 1 text; primary/active controls use color 3 as fill with color 0 text. No brackets, gradients, rounded corners, or press offset. Focus is a 1px color 3 outline; hover only shifts the border to color 3.
  4. Dithered Tracks & Scrollbars: 1-bit checkerboard/dither pattern in color 2 for tracks, with solid thumb markers in color 1 or 3.
  5. Cursor: Crisp pointer/crosshair on FG with a contrasting outline so it remains readable across light and dark regions.

6. Host & Ecosystem Alignment#

  • Boot / Empty State: Launching a host without a ROM boots the built-in system ROM (boot.rom) using the house style to display system info, memory/state views, and ROM loading. All first-party hosts do this by default; the CLI, SDL3, and browser binaries embed the same assembled bytes.
  • Boot ROM reference: examples/boot.asm is the canonical first-party splash. It reads SYS_CAPS and takes exactly one path: text-only hosts receive the docs/LOGO.txt block-glyph grid on the terminal (wordmark excluded) plus the author, license, and VM specifications; screen hosts copy assets/logo.png 1:1 into a 200×144 dithered emblem with a hard color-2 shadow and show centered author, license, and VM specification lines, using the Deep Ink palette slots, an inverted header strip, a hairline content box, and a color-3 status line; the frame remains visible until Escape or a window close, so it runs indefinitely by default. The wordmark from the source block is not rendered in either path.
  • Browser host controls: build/0xvm-wasm.html opens boot.rom automatically. Run/Pause, Restart, load-file, four screen-size presets (320×240, 640×480, 800×600, and 1024×768), and console controls remain available; choosing a preset restarts the current ROM at that resolution. Demo-ROM links and ?rom= selection are intentionally omitted.
  • Scaling & Framing: Prefer integer scaling (1x, 2x, 3x, ...) and optional outer padding in color 0 so content sits cleanly inside the window.
  • Terminal Host Parity: Map the 4 palette slots to terminal colors and render sub-pixels via half-block or quadrant Unicode glyphs while keeping layout proportions consistent.
  • Naming & Documentation: Use consistent 0x hex notation, lowercase identifiers where idiomatic, and clean diagrams aligned with the house visual rules.
docs / Machine Contract

Machine Contract (v2)#

Status: implemented and frozen. This document defines the observable

machine that the assembler, emulator, ROMs, and hosts agree on. ABI v2 replaces

the transitional core I/O opcodes of v1 with a device page and two port

opcodes. ROMs from v1 that contain PRINT*/READ* opcodes are not compatible.

0. Decisions#

QuestionDecision
Base architectureKeep the 64-bit core: 64-bit cells, 64-bit arithmetic, floats, CALL/ENTER/LOCAL_*
Address space64 KiB, byte-addressed, 16-bit addresses
Instruction encoding8-bit opcode with fixed, per-opcode immediate widths
I/OHost device callbacks through DEI/DEO; no I/O opcodes in the core

Non-goals for this contract: moving a running machine between hosts, dynamic memory growth, and host-specific I/O policy in the core. The machine is local; ROMs are its distribution unit.

1. Design principles#

  1. Implementation-first. A feature is only added if the cost of implementing

it in a second emulator remains small.

  1. Frozen ABI. Opcode numbers, memory map, image format, and device ports do

not change casually. This is what lets ROMs outlive their assembler.

  1. ROM is the distribution unit. Programs are shipped as byte images, not as

text that must be re-parsed by every host.

  1. Thin host boundary. The core knows only bytes, stacks, RAM, and two port

opcodes. Screens, keyboards, and files belong to host devices.

2. Numbers and representation#

  • A cell is 64 bits (int64_t). Two's-complement wrapping arithmetic is

used for ADD, SUB, MUL, shifts, and bitwise ops.

  • Floats are raw IEEE-754 bit patterns in cells; the VM has no type tags.
  • Addresses and instruction pointers are 16-bit unsigned (uint16_t).
  • All multi-byte values — immediates and RAM values — are big-endian.
  • ticks is a 64-bit count of successfully executed instructions, including

HALT and device-driven halts.

3. Machine state#

The state consists of registers, one operand stack, call-frame metadata, allocator metadata, addressable RAM, and host device callbacks. Stacks and metadata live outside addressable RAM, as in Uxn; only mem is reachable by load/store instructions.

FieldWidthMeaning
ip16-bitByte address of the next instruction in mem
sp16-bitNumber of live cells on the operand stack (0..256)
fp16-bitIndex in the stack of the current frame's first local
fsp16-bitNumber of live call frames (0..64)
hp16-bitAllocator bump pointer into the heap region; initial value 0x4000
ticks64-bitSuccessfully executed instructions
devpointersHost read/write callbacks plus an opaque context

Device callbacks are host wiring, not machine state: vm_free() and image loading preserve callbacks installed after vm_init(). A fresh vm_init() starts with no device callbacks, so a host installs them before running a ROM.

Fixed capacities:

  • operand stack: 256 cells (2048 bytes outside RAM)
  • call frames: 64 entries (ret_ip, prev_fp)
  • allocator blocks: 64 entries (addr, size, live)
  • addressable RAM: 65536 bytes (mem[0x0000..0xFFFF])
  • device ports: 256 entries outside RAM

No buffer grows at runtime. Overflow, underflow, and exhausted metadata are errors, not wrap-around behaviour.

4. Memory map#

0x0000 ─────────────── zero page (addressable, 256 bytes)
0x0100 ─────────────── ROM image: code + static data
0x3FFF ─────────────── end of image region
0x4000 ─────────────── heap start (hp initial value)
0xFFFF ─────────────── end of RAM

device page: 256 ports, outside RAM, addressed only by DEI/DEO
  • The image loader writes the ROM payload at 0x0100. Maximum payload size is

0x3F00 bytes (16128).

  • 0x0000..0x00FF is ordinary addressable RAM, intended for frequently used

variables. It is not pre-filled by the ROM.

  • ALLOC returns addresses in 0x4000..0xFFFF; the heap grows upward from

0x4000. Allocation sizes are rounded up to a multiple of 8.

  • Ports are not RAM addresses: DEI/DEO immediates select host devices,

and no load/store instruction can reach them.

5. Instruction encoding#

Every instruction starts with one opcode byte. Assigned opcodes are explicit because retired I/O opcodes remain reserved:

  • 0x00..0x40, 0x46..0x7F: current core opcodes and reserved slots.
  • 0x0E and 0x41..0x45: permanently unassigned (retired v1 I/O opcodes).
  • 0x80: DEI (device input).
  • 0x81: DEO (device output).
  • 0x82..0xFF: reserved for future devices/vectors.

Immediate widths are fixed per opcode:

ImmediateOpcodesTotal bytesEncoding
noneall others1—
1 byteENTER (0x2E), LOCAL_GET (0x2F), LOCAL_SET (0x30), DEI (0x80), DEO (0x81)2unsigned index/port 0..255
2 bytesJMP (0x09), JMP_Z (0x0A), CALL (0x2B)3big-endian absolute byte address
8 bytesPUSH (0x02), PUSHF (0x32)9big-endian int64 / raw 64-bit double

Fetching an instruction means reading mem[ip], determining its immediate width from this table, advancing ip by 1 + width, and decoding the immediate bytes from mem. Jump and call targets are absolute byte addresses, not instruction indices.

CALL_I (0x2C) and JMP_I (0x31) are single-byte opcodes that take their target from the stack.

6. Execution semantics#

  • HALT (0x00) leaves ip on the halt instruction and returns VM_HALTED.
  • RET (0x2D) pops a result, restores ip and fp from the top frame, and

leaves the result on the caller's stack.

  • CALL (0x2B) pushes {return_ip, fp} and jumps; ENTER n reserves n zeroed

locals at [fp, fp+n); LOCAL_GET/LOCAL_SET index only that region.

  • ALLOC pops a positive size, rounds to 8, reuses a dead block when one fits,

otherwise bumps hp; FREE marks a live block dead.

  • Loads and stores may address any byte in RAM: the full access width must

fit in 0x0000..0xFFFF. This lets programs read static data directly from the image region. hp constrains only ALLOC/FREE, not ordinary loads/stores. Multi-byte values use big-endian byte order.

  • DEI port checks stack room, reads one cell from the host, then pushes it.
  • DEO port requires a cell, writes it to the host, then pops it. A callback may

return VM_OK, VM_HALTED, or VM_ERR_IO.

PRINT, FPRINT, PRINT_STR, PRINT_CHAR, READ_INT, and READ_STR are not opcodes. They are optional macros in stdlib/console.asm that expand to device port accesses in the payload, and a program opting in must INCLUDE that file. The same is true of INC/DEC/NEG and GET/SET in stdlib/. The source-level INCLUDE, IF/IFDEF/IFNDEF, and MACRO directives are processed by the assembler and emit no instruction, opcode, device port, or ROM header change.

7. Reset and halt#

On load:

  1. all of mem is zeroed;
  2. stacks, frames, and block metadata are zeroed; sp = fp = fsp = 0;
  3. hp = 0x4000;
  4. ip is set to the image entry point (normally 0x0100);
  5. ticks = 0;
  6. installed device callbacks are preserved.

Execution proceeds until HALT, a device halt, or an error. There is no interrupt mechanism in this contract; event vectors are reserved for a future device extension.

8. Image format#

ROM files use a 16-byte header followed by the payload:

OffsetSizeField
04Magic 56 4D 49 4D ("VMIM")
41Format version, currently 2
51Flags, must be 0
62Reserved, must be 0
82Payload length, big-endian, 0..0x3F00
102Entry point, big-endian, normally 0x0100
124Reserved, must be 0

The loader copies exactly payload length bytes to mem[0x0100..], zeroes the remainder of RAM, and sets ip to the entry point. The entry point must lie inside the loaded payload; otherwise loading fails.

9. Errors#

The machine is not total: invalid opcodes, bad jump targets, stack overflow/underflow, bad addresses, allocation failures, and device failures return the existing VM_ERR_* statuses. A failed instruction leaves all VM state unchanged (atomic error handling), which is required by the test suite and is valuable for debuggers. Uxn's "any byte sequence is a valid program" property is deliberately not adopted.

A device callback that changes host state is a side effect outside VmState; callbacks must not mutate VM state unless they can complete successfully. On a device halt, ip stays on the DEI/DEO instruction and ticks increments; DEO consumes its cell, while DEI does not push a result.

10. Host boundary#

The core depends on no platform headers and performs no I/O itself. A host provides:

  • a ROM image to load;
  • a step/run loop;
  • device callbacks with this shape:
VmStatus read(void *ctx, VmState *vm, uint8_t port, int64_t *out);
VmStatus write(void *ctx, VmState *vm, uint8_t port, int64_t value);

Callbacks return VM_OK, VM_HALTED, or VM_ERR_IO. The callback context and all formatting/input policy belong to the host. Both supplied hosts share the System/Console implementation in apps/common/host.c; 0xvm-sdl also supplies Screen, Controller, and timer ports:

PortNameAccessMeaning
0x00VM_SYS_VERSIONreadROM format version
0x01VM_SYS_DEBUGread/writetick-prefix flag
0x02VM_SYS_HALTwritehalt with VM_HALTED
0x03VM_SYS_CAPSreadhost capability bitmask (see below)
0x10VM_CONSOLE_PUTCwritelow byte to stdout
0x11VM_CONSOLE_GETCreadone byte from stdin (0 on EOF)
0x12VM_CONSOLE_PUTIwritesigned decimal + newline
0x13VM_CONSOLE_PUTFwritedouble bits + newline
0x14VM_CONSOLE_PUTS_ADDRwriteRAM address of the string to write
0x15VM_CONSOLE_PUTS_LENwritelength of the string to write
0x16VM_CONSOLE_PUTSwritestring + newline (value ignored)
0x17VM_CONSOLE_GETS_ADDRwriteRAM address for input
0x18VM_CONSOLE_GETS_MAXwritemaximum input length
0x19VM_CONSOLE_GETSwriteread a line into RAM (value ignored)
0x1AVM_CONSOLE_GETS_LENreadlength from the last GETS
0x1BVM_CONSOLE_GETIreadone integer from stdin
0x20VM_SCREEN_WIDTHreadframebuffer width in pixels
0x21VM_SCREEN_HEIGHTreadframebuffer height in pixels
0x22VM_SCREEN_COLORwriteRGB colour in the low 24 bits
0x23VM_SCREEN_PIXELwritex in the high 16 bits, y in the low 16
0x24VM_SCREEN_DRAWwritepresent the framebuffer (value ignored)
0x25VM_SCREEN_CLEARwritefill with the current colour (value ignored)
0x30VM_CONTROLLER_KEYreadnext key-down, 0 if none (consumes)
0x31VM_CONTROLLER_QUITread1 after a window-close request
0x40VM_TIMER_MSreadmilliseconds since host start

VM_SYS_CAPS is always readable and returns a bitmask of VM_CAPS_CONSOLE (0x01), VM_CAPS_SCREEN (0x02), VM_CAPS_CONTROLLER (0x04), and VM_CAPS_TIMER (0x08). A ROM can branch on this mask before touching optional devices; the Console is always present in the supplied hosts.

Screen, Controller, and timer ports are optional: a ROM that uses them depends on a host that provides them, and reads of unprovided ports return VM_ERR_IO. Controller key codes are 0 for none, 1..4 for up/down/left/right, 5 for space, 6 for enter, 7 for escape, 8 for backspace, 9 for delete, and 32..126 for printable ASCII. A key is delivered once and cleared by the read. Other hosts may assign different meanings to other ports.

Read ports are synchronous and blocking: GETC, GETI, and GETS wait for host input and have no ready/status port. GETC reports EOF as 0; GETI reports EOF, unparseable input, and overflow as 0; GETS reports EOF as an empty line. Stream errors return VM_ERR_IO.

Instruction tracing (-t) and the -D tick prefix are host policies, not machine state. -D enables VM_SYS_DEBUG, which the Console device reads when formatting output.

11. Implementation status#

The current codebase conforms to this contract:

  1. Programs are bytes in mem; vm_step fetches and decodes from ip.
  2. VmState contains fixed arrays for RAM, stack, frames, and block metadata;

the core never calls realloc and contains no stdio calls.

  1. ip, jump/call targets, CALL return addresses, and assembler labels are

absolute 16-bit byte addresses.

  1. The assembler emits a v2 VMIM ROM and maps source lines by absolute byte

address. Static data stays in the image region; the image is not copied into the heap.

  1. Core I/O opcodes are gone. DEI/DEO are the only I/O instructions, and

PRINT*/READ* are optional stdlib macros that expand to Console ports.

  1. 0xvm accepts assembly source or a ROM, 0xasm writes a ROM, 0xdis

decodes source or a ROM (labelling reserved bytes and reporting truncated immediates), 0xrom validates and prints ROM headers, and 0xvm-sdl installs System/Console callbacks; 0xvm-sdl also adds Screen, Controller, and timer.

  1. tests/conformance.asm is an executable v2 conformance image. It exercises

every opcode and immediate shape, the full System/Console port set, and ends with VM_SYS_HALT. A passing run emits the golden transcript in tests/conformance.expected; the CLI input is B-7\nhey\n. make conformance-check runs the shipped ROM through 0xvm, make sdl-check runs it through 0xvm-sdl with dummy video, and 0xtest runs the same image through a fresh scripted host.

  1. C-level conformance cases check atomic errors for reserved/retired opcodes,

truncated immediates at the RAM boundary, stack overflow/underflow, division by zero, bad addresses and jump targets, bad frames and locals, heap overflow, and device errors.

docs / Assembly Language

0xvm Assembly Language#

Language reference for VMIM v2 assembly source.

This document describes the source language accepted by 0xasm. For the frozen binary contract, see the Machine Contract. For encoder and interpreter implementation details, see VM Implementation.

1. Program model#

A program is written as one or more assembly source files, assembled into a VMIM ROM, then loaded by a host.

./build/0xasm -f program.asm -o program.rom
./build/0xvm -f program.rom

The machine model relevant to source code is:

  • A cell is a signed 64-bit integer. Arithmetic is two's-complement wrapping.
  • A byte address is 16 bits. ip and all jump/call targets are absolute byte

addresses, not instruction indices.

  • RAM is 64 KiB. The ROM image is loaded at 0x0100; static data and code live

in the image. The heap starts at 0x4000.

  • The operand stack, call frames, and allocator metadata live outside

addressable RAM. Only mem is reachable by LOAD*/STORE*.

  • I/O is not part of the instruction set. DEI and DEO access a 256-entry

device page supplied by the host.

  • The assembler has no built-in pseudo-ops. Readable aliases such as INC,

PRINT, and SET_COLOR are opt-in macros from stdlib/.

2. Lexical structure#

Statements#

  • One instruction or directive per line.
  • Mnemonics, directive names, and macro names are case-insensitive. Labels,

constants, and macro parameter names are case-sensitive.

  • Labels have the form name:; names start with a letter or _ and continue

with letters, digits, or _.

  • A label may share a line with an instruction or data directive.
loop:
    PUSH 1
    ADD
    JMP loop

Comments#

Comments start with ;, #, or // and run to the end of the line. Comment markers inside quoted strings are literal text.

PUSH 42       ; decimal
PUSH 0x2A     # hex
STR "a//b"    // the slashes are part of the string

Operands#

Instruction operand kinds are:

KindUsed byExample
noneHALT, DUP, RET, ...HALT
integer expressionPUSH, ENTER, LOCAL_GET/SET, data directivesPUSH N*2
float literalPUSHFPUSHF 1.5
jump targetJMP, JMP_Z, CALLJMP done
device portDEI, DEODEO CONSOLE_PUTC

Missing or illegal operands are reported with source line numbers. DEI and DEO ports must be expressions in 0..255.

3. Expressions and constants#

Integer expressions are accepted by PUSH, ENTER, LOCAL_GET, LOCAL_SET, CALL, jump targets, DEI/DEO ports, and numeric data directives.

FormExamples
Decimal42, -7
Hexadecimal0x2A, 0xFFFF
Named constantN, WIDTH
Parentheses(N + 1) * 2
Unary operators+x, -x, ~x
Binary operators`+ - * / % << >> & ^== != < <= > >=`

VM_IMAGE_START is a C header macro, not a built-in assembler constant. Define EQU VM_IMAGE_START 0x0100 yourself if you want that name in source.

Operator precedence, from highest to lowest: primary expressions, unary + - ~, * / %, + -, << >>, comparisons (== != < <= > >=, one level), &, ^, |. Arithmetic uses uint64_t wrapping; division by zero and UINT64_MAX / UINT64_MAX are assembler errors; shifts of 64 or more yield zero. The literal -9223372036854775808 is accepted as INT64_MIN.

Define constants with EQU:

EQU WIDTH 320
EQU HEIGHT 200
EQU CELL_BYTES WIDTH * HEIGHT

Constants are evaluated assembly-time only. The name must be label-style, duplicates are rejected, and each expression is evaluated immediately when the EQU is read. The same expression grammar is used by IF and ELIF, except those branches may reference constants only.

PUSHF takes a floating-point literal only, not an expression or constant, and pushes its raw IEEE-754 bit pattern as a cell. The token must be shorter than 128 bytes and fully accepted by strtod() without range error. The VM has no type tags, so the same cell can be interpreted as an integer or a double.

4. Instruction set#

Stack effects are written bottom-to-top, so the rightmost value is the top. For binary operations, b is popped first and a is the value below it.

4.1 Core and control flow#

InstructionEffectDescription
HALT[...] → [...]Stop with VM_HALTED; ip stays on the opcode
NOP[...] → [...]Advance ip and ticks
PUSH x[...] → [..., x]Push a big-endian int64 immediate
POP[..., x] → [...]Discard the top
DUP[..., x] → [..., x, x]Duplicate the top
ADD[..., a, b] → [..., a+b]Wrapping 64-bit addition
SUB[..., a, b] → [..., a-b]Wrapping 64-bit subtraction
MUL[..., a, b] → [..., a*b]Wrapping 64-bit multiplication
CMP_LT[..., a, b] → [..., 0\|1]Signed less-than
JMP target[...] → [...]Set ip to an absolute byte address
JMP_Z target[..., c] → [...]Pop c; jump if zero
JMP_I[..., target] → [...]Pop target and jump

Comparisons and logical operations push 1 or 0, so they feed JMP_Z directly.

4.2 Arithmetic, comparison, bitwise, and logical#

InstructionEffectDescription
DIV[..., a, b] → [..., a/b]Truncates toward zero; INT64_MIN / -1 wraps
MOD[..., a, b] → [..., a%b]Sign of a; INT64_MIN % -1 is 0
CMP_EQ / CMP_NE[..., a, b] → [..., 0\|1]Equality / inequality
CMP_LE / CMP_GT / CMP_GE[..., a, b] → [..., 0\|1]Signed comparisons
AND / OR / XOR[..., a, b] → [..., a op b]64-bit bitwise operations
NOT[..., a] → [..., ~a]Bitwise complement
SHL / SHR[..., a, b] → [..., a shift b]Count masked to 0..63; SHR is logical
LNOT[..., a] → [..., !a]Logical NOT of a booleanized operand
LAND / LOR[..., a, b] → [..., a && b \| a \|\| b]Logical AND / OR

A zero divisor returns VM_ERR_DIV_ZERO without changing the stack.

4.3 Stack shuffling#

InstructionEffectDescription
SWAP[..., a, b] → [..., b, a]Exchange the top two
OVER[..., a, b] → [..., a, b, a]Copy the second item to the top
ROT[..., a, b, c] → [..., b, c, a]Rotate the top three
PICK[..., x, n] → [..., x_n]Pop n, copy stack[sp-2-n]; n=0 duplicates the new top

4.4 RAM and heap#

InstructionEffectDescription
LOAD8 / LOAD16[..., addr] → [..., value]Unsigned byte / 16-bit read
LOAD32[..., addr] → [..., value]Signed 32-bit read, sign-extended
LOAD32U[..., addr] → [..., value]Unsigned 32-bit read, zero-extended
LOAD64[..., addr] → [..., bits]Raw 64-bit read
STORE8 / STORE16 / STORE32 / STORE64[..., val, addr] → [...]Write 1/2/4/8 bytes; address is on top
ALLOC[..., size] → [..., addr]Allocate a heap block, reusing free blocks
FREE[..., addr] → [...]Mark a live block dead for reuse

ALLOC requires a positive size, rounds up to a multiple of 8, and returns an address in the heap region. FREE requires a live block's start address.

4.5 Procedures and locals#

InstructionOperandEffectDescription
CALLtarget[...] → [...]Push {return address, fp}, set fp = sp, jump
CALL_I—[..., target] → [...]Pop target, then call
RET—[..., result] → [..., result]Unwind one frame, leave result for caller
ENTER n0..255[...] → [..., 0 × n]Reserve n zeroed locals at [fp, fp+n)
LOCAL_GET i0..255[...] → [..., local]Push stack[fp+i]
LOCAL_SET i0..255[..., v] → [...]Pop v into stack[fp+i]

Locals share the 256-cell operand stack with ordinary pushes. A typical procedure body starts with ENTER n, then uses LOCAL_SET/LOCAL_GET. RET requires a result on the stack.

4.6 Floats#

InstructionEffectDescription
PUSHF x[...] → [..., bits]Push a raw 64-bit double literal
FADD / FSUB / FMUL / FDIV[..., a, b] → [..., bits]Double-precision arithmetic
FNEG / FABS / FSQRT[..., a] → [..., bits]Unary double operations
FCMP_LT / FCMP_EQ / FCMP_LE / FCMP_GT / FCMP_GE[..., a, b] → [..., 0\|1]Double comparisons
FTOI[..., bits] → [..., int]Truncating conversion; NaN/overflow saturate
ITOF[..., int] → [..., bits]int64_t to double

4.7 Device access#

InstructionEffectDescription
DEI port[...] → [..., value]Read a cell from the host device
DEO port[..., value] → [...]Pass the top cell to the host device

Port constants are supplied by stdlib/ports.asm. System and Console ports are available on every host; Screen, Controller, and timer ports depend on host capabilities. See Devices below.

4.8 Encoding summary#

ImmediateInstructionsTotal bytesEncoding
nonemost opcodes1—
1 byteENTER, LOCAL_GET, LOCAL_SET, DEI, DEO2unsigned index/port
2 bytesJMP, JMP_Z, CALL3big-endian absolute byte address
8 bytesPUSH, PUSHF9big-endian int64 / raw double bits

JMP_I and CALL_I take their target from the stack and are single-byte instructions. Frozen opcode numbers are listed in the Machine Contract.

5. Data directives and image layout#

The first pass records instructions, data directives, and labels. The second pass assigns absolute addresses and emits this layout:

VM_IMAGE_START + 0:  JMP <code_start>       (3-byte entry stub)
VM_IMAGE_START + 3:  static data from DB/DW/DQ/STR/ALIGN
VM_IMAGE_START + n:  encoded instructions
DirectiveMeaning
DB a, b, ...Emit bytes
DW a, b, ...Emit big-endian 16-bit values
DQ a, b, ...Emit big-endian 64-bit values
STR "text"Emit a string with no automatic terminator
ALIGN nPad the data area to a multiple of n (1..4096)

STR understands \n, \r, \t, \0, \\, \", and \xNN escapes. Labels on data directives resolve to absolute RAM addresses, so programs read and write static data with LOAD*/STORE*. The image is not copied into the heap. ALIGN pads the data area itself; a label written on the ALIGN directive is assigned before the padding is emitted.

EQU GREETING_LEN 7

greeting:
    STR "hello\n"
    DB 0

    PUSH greeting
    PUSH GREETING_LEN
    PRINT_STR                 ; expects [addr, len]

Labels are whole operands only: they work as jump targets or as values for PUSH, but cannot be combined with arithmetic in data directives. Use EQU constants for lengths and counts.

The assembled payload must fit in VM_IMAGE_MAX (16128 bytes).

6. Source directives#

These directives are expanded by the assembler and emit no VM opcodes.

6.1 Includes#

INCLUDE "all.asm"
INCLUDE "graphics/sprites.asm"

Relative paths resolve against the including file's directory; a path is treated as absolute only when it begins with /. Quoted paths recognise \n, \r, and \t; any other backslash is dropped before the next character. 0xasm -I DIR adds search directories after the including file's directory and before the built-in stdlib/ directory. Includes may nest 32 levels; cycles are rejected. Diagnostics inside included files use file:line: prefixes.

6.2 Conditionals#

IF WIDTH == 320
    ; ...
ELIF WIDTH == 640
    ; ...
ELSE
    ; ...
ENDIF

IFDEF DEBUG
    ; ...
ENDIF

IFNDEF NO_SCREEN
    ; ...
ENDIF

IF/ELIF use the constant-only expression grammar. IFDEF/IFNDEF test whether a constant or macro name is defined, not a label. Constant names are case-sensitive; macro names are case-insensitive. Inactive branches are skipped but still parsed for balanced directives; they cannot define constants, labels, or macros.

6.3 Macros#

MACRO INC
    PUSH 1
    ADD
ENDMACRO

MACRO STORE_XY value, x, y
    PUSH %value
    PUSH %x
    PUSH %y
    CALL pixel_addr
    STORE8
ENDMACRO
  • MACRO name p1, p2, ... ends with ENDMACRO or ENDM.
  • Parameters are %1, %2, ... or %p1, %p2, ...; parameter names are

case-sensitive.

  • %% expands to a unique prefix, making labels such as %%done safe to reuse.
  • Invocation requires exactly the declared number of arguments. Commas inside

quotes, parentheses, or brackets stay within one argument.

  • Macro names are case-insensitive and may not shadow instructions or

directives. Zero-parameter macros are allowed.

  • Nesting is limited to 32 levels; recursion is rejected by that limit.
  • Macro-generated bytes use the invocation line and the display path

<macro NAME> in traces and diagnostics.

7. Standard library#

stdlib/ is a set of opt-in, idempotent macro files. Include all.asm to pull in the general-purpose modules, or include individual files. Every file is guarded with IFNDEF, so repeated inclusion is harmless. Duplicate macro names are rejected: to replace a stdlib macro, omit that module or predefine its guard constant (for example STD_ARITH) before including it, then define your own.

ModuleProvides
all.asmUmbrella include for 11 general-purpose modules; ports.asm arrives indirectly through console, screen, controller, and timer
arith.asmINC, DEC, NEG
locals.asmGET/SET aliases for LOCAL_GET/LOCAL_SET
console.asmPRINT_CHAR, PRINT, FPRINT, READ_INT, PRINT_STR, READ_STR
ports.asmSYS_*, CAPS_*, CONSOLE_*, SCREEN_*, CONTROLLER_*, TIMER_* constants
screen.asmSCREEN_SIZE, SET_COLOR, PLOT_XY, PLOT, DRAW, CLEAR
controller.asmREAD_KEY, QUIT_REQUESTED
timer.asmNOW_MS
mem.asmMEMCPY, MEMSET, MEMZERO, MEMCMP
strings.asmSTRCPY, STRCMP, STREQUAL, STRCAT, STRSLICE, STRFIND, STRCHR, STRLENZ
alloc.asmALLOC_ZERO, ALLOC_ARRAY, FREE_PTR, ARENA_INIT/ARENA_ALLOC/ARENA_FREE
util.asmMIN, MAX, CLAMP, ABS, ALIGN8, bit helpers, RNG_SEED/RNG_NEXT
collections.asmVEC_* and MAP_* helpers over an arena

Strings are explicit (addr, length) byte buffers. STRLENZ measures a zero-terminated buffer; the other string macros take explicit lengths.

8. Devices and host capabilities#

System and Console ports are provided by every host. Programs that need graphics or input should read SYS_CAPS first.

PortConstantAccessMeaning
0x00SYS_VERSIONreadROM format version (2)
0x01SYS_DEBUGread/writetick-prefix flag
0x02SYS_HALTwritehalt with VM_HALTED
0x03SYS_CAPSreadcapability bitmask
0x10CONSOLE_PUTCwritelow byte to stdout
0x11CONSOLE_GETCreadone byte from stdin (0 on EOF)
0x12CONSOLE_PUTIwritesigned decimal + newline
0x13CONSOLE_PUTFwritedouble bits + newline
0x14CONSOLE_PUTS_ADDRwritestring address
0x15CONSOLE_PUTS_LENwritestring length
0x16CONSOLE_PUTSwritestring + newline (value ignored)
0x17CONSOLE_GETS_ADDRwriteinput buffer address
0x18CONSOLE_GETS_MAXwritemaximum input length
0x19CONSOLE_GETSwriteread a line (value ignored)
0x1ACONSOLE_GETS_LENreadlength from last GETS
0x1BCONSOLE_GETIreadone integer from stdin

Capability bits from SYS_CAPS:

BitConstantDevice
0x01CAPS_CONSOLEConsole ports
0x02CAPS_SCREENScreen ports
0x04CAPS_CONTROLLERController ports
0x08CAPS_TIMERTimer port

Optional devices:

PortConstantAccessMeaning
0x20SCREEN_WIDTHreadframebuffer width
0x21SCREEN_HEIGHTreadframebuffer height
0x22SCREEN_COLORwriteRGB colour in the low 24 bits
0x23SCREEN_PIXELwritex in the high 16 bits, y in the low 16
0x24SCREEN_DRAWwritepresent the framebuffer (value ignored)
0x25SCREEN_CLEARwritefill with the current colour (value ignored)
0x30CONTROLLER_KEYreadnext key-down, 0 if none (consumes)
0x31CONTROLLER_QUITread1 after a close request
0x40TIMER_MSreadmilliseconds since host start

Reads are synchronous, but only CONSOLE_GETC, CONSOLE_GETI, and CONSOLE_GETS block waiting for input. There is no ready/status port. CONSOLE_GETS strips a trailing newline and records its length in CONSOLE_GETS_LEN.

9. 0xasm command line#

./build/0xasm -f program.asm -o program.rom
./build/0xasm -f program.asm -I extra/includes -o program.rom
./build/0xasm -h

-f is required; there are no positional source arguments, and an input that is already a ROM image is rejected. With no -o, the output path replaces a trailing .asm with .rom or appends .rom.

FlagMeaning
-f FILEinput source file (required)
-o FILEoutput ROM path (default: change .asm to .rom, or append .rom)
-I DIRadd an include search directory (repeatable)
-v, --versionprint version
-h, --helpprint help

Errors are reported as file:line: message, using the innermost file when the error occurs inside an include or macro expansion. Macro-expanded bytes use the invocation line and the display path <macro NAME>. Line and file metadata is source-level only: it is not encoded in the ROM. Tracing is a 0xvm host feature (0xvm -t), not an 0xasm flag.

10. Examples#

ExampleDemonstrates
examples/counter.asma minimal loop
examples/features.asmdata, procedures, floats, and Console I/O
examples/asm_ext/main.asmincludes, conditionals, and macros
examples/statistics.asmheap allocations and larger programs
examples/boot.asmhost-aware Console and Screen output
examples/paint.asmScreen, Controller, and timer devices
examples/snake.asmarena allocation, RNG, strings, and game loop
examples/typography.asmbitmap font and text editing

11. Common pitfalls#

  • STORE* expects the value first, address on top.
  • PICK 0 duplicates the new top after popping the index; it is not the same as

OVER.

  • Jump and call targets are absolute byte addresses, not line or instruction

numbers.

  • DEI/DEO ports are 0..255; use the constants from ports.asm.
  • Static data lives in the image region, not on the heap. Use ALLOC for

runtime buffers.

  • Floats are raw bits; ADD on a double bit pattern is integer arithmetic.
  • Screen, Controller, and timer ports may be absent. Check SYS_CAPS before

using them.

  • 0x41 sleep is a host extension, not a frozen ABI port. examples/boot.asm

uses it for the splash delay; the CLI host has no such device.

  • A label after the final item maps to VM_IMAGE_START + total, one past the

loaded payload; jump range checking only enforces 0..0xFFFF.

  • The image has a fixed maximum size; large embedded bitmaps can overflow it.
  • Macro recursion is rejected; use parameterised helpers and labels with %%

instead.

docs / Lua Subset

0xvm Lua Subset#

Language guide for the 0xluac compiler.

0xluac (version 0.1) compiles a deliberately small Lua-like language to 0xasm source. It does not emit a ROM directly: the generated assembly is passed through 0xasm, which supplies labels, line data, and the VMIM ROM wrapper. This keeps the generated program inspectable in 0xdb.

For the compiler's development history, see Compiler Design. For the assembly output language, see Assembly Language. For the target machine, see the Machine Contract.

1. Build pipeline#

python3 -m luac compile program.lua -o build/program.asm -m build/program.lumap
./build/0xasm -f build/program.asm -o build/program.rom
./build/0xvm -f build/program.rom

The optional -m/--map file is a Lua source-line sidecar for 0xdb.

2. Command line#

python3 -m luac compile SOURCE -o OUTPUT [-m MAP]
0xluac compile SOURCE -o OUTPUT [-m MAP]

0xluac is the installed form of the same command; the name avoids a collision with the Lua luac compiler. The package requires Python 3.10 or newer.

FlagMeaning
SOURCEinput .lua file
-o OUTPUT, --output OUTPUTrequired generated 0xasm path
-m MAP, --map MAPwrite a Lua source-line map

Install the command with:

pip3 install -e .
# or
make luac-install

Compile errors are printed with a 0xluac: prefix. Lexer, parser, and import errors include line N and, for modules, the file name; most semantic codegen errors are plain messages.

3. Lexical rules#

Comments#

-- A line comment runs to the end of the line.
local x = 1 -- trailing comment

Identifiers and keywords#

Identifiers start with a letter or _ and continue with letters, digits, or _. Reserved words are:

local print if then elseif else end while do for
function return break continue const import

There are no boolean literals. Comparisons produce the integers 1 and 0.

Literals#

local dec = 42
local hex = 0xFFC040
local text = "hello\n"
local quoted = 'single quotes work too'

Integer literals are decimal or 0x hexadecimal. String literals support \n, \r, \t, \\, \", \', and \xNN escapes. Floating-point literals are not part of the subset.

4. Values and storage#

Integers#

All numeric values are signed 64-bit cells. Arithmetic follows the VM's two's-complement wrapping rules. Comparison results are 0 or 1.

Static data#

const declarations with bytes, words, or quads create global data labels in the generated assembly. They are initialized at compile time and remain writable VM memory at runtime.

const WIDTH = 320
const BASE = 0x100
const row = bytes { 0x80, 0x40, 0x20 }
const offsets = words { BASE, BASE + 2, -1 }
const glyphs = quads { 0x0102030405060708, -1 }

print(row[0])
print(offsets[1])
print(glyphs[0] >> 56)
ConstructorElement widthGenerated directive
bytes { ... }1 byteDB
words { ... }4 bytesDW
quads { ... }8 bytesDQ

Indexing uses element units: words[1] is the second 4-byte word, not byte offset 1.

Static zeroed arrays can also be created with byte_array(n) and word_array(n). The count must be a positive literal.

local bytes = byte_array(4)
bytes[0] = 65
local words = word_array(3)
words[2] = -2

Strings#

A string value is an (address, length) pair. A string local occupies two VM cells: the address of its bytes and its length.

local title = "0XVM TYPE"
print(title)               -- string + newline
print(strlen(title))       -- 9
print(title[0])            -- 48, the byte at index 0

String literals are interned into static data. Indexing a string is read-only. String equality with ==, concatenation, string function parameters, string returns, and general table values are not supported; use strcmp for equality.

Heap pointers#

alloc_bytes(n) and alloc_words(n) allocate runtime buffers and return pointers. Indexing is typed by the allocation; pointer arithmetic uses byte offsets.

local text = alloc_bytes(4)
text[0] = 65
local tail = text + 2
tail[0] = 66
print(text[2])             -- 66
free(text)

alloc_words(3) reserves three 4-byte elements. words + 8 points at the third word because 8 is a byte offset.

free requires a bare local with a tracked pointer descriptor (produced by an allocation or by pointer arithmetic on one). It does not check that the address is a live block start, so the VM may still return VM_ERR_BAD_ADDR.

5. Declarations#

Locals#

local x = 1
local w, h = screen_size()
x = x + 2

local name = expr declares a local. Multiple locals are only supported for local w, h = screen_size(). Locals have function-wide scope: declarations in nested blocks share the same function frame and are visible throughout that function. They are initialized when execution reaches the declaration.

Top-level locals are not global. Each function has its own frame and can see only constants, data labels, its parameters, and its own locals. Use const data tables for shared mutable state.

Constants#

const FRAME_MS = 66
const MASK = 0xFF
const COLOR = 0xFFC040

const name = expr evaluates a compile-time integer expression and emits an EQU in the generated assembly. Constant expressions use the same operators as normal expressions but may only reference constants and literals. All top-level scalar constants are folded before code emission, so runtime code may forward-reference them; constant initializers themselves are folded in source order.

const name = bytes/words/quads { ... } creates a static data label rather than a scalar constant. Unlike the name suggests, that label is writable VM memory.

Functions#

function add(a, b)
    return a + b
end

print(add(2, 3))

Functions are top-level only. They may call functions defined later in the file, call themselves recursively, and be used as expressions or statements. A function with no explicit return returns 0.

Imports#

import "modules/main"

Imports are resolved relative to the importing file. A different suffix is replaced with .lua; absolute paths are also accepted. Each file is expanded once; duplicate and circular imports are errors. Constants, data labels, functions, and top-level statements are spliced into one generated program at the import point. There are no namespaces or export/private distinction: all imported declarations share one symbol table, and duplicate symbols are errors.

6. Expressions#

Operators#

From lowest to highest precedence:

LevelOperatorsMeaning
comparison== ~= < <= > >=integer comparisons
bitwise OR``bitwise OR
bitwise XOR~bitwise XOR
bitwise AND&bitwise AND
shift<< >>left / right shift
additive+ -addition / subtraction
multiplicative* / %multiplication / division / remainder
unary- ~negation / bitwise complement
primaryexpr, name(args), value[index], (expr)grouping, calls, indexing

Parentheses may be used to override precedence. Boolean and, or, not, concatenation, exponentiation, varargs, and method calls are not supported. Arithmetic on a string is a compile error.

Data constructors#

bytes { ... }, words { ... }, and quads { ... } may appear where an expression is expected. Values must be compile-time integer expressions.

Indexing#

local byte = row[i]
row[i] = byte + 1

Indexing works on static arrays, heap pointers, and strings. Static array and string indices are in element units; heap pointer indices are in allocation element units. Only literal indices with a known size/offset are checked at compile time. Dynamic indices and runtime pointer offsets are unchecked and fall through to the VM's address checks.

7. Statements#

Assignment#

x = expr
row[0] = expr
pointer[i] = expr

Both simple and indexed assignment are supported.

Output#

print(42)          -- signed decimal + newline
print("hello")     -- string bytes + newline
print_str(text)    -- string bytes + newline

print selects the Console integer or string printer based on the expression.

Conditionals#

if x == 0 then
    print("zero")
elseif x < 0 then
    print("negative")
else
    print("positive")
end

elseif and else are optional. Conditions are integer expressions; 0 is false and any non-zero value is true.

Loops#

local i = 0
while i < 10 do
    i = i + 1
    if i == 3 then
        continue
    end
    if i == 8 then
        break
    end
end

for j = 1, 3 do
    print(j)
end

while runs until its condition is zero. for name = start, limit do counts from start to limit inclusive with an implicit step of 1; limit is evaluated once. break and continue are valid only inside loops.

Calls#

add(1, 2)          -- statement call; result discarded
local sum = add(1, 2)

Calls to unknown functions, or calls with the wrong argument count, are compile errors.

Return#

return expr is valid only inside a function. A function returns exactly one integer cell; string returns are compile errors. A bare return, or a function with no explicit return, returns 0.

8. Function ABI and scope#

Generated functions compile to CALL/RET frames:

  • Arguments are copied into zeroed locals at function entry.
  • All locals collected anywhere in the function body share one ENTER frame.
  • The result is the value left on the stack for RET.
  • Functions always leave one result cell, defaulting to 0.
  • Nested functions and closures are not supported.

Function names are global within the merged program. Imported functions and top-level functions share the same namespace.

9. String bindings#

BindingArgumentsResult / effect
print_str(s)stringwrite string + newline
strlen(s)stringbyte length
strcmp(a, b)string, stringsigned byte difference: 0 if equal, sign gives the order
slice(s, start, count)string, integer, integerclamped substring view (addr, len)
strcpy(dest, s)pointer, stringcopy bytes into dest; no capacity check
strfind(s, needle)string, stringfirst index or -1
strchr(s, byte)string, integerfirst index of byte or -1

slice requires compile-time, non-negative start and count values. It clamps the requested range to the string and returns a view into the original bytes; a start beyond the end yields an empty string. Use strcpy into a heap buffer when a copy is needed. strchr searches for a byte value, not a one-character string.

local part = slice("0XVM TYPE", 5, 4)
print(part)
print(strlen(part))

String bindings automatically include stdlib/strings.asm in the generated assembly. String function parameters and string returns are not supported, so pass labels or indices when sharing text across functions.

10. Device intrinsics#

IntrinsicArgumentsResult / effectStdlib include
screen_size()0width, height (multi-local only)screen.asm
set_color(rgb)1set current colourscreen.asm
plot(x, y)2write one pixelscreen.asm
draw()0present the framescreen.asm
clear()0fill with current colourscreen.asm
read_key()0next Controller code, 0 if nonecontroller.asm
quit_requested()01 after close requestcontroller.asm
now_ms()0milliseconds since host starttimer.asm
sleep(ms)1host sleep / wait requestdirect DEO 0x41

sleep is a host extension outside the frozen VM ABI. SDL3 clamps the wait to 0..1000 ms, the WASM host yields to the next animation frame, and the CLI host provides no sleep device.

local w, h = screen_size()
set_color(0xB9E5AD)
plot(10, 10)
draw()

local key = read_key()
if quit_requested() == 1 then
    print("bye")
elseif key == 7 then
    print("escape")
end

Boolean or is not supported; use nested if or elseif instead.

Screen, Controller, and timer devices depend on host capabilities. A CLI host provides Console only. Generated programs that call these intrinsics will run in CLI hosts only if the device branch is kept dormant, as in tests/lua/devices.lua.

11. Generated assembly conventions#

0xluac emits ordinary assembly with:

  • INCLUDE "console.asm" always.
  • INCLUDE "screen.asm", controller.asm, timer.asm, or strings.asm when

the corresponding intrinsics or bindings are used.

  • EQU lines for scalar constants.
  • Static DB/DW/DQ labels for data tables and interned strings.
  • One ENTER n frame for the top-level program and one per function.
  • A final HALT after top-level statements.
  • Function labels emitted after main, allowing forward calls.
  • Data labels emitted after code and functions, so the assembler's entry JMP

skips them.

The output is intended to be readable and debuggable, not minified. The other stdlib/ modules are available to assembly authors, but only the built-ins in this guide are callable from Lua source.

12. Source maps and debugging#

python3 -m luac compile examples/typography.lua \
  -o build/lua-typography.asm -m build/lua-typography.lumap
./build/0xasm -f build/lua-typography.asm -o build/lua-typography.rom
./build/0xdb -f build/lua-typography.rom \
  -s build/lua-typography.asm -m build/lua-typography.lumap

The map is a tab-separated sidecar beginning with # luac source map v1. Each entry maps a generated assembly line to a Lua file and line. For a ROM, 0xdb also needs -s with the generated assembly source for address-to-assembler-line data; the Lua map then overlays Lua file and line information. Stepping, listing, and line breakpoints can use Lua source lines.

13. Limitations#

  • No general tables, metatables, or userdata.
  • No floating-point literals or arithmetic.
  • No boolean operators or boolean literals.
  • No string function parameters or string returns.
  • No nested functions or closures.
  • No generic for, repeat, goto, or multiple assignment except

screen_size().

  • No runtime bounds checking on arrays or pointers.
  • slice offsets must be compile-time non-negative integers.
  • Device intrinsics require a host that provides the corresponding device.

These limits are deliberate: the subset targets a small stack VM with fixed memory and a transparent assembly output.

14. Examples and tests#

FileDemonstrates
examples/typography.luafull graphical text editor with data tables and intrinsics
examples/raycaster.luafirst-person maze explorer with DDA raycasting
tests/lua/smoke.luabasic statements, loops, and output
tests/lua/functions.luaforward calls, recursion, statement calls, locals
tests/lua/control.luaif/elseif, while, for, break, continue
tests/lua/arrays.luabyte/word storage and dynamic indices
tests/lua/heap.luaallocation, typed pointer offsets, free
tests/lua/data.luaconstants, bytes/words/quads, big-endian layout
tests/lua/bitops.luahex literals, shifts, AND/OR/XOR, unary NOT
tests/lua/strings.luastring values, indexing, slicing, string bindings
tests/lua/devices.luadevice intrinsics with a dormant CLI branch
tests/lua/modules.luaimports and one-time module expansion

Run the golden checks with:

make lua-check
docs / VM Implementation

VM Implementation#

This document describes the virtual machine in this repository: its state model, instruction encoding, execution rules, assembler, ROM format, and test setup. The Machine Contract is the frozen ABI; this document explains how the current code implements it.

1. Overview#

The project implements a small, single-threaded stack VM in the spirit of Uxn. It is a standalone VM: assembly source is turned into a byte payload, wrapped in a VMIM ROM, loaded into RAM, and executed locally from start to halt. The CLI can also load a previously built ROM directly.

The layers are:

  1. Core VM (include/vm.h, src/vm.c) — fixed state, byte decoder,

interpreter, RAM allocator metadata, and two device-port instructions.

  1. Assembler (include/asm.h, src/asm.c) — source text to byte payload

and ROM, with a per-byte source-line map.

  1. Libraries (build/lib0xvm.a, build/lib0xvm.so) — the VM, assembler,

and decoder built as one static and one shared library.

  1. Tools (apps/asm, apps/dis, apps/rom, apps/db) — 0xasm, 0xdis,

0xrom, and 0xdb, built from the same core and decoder.

  1. Hosts (hosts/cli, hosts/sdl3, hosts/wasm) — 0xvm, 0xvm-sdl,

and the browser host, with host-backed System/Console devices and optional Screen, Controller, and timer ports.

  1. Tests — VM, assembler, ROM, device, conformance ROM, and disassembler

checks under tests/.

Cells and arithmetic are 64-bit; addresses and ip are 16-bit byte addresses. The VM has a fixed 64 KiB RAM, and no buffer in the core grows at runtime. The core contains no stdio calls: all I/O passes through host device callbacks.

2. Source layout#

FileRole
include/vm.hPublic types, opcodes, statuses, constants, device API, and declarations
src/vm.cROM/image loading, decoder, interpreter, device dispatch, heap allocator
include/asm.h, src/asm.cTwo-pass assembler, byte encoding, macros, ROM writer
include/dis.h, src/dis.cInstruction decoder for disassembly output
hosts/cli/main.cCLI host: assemble/run sources and ROMs, trace, tick debug prefix
hosts/sdl3/main.cSDL3 host: window, framebuffer, keyboard, quit flag, timer
hosts/wasm/main.c, hosts/wasm/library.jsBrowser host: canvas, keyboard, timer, and Console bridge
hosts/wasm/index.html, hosts/wasm/app.jsBrowser host page and UI glue
apps/common/tools.cFile/ROM helpers shared by tools and hosts
apps/common/host.cShared System/Console devices and port-range dispatcher
apps/test/main.cTest executable entry point
tests/*.c, tests/tests.hVM, assembler, ROM, device, host, conformance, and disassembler suites
tests/conformance.asmExecutable v2 conformance ROM source
stdlib/*.asmOpt-in macro library (ports, arithmetic, locals, Console, Screen, Controller, timer)
examples/*.asmExample programs
MakefileBuilds all apps and provides make test

3. Machine state#

typedef struct {
    void *ctx;
    VmDeviceRead read;   /* VmStatus(void *, VmState *, uint8_t, int64_t *) */
    VmDeviceWrite write; /* VmStatus(void *, VmState *, uint8_t, int64_t) */
} VmDevice;

typedef struct {
    uint16_t ret_ip;   /* byte address to resume at after RET */
    uint16_t prev_fp;  /* caller's frame pointer */
} VmFrame;

typedef struct {
    uint16_t addr;
    uint16_t size;     /* allocated size, rounded up to 8 */
    uint8_t  live;     /* 1 = in use, 0 = on the free list */
} VmBlock;

typedef struct {
    uint16_t ip;       /* byte address of the next instruction in mem */
    uint16_t sp;       /* live cells on the operand stack */
    uint16_t fp;       /* index of the current frame's first local */
    uint16_t fsp;      /* live call frames */
    uint16_t hp;       /* allocator bump pointer; starts at 0x4000 */
    uint64_t ticks;    /* successfully executed instructions */

    int64_t  stack[256];
    uint8_t  mem[65536];
    VmFrame  frames[64];
    VmBlock  blocks[64];
    uint16_t block_count;
    VmDevice dev;      /* host device callbacks; preserved across resets */
} VmState;

ip is a byte address into mem, not an instruction number. sp counts live stack cells; fp is the index of the current frame's first local; fsp counts live frames; hp is the allocator bump pointer. ticks counts successful steps, including HALT and device-driven halts. All VM state is contained in the struct: no field owns heap memory. The device's opaque ctx belongs to the host and is not interpreted by the core.

vm_init() zeroes the state, then sets hp = VM_HEAP_START (0x4000) and clears device callbacks. A host installs callbacks with vm_set_device() before running. vm_free() resets the machine to the same post-init state but keeps the installed callbacks; image loading preserves them as well.

Memory map#

0x0000 ─────────────── zero page (addressable RAM)
0x0100 ─────────────── image origin (VM_IMAGE_START)
0x3FFF ─────────────── end of image region
0x4000 ─────────────── heap start (initial hp)
0xFFFF ─────────────── end of 64 KiB RAM

device page: 256 ports, outside RAM, addressed only by DEI/DEO

The image payload is limited to VM_IMAGE_MAX (0x3F00) bytes. Loads and stores may access any byte of mem; the full access width must fit below 0x10000. ALLOC/FREE are the only operations constrained to the heap region. Multi-byte RAM values use big-endian byte order. Device ports are not RAM addresses and cannot be reached by load/store instructions.

4. Instruction encoding#

Every instruction starts with one opcode byte. Opcodes are assigned explicitly because retired I/O opcode values remain reserved:

  • 0x00..0x40 contains the current core opcodes, with 0x0E unassigned.
  • 0x41..0x45 are unassigned (retired v1 I/O opcodes).
  • 0x46..0x7F are reserved.
  • 0x80 is DEI (device input), 0x81 is DEO (device output).
  • 0x82..0xFF are reserved.
ImmediateOpcodesTotal bytesEncoding
noneall others1—
1 byteENTER (0x2E), LOCAL_GET (0x2F), LOCAL_SET (0x30), DEI (0x80), DEO (0x81)2unsigned index/port 0..255
2 bytesJMP (0x09), JMP_Z (0x0A), CALL (0x2B)3big-endian absolute byte address
8 bytesPUSH (0x02), PUSHF (0x32)9big-endian int64 / raw double bits

vm_inst_size() returns the encoded byte count for an opcode. CALL_I and JMP_I are single-byte opcodes that read their byte target from the stack.

Fetching decodes mem[ip], checks that the whole instruction fits in RAM, advances ip by 1 + immediate width, and reads the immediate from mem. Direct jump/call targets are absolute RAM byte addresses, not instruction indices. vm_opcode_name() returns RESERVED for unassigned values.

5. Instruction semantics#

Notation: stack contents are bottom-to-top, so the rightmost value is the top. For binary ops, b is popped first and a is the value below it.

Core and control flow#

OpcodeEffectDescription
HALT[...] → [...]Stop with VM_HALTED; ip stays on the opcode
NOP[...] → [...]Advance ip and ticks
PUSH x[...] → [..., x]Push a big-endian int64 immediate
POP[..., x] → [...]Discard the top
DUP[..., x] → [..., x, x]Duplicate the top
ADD/SUB/MUL[..., a, b] → [..., a op b]Wrapping 64-bit arithmetic
CMP_LT[..., a, b] → [..., 0\|1]Signed less-than
JMP target[...] → [...]Set ip to an absolute byte address
JMP_Z target[..., c] → [...]Pop c; jump if zero
JMP_I[..., target] → [...]Pop target and jump

Arithmetic uses unsigned operations and casts back to int64_t, avoiding undefined behavior on signed overflow. Comparisons and logical ops push 1 or 0, so they feed JMP_Z directly.

Arithmetic, comparisons, bitwise and logical#

OpcodeEffectDescription
DIV[..., a, b] → [..., a/b]Truncated toward zero; INT64_MIN / -1 wraps
MOD[..., a, b] → [..., a%b]Sign of a; INT64_MIN % -1 is 0
CMP_EQ/CMP_NE[..., a, b] → [..., 0\|1]Equality / inequality
CMP_LE/CMP_GT/CMP_GE[..., a, b] → [..., 0\|1]Signed comparisons
AND/OR/XOR[..., a, b] → [..., a op b]64-bit bitwise ops
NOT[..., a] → [..., ~a]Bitwise complement
SHL/SHR[..., a, b] → [..., a shift b]Count masked to 0..63; SHR is logical
LNOT[..., a] → [..., !a]Logical NOT of booleanized operand
LAND/LOR[..., a, b] → [..., a && b \| a \|\| b]Logical AND/OR

Zero divisors return VM_ERR_DIV_ZERO without changing the stack.

Stack shuffling#

OpcodeEffectDescription
SWAP[..., a, b] → [..., b, a]Exchange the top two
OVER[..., a, b] → [..., a, b, a]Copy the second item to the top
ROT[..., a, b, c] → [..., b, c, a]Rotate the top three
PICK[..., x, n] → [..., x_n]Pop n, copy stack[sp-2-n]; n=0 duplicates the new top

RAM access and allocation#

OpcodeEffectDescription
LOAD8/LOAD16[..., addr] → [..., value]Unsigned byte / 16-bit read
LOAD32[..., addr] → [..., value]Signed 32-bit read, sign-extended
LOAD32U[..., addr] → [..., value]Unsigned 32-bit read, zero-extended
LOAD64[..., addr] → [..., bits]Raw 64-bit read
STORE8/STORE16/STORE32/STORE64[..., val, addr] → [...]Write 1/2/4/8 bytes; address on top
ALLOC[..., size] → [..., addr]Allocate a heap block, reusing free blocks
FREE[..., addr] → [...]Mark a live block dead for reuse

ALLOC requires a positive size, rounds it up to a multiple of 8, and checks that the rounded size fits from hp to the end of RAM. First-fit reuse splits a larger dead block into a live prefix and a dead suffix; otherwise hp is bumped. FREE requires a live block's start address. The operand is replaced in place by the returned RAM address.

Procedures and locals#

OpcodeOperandEffectDescription
CALLtarget[...] → [...]Push {return byte address, fp}, set fp = sp, jump
CALL_I—[..., target] → [...]Pop target, then call
RET—[..., result] → [..., result]Unwind one frame, leave result for caller
ENTERn[...] → [..., 0 × n]Reserve n zeroed locals at [fp, fp+n)
LOCAL_GETindex[...] → [..., local]Push stack[fp + index]
LOCAL_SETindex[..., v] → [...]Pop v into stack[fp + index]
JMP_I—[..., target] → [...]Pop target and jump

CALL saves the byte address after the call instruction. Locals live on the same operand stack below new pushes, so frames and locals share the 256-cell stack while frame metadata uses the fixed 64-entry array. LOCAL_GET/LOCAL_SET validate the index against the current frame's local region; the usual order is ENTER n; PUSH v; SET i. RET requires a result on the stack, restores fp and ip from the top frame, and leaves the result at the caller's top.

Floats#

OpcodeEffectDescription
PUSHF[...] → [..., bits]Push a raw 64-bit double literal
FADD/FSUB/FMUL/FDIV[..., a, b] → [..., bits]Double-precision arithmetic
FNEG/FABS/FSQRT[..., a] → [..., bits]Unary double operations
FCMP_LT/FCMP_EQ/FCMP_LE/FCMP_GT/FCMP_GE[..., a, b] → [..., 0\|1]Double comparisons
FTOI[..., bits] → [..., int]Truncating conversion; NaN/overflow saturate
ITOF[..., int] → [..., bits]int64_t to double

Floats are raw IEEE-754 bit patterns in ordinary int64_t cells; the VM does not track types. vm_bits_to_f64() and vm_f64_to_bits() use memcpy to avoid strict-aliasing undefined behavior. Printing a double is host policy, supplied by the Console device and the optional FPRINT stdlib macro.

Device layer#

OpcodeEffectDescription
DEI port[...] → [..., value]Check stack room, read a cell from the host, push it
DEO port[..., value] → [...]Call the host with the top cell, then pop it

The core has no I/O opcodes and no stdio calls. It only validates the operand stack, invokes vm->dev.read or vm->dev.write, and interprets the returned status. A callback returns VM_OK, VM_HALTED, or VM_ERR_IO; any other status is treated as VM_ERR_IO. A device halt keeps ip on the port instruction: DEO consumes its cell, while DEI does not push a result. ticks increments for a successful device halt.

The CLI installs these ports:

PortNameAccessMeaning
0x00VM_SYS_VERSIONreadROM format version (2)
0x01VM_SYS_DEBUGread/writetick-prefix flag
0x02VM_SYS_HALTwritehalt with VM_HALTED
0x03VM_SYS_CAPSreadcapability bitmask (0x01 console, 0x02 screen, 0x04 controller, 0x08 timer)
0x10VM_CONSOLE_PUTCwritelow byte to stdout
0x11VM_CONSOLE_GETCreadone byte from stdin (0 on EOF)
0x12VM_CONSOLE_PUTIwritesigned decimal + newline
0x13VM_CONSOLE_PUTFwritedouble bits + newline
0x14VM_CONSOLE_PUTS_ADDRwriteRAM address of the string to write
0x15VM_CONSOLE_PUTS_LENwritelength of the string to write
0x16VM_CONSOLE_PUTSwritestring + newline (value ignored)
0x17VM_CONSOLE_GETS_ADDRwriteRAM address for input
0x18VM_CONSOLE_GETS_MAXwritemaximum input length
0x19VM_CONSOLE_GETSwriteread a line into RAM (value ignored)
0x1AVM_CONSOLE_GETS_LENreadlength from the last GETS
0x1BVM_CONSOLE_GETIreadone integer from stdin

PUTS and GETS validate the configured RAM range before touching mem. GETS strips a trailing newline and records its length for GETS_LEN. Read ports are synchronous and blocking; there is no ready/status port. GETC reports EOF as 0, GETI maps EOF/bad input/overflow to 0, and GETS maps EOF to an empty line; stream errors return VM_ERR_IO. -D sets VM_SYS_DEBUG; the Console callback then prefixes formatted output with [vm tick=N]. Another host can install different callbacks without changing the core or the ROM.

The following source-level mnemonics are not opcodes. They are opt-in macros in stdlib/console.asm (which includes stdlib/ports.asm for the constants):

MacroExpansion
PRINT_CHARDEO 0x10
PRINTDEO 0x12
FPRINTDEO 0x13
READ_INTDEI 0x1B
PRINT_STRDEO 0x15, DEO 0x14, PUSH 0, DEO 0x16
READ_STRDEO 0x18, DEO 0x17, PUSH 0, DEO 0x19, DEI 0x1A

6. Execution model#

vm_step(vm) executes exactly one instruction:

  • Fetch and decode from vm->ip; a truncated immediate or out-of-RAM address is

VM_ERR_BAD_IP, and an unassigned opcode is VM_ERR_BAD_OP.

  • Normally ip becomes the address after the instruction.
  • JMP/JMP_Z, JMP_I, CALL/CALL_I, and RET assign a new ip.
  • HALT or a callback returning VM_HALTED stops execution and leaves ip on

the current instruction.

ticks increments only after a successful step. vm_run(vm, max_steps) repeats vm_step until a non-VM_OK status or the step budget is exhausted; max_steps == 0 means unlimited, and exhaustion returns VM_OK so the caller can resume later.

Atomic error handling#

Every instruction validates its preconditions before mutating state. For example, binary ops check stack depth first; DIV/MOD check the divisor before popping; JMP_Z and JMP_I validate targets before consuming the condition or target; ALLOC checks size, rounding, stack room, heap room, and metadata room before changing hp, sp, or the block list; loads/stores validate stack depth and address range before touching RAM; LOCAL_SET checks the slot before writing; and RET checks the frame and result before unwinding. DEI checks stack room and a callback exists before invoking the host; DEO checks stack depth before reading the value. A failed step leaves ip, sp, fp, fsp, hp, ticks, RAM, stack, frames, and block metadata exactly as they were.

A device callback is host code. If it returns VM_ERR_IO, the core has made no state change; callbacks must avoid mutating VM state unless they can complete successfully. Side effects outside VmState (stdout, stdin, files, host buffers) belong to the host and are not rolled back.

Status codes: VM_OK, VM_HALTED, VM_ERR_BAD_IP, VM_ERR_BAD_OP, VM_ERR_STACK_OVERFLOW, VM_ERR_STACK_UNDERFLOW, VM_ERR_HEAP_OVERFLOW, VM_ERR_BAD_ADDR, VM_ERR_DIV_ZERO, VM_ERR_IO, VM_ERR_BAD_FRAME, and VM_ERR_BAD_LOCAL. Use vm_status_str() and vm_opcode_name() for printable names.

7. Assembler#

src/asm.c is a line-oriented, two-pass assembler.

  • One instruction per line; mnemonics are case-insensitive.
  • Comments begin with ;, #, or // and are ignored inside quoted strings.
  • Labels are name: (letters/digits/underscore, starting with a letter or _)

and may share a line with an instruction or data directive.

  • JMP, JMP_Z, and CALL accept a label or an integer expression.
  • Operand kinds are none, integer expression, float literal, jump target,

local index, and device port; missing/illegal operands are reported with line numbers. DEI/DEO ports must be expressions in 0..255.

Expressions and constants#

PUSH, ENTER, LOCAL_GET/SET, CALL, jump targets, DEI/DEO ports, and numeric data values accept integer expressions: decimal or 0x hex literals, unary + - ~, binary + - * / % << >> & ^ | == != < <= > >= (C-like precedence), parentheses, and previously defined constants. EQU name expr defines a constant. Arithmetic wraps in uint64_t; division by zero is an error; shifts of 64 or more yield zero; and -9223372036854775808 is accepted as INT64_MIN.

Includes, conditionals, and macros#

These directives are expanded entirely in the assembler; they emit no VM opcode and require no changes to the ROM header, RAM map, or device ports.

  • INCLUDE "path" inserts another source file. Relative paths resolve against

the including file's directory; absolute paths are used as-is. Includes may nest up to 32 levels, and cycles are rejected. Diagnostics inside included files use file:line: prefixes.

  • IF expr / IFDEF name / IFNDEF name, with optional ELIF expr and

ELSE, are closed by ENDIF. IF/ELIF expressions use the same constant-only expression grammar as operands; IFDEF/IFNDEF test whether a constant or macro name is defined. Inactive branches are skipped but still parsed for balanced directives, so they cannot define constants, labels, or macros.

  • MACRO name p1, p2, ... ... ENDMACRO (or ENDM) defines a reusable body.

Parameters are referenced as %1, %2, ... or %p1, %p2, ...; %% expands to a unique prefix, which makes macro-local labels safe to repeat: %%done: and JMP %%done. Macro names are case-insensitive and may not shadow instructions or directives. Invocation is name arg1, arg2, ... with exactly the declared number of arguments; commas inside quotes or parentheses stay within one argument. Nesting is limited to 32 levels, and recursion is rejected by that limit. Zero-parameter macros are allowed; the stdlib uses them for INC, PRINT_CHAR, and friends. Macro names may not shadow instructions or directives, but may replace stdlib macros.

AsmProgram.lines records the line of the original call site for instructions and data emitted from a macro, and the real line inside an included file for included source. Errors report the innermost source path when one is available.

Image layout and data directives#

The first pass records instructions, data directives, and labels. The second pass computes every label's absolute RAM address and emits bytes with this layout:

VM_IMAGE_START + 0:  JMP <code_start>       (3-byte entry stub)
VM_IMAGE_START + 3:  static data from DB/DW/DQ/STR/ALIGN
VM_IMAGE_START + n:  encoded instructions

DB (bytes), DW (big-endian 16-bit), DQ (big-endian 64-bit), STR (quoted string with \n, \r, \t, \0, \\, \", \xNN escapes), and ALIGN n (1..4096) append bytes to the static-data area. ALIGN pads relative to the data area's own offset. Labels on data directives resolve to their absolute RAM addresses, so programs use LOAD*/STORE* to access them; the image is not copied into the heap. The total payload must fit in VM_IMAGE_MAX.

Stdlib macros, aliases, and line map#

The assembler has no built-in pseudo-ops or source aliases. stdlib/arith.asm defines INC, DEC, and NEG as multi-instruction macros; stdlib/locals.asm defines GET and SET as aliases for LOCAL_GET and LOCAL_SET; stdlib/console.asm defines the device-port sequences in section

  1. stdlib/all.asm includes all three. Each file is guarded with IFNDEF, so

including it more than once is harmless. A program opts in with INCLUDE "all.asm" (or an individual file) and may override any stdlib name with its own MACRO definition. INCLUDE searches the including file's directory, then the -I directories passed to 0xasm, then the built-in stdlib directory compiled into the assembler.

AsmProgram.lines maps every payload byte to its source line (0 for generated bytes); asm_line_of(prog, addr) takes an absolute RAM byte address, which is what the CLI's -t trace prints. Macro-generated bytes report the invocation line.

asm_parse_string() and asm_parse_file() return 0 on success or -1 on failure with a line-numbered message in prog.error and prog.error_line (unknown mnemonics, invalid operands or ports, duplicate/undefined labels, duplicate constants, bad escapes, out-of-range jumps/targets, oversized images, and file I/O errors). asm_program_free() releases the emitted payload buffers while preserving the diagnostic fields. The assembler may grow its source-side scratch buffers, but the emitted payload and the VM itself are fixed.

8. ROM format and loading#

asm_make_rom() encodes a 16-byte header plus payload; asm_write_rom() writes those bytes to a file. The header is:

OffsetSizeField
04Magic 56 4D 49 4D ("VMIM")
41Format version, currently 2
51Flags, must be 0
62Reserved, must be 0
82Payload length, big-endian, 0..0x3F00
102Entry point, big-endian, normally 0x0100
124Reserved, must be 0

vm_load_rom() checks the header, requires the buffer length to be exactly header plus payload, then calls vm_load_image(). That zeroes all RAM and metadata, copies the payload to 0x0100, sets hp = 0x4000 and ip to the entry point, and leaves ticks = 0. The entry must lie inside the loaded payload. Malformed images return VM_ERR_BAD_IP without changing the state.

The tools support both paths:

./build/0xvm -f examples/counter.asm     # assemble, wrap, load, run
./build/0xasm -f examples/counter.asm    # write counter.rom
./build/0xvm -f counter.rom              # load and run the ROM
./build/0xdis -f counter.rom             # decode the ROM payload
./build/0xrom -f counter.rom             # inspect and validate the header

dis starts at the entry point, follows the entry JMP past static data, and decodes linearly to the end of the payload. Reserved opcode bytes are printed as RESERVED (0xNN) instead of being treated as errors; immediates that cross the payload end are reported as decode errors.

9. Building and testing#

make all                 # build lib0xvm, the 0x* tools, and 0xtest
make test                # build and run build/0xtest
make shared              # build only the shared library
make type=RELEASE test   # release build (no sanitizers)

The Makefile discovers every tests/*.c, compiles it, and links the objects into build/0xtest with build/lib0xvm.a. DEBUG builds enable AddressSanitizer and UndefinedBehaviorSanitizer.

  • The VM suite covers stack ops and shuffling, arithmetic/wraparound,

division edges, comparisons/bitwise/logical ops, both jump paths and indirect jumps, all RAM widths and bounds, allocation/free-list reuse, calls/locals, floats, and error atomicity.

  • The device suite covers fake host reads and writes, argument passing,

device errors and atomicity, device halts, retired opcode values, and opcode names.

  • The assembler suite covers parsing, comments, labels, expressions and

constants, every mnemonic, opt-in stdlib macros, data directives and image layout, byte-address line mapping, file loading, running parsed programs, and parse errors.

  • The ROM suite checks header encoding, load validation, and writing a v2

ROM that can be reloaded and run.

  • The conformance suite assembles tests/conformance.asm and runs it from

both an in-memory ROM and a generated build/conformance-v2.rom. It checks the exact transcript in tests/conformance.expected, final stack state, and device-halt status. make conformance-check runs the same artifact through 0xvm with input B-7\nhey\n and diffs the CLI output.

  • The negative conformance cases build raw images for reserved/retired

opcodes, stack overflow/underflow, division by zero, out-of-range loads and jump targets, bad frames/locals, heap overflow, and device errors. Each case requires the expected status and atomic state on the failing step; a truncated immediate is placed at the RAM boundary to test decode bounds.

  • The disassembler suite checks every immediate shape, reserved bytes, RAM

and payload truncation, and linear decoding of a loaded image.

For example:

./build/0xvm -f examples/counter.asm

prints the loop's 0..5 and the final 60 before halting. gcd.asm prints 21; features.asm demonstrates data labels, constants, locals, floats, and Console I/O together; statistics.asm reads a count and values from stdin and prints descriptive statistics.

10. Current limitations#

  • Floats use raw bit patterns with no runtime type tag: mixing integer and float

ops on the same value is the program's responsibility.

  • 0xvm supplies System and Console; 0xvm-sdl and the browser host additionally

supply Screen, Controller, and timer. Other hosts may assign other ports.

  • There is no interrupt or event-vector mechanism; those ports remain reserved.
  • The image region has no relocation or protection model beyond the loader's

payload-length check.

  • INCLUDE resolves through the local filesystem; ROMs are self-contained and

do not carry included source.

docs / Compiler Design

0xluac compiler design#

0xluac compiles a deliberately small Lua subset to 0xasm text. Emitting assembly rather than a raw VMIM ROM keeps labels, source paths, and line mapping in the assembler, so 0xdb can inspect generated programs without a new ROM metadata format.

This document tracks the work that made a typography-level graphical demo possible in the subset. Each numbered item was implemented, tested, and committed on its own before the next one started.

Current subset#

  • Integer literals and signed 64-bit arithmetic: +, -, *, /, %, unary -.
  • Comparisons: ==, ~=, <, <=, >, >=.
  • Locals and assignment: local x = expr, local w, h = screen_size(),

x = expr.

  • Control flow: if/elseif/else, while, numeric for with an implicit

step of 1, plus break and continue inside loops.

  • Functions with parameters, locals, return, forward calls, and recursion.
  • Static byte/word arrays with literal or dynamic indices.
  • Typed heap allocations, raw pointer offsets, and explicit free.
  • Bitwise &, |, ~ (XOR), unary ~ (NOT), <<, >>, and hex literals.
  • Top-level const values and initialized byte/word/quad data tables.
  • Device intrinsics: screen_size, set_color, plot, draw, clear,

read_key, quit_requested, now_ms, and sleep.

  • String locals hold (address, length) pairs; literals, string variables,

slice, byte indexing, and the strlen, print_str, strcmp, strfind, strchr, and strcpy bindings are supported.

  • Output: print(integer_expr) and print(string_expr).
  • Static string literals are emitted as (address, length) buffers.
  • Top-level import "name" loads name.lua relative to the importing file and

merges constants, data, functions, and top-level statements into one program.

  • -m/--map writes a Lua source-line sidecar; 0xdb -m overlays it on the

assembler's line data for stepping, listing, and line breakpoints.

Not supported yet: string function parameters/returns or table values.

Work items#

#ItemStatusNotes
1Functions with parameters, returns, and scopesDoneCALL/RET ABI, arguments via PICK, caller cleanup, recursion.
2Arrays/byte buffers and indexingDonea[i], LOAD8/STORE8, LOAD32/STORE32.
3Heap allocation and pointersDonealloc_bytes/alloc_words, pointer offsets, FREE.
4Bitwise operators and hex literalsDone&, `, binary ~/unary ~, <<, >>, 0x...`.
5Static data declarationsDoneconst, bytes/words/quads tables, EQU/DB/DW/DQ.
6Device/runtime intrinsicsDoneScreen, controller, timer macros; DEO 0x41 sleep; SDL3/WASM smoke.
7Strings as values and string library bindingsDone(addr, len) locals, stdlib bindings, read-only indexing, clamped slicing.
8Modules/includesDoneimport, relative resolution, one-time expansion, merged symbols.
9Source-line mapping, break/continue, elseifDoneSidecar line map for 0xdb; loop jumps and chained conditions.

1. Functions with parameters, returns, and scopes#

Goal. Allow a program to define reusable functions and call them from expressions or as statements, with correct stack behavior.

Syntax sketch.

function add(a, b)
    return a + b
end

print(add(2, 3))   -- expression call
add(1, 2)          -- statement call; result discarded

Design.

  • Each function gets a label, its own local frame, and its own scope.
  • Arguments arrive on the stack at fp. ENTER n reserves argument and body

locals; PICK (n + argc - i) copies argument i into local slot i - 1.

  • RET requires exactly one result. A missing return emits PUSH 0; RET.
  • After an expression call, the caller removes the arguments with SWAP; POP

repeated argc times. After a statement call, it pops argc + 1 values.

  • Calls may be forward references, enabling recursion.

Acceptance.

  • Zero-argument, multi-argument, nested, and recursive calls work.
  • Function locals do not collide with top-level or other functions' locals.
  • Unknown functions, wrong arity, nested definitions, and return outside a

function are compile errors.

  • A golden program exercises calls as expressions and statements.

2. Arrays/byte buffers and indexing#

Goal. Represent the editor text buffer and bitmap font rows as indexable byte arrays.

Syntax sketch.

local text = byte_array(16)
text[0] = 65
print(text[0])

Design. Add Index and array-valued Local expressions, then emit LOAD8/STORE8 for byte arrays and LOAD32/STORE32 for word arrays. Bounds checks are compile-time only for static sizes; dynamic values remain unchecked unless a runtime helper is added later.

Acceptance. Read/write byte and word arrays; indexing works in expressions and assignments; out-of-range static indices are rejected.

3. Heap allocation and pointers#

Goal. Allocate the 1024-byte text buffer and derive offsets for helpers.

Syntax sketch.

local text = alloc_bytes(1024)
text[caret] = byte
local tail = text + 16
tail[0] = 10
free(text)

Design. alloc_bytes(n) emits ALLOC with n bytes; alloc_words(n) emits ALLOC with 4 * n bytes. Both return an ordinary 64-bit address that can be stored in a local, indexed with the same LOAD8/STORE8 and LOAD32/STORE32 paths as static arrays, and combined with +/-. Pointer arithmetic is a raw byte offset, so words + 4 addresses the second word. The compiler tracks literal offsets for compile-time bounds checks; runtime offsets and sizes are unchecked and fail through the VM's own address checks. free(ptr) maps to FREE and invalidates the pointer local. Allocation failures remain a runtime error for a later error-handling pass.

Acceptance. Byte and word buffers can be allocated with literal or runtime sizes, indexed through derived pointers, and freed. Out-of-range literal indices and releases of non-pointer expressions are compile errors.

4. Bitwise operators and hex literals#

Goal. Support pixel packing (x << 16 | y), caret blink (& 1), and color constants.

Syntax sketch.

local packed = x << 16 | y
local color = 0xFFC040

Design. The lexer accepts <<, >>, &, |, ~, and 0x/0X literals. Hex values become normal integer tokens and are emitted as decimal VM immediates. Precedence follows Lua: unary -/~, multiplicative, additive, shifts, &, binary ~, |, then comparisons. Binary ~ maps to XOR, while unary ~ maps to NOT; ~= remains the inequality comparison. Logical and/or/not remain a separate decision.

Acceptance. Shifts, AND/OR/XOR, unary NOT, and hex literals produce the same values as the VM conformance program, and precedence relative to arithmetic and comparisons matches Lua.

5. Static data declarations#

Goal. Emit the bitmap font and compile-time constants without raw assembly.

Syntax sketch.

const FRAME_MS = 66
const BASE = 0x100
const glyphs = bytes { 0x88, 0x88, 0xC8, 0xB0 }
const offsets = words { BASE, BASE + 2 }
const rows = quads { 0x0102030405060708, -1 }

Design. Top-level constants are folded with the VM's 64-bit arithmetic and emitted as EQU directives. Initialized tables get labels and are emitted with DB, DW, or DQ. Because the assembler's DW is a 16-bit directive while LOAD32 reads four bytes, each compiler word becomes two DW halves in big-endian order; quadwords use DQ. Strings continue to use STR labels. Const table names behave like array pointers, support name[i], and carry the same compile-time bounds checks. Declarations must appear before use, and constants cannot be reassigned. Data is emitted after code so the assembler's entry JMP still skips it.

Acceptance. Constants are usable in expressions and data initializers; byte, word, and quadword tables are emitted with correct big-endian layout; labels are referenceable and indexable.

6. Device/runtime intrinsics#

Goal. Expose the stdlib device macros to generated programs.

Syntax sketch.

local w, h = screen_size()
set_color(0x101018)
clear()
plot(x, y)
draw()
local key = read_key()
if quit_requested() then return end
local now = now_ms()
sleep(20)

Design. The intrinsic names are reserved and cannot be redefined as Lua functions. Each call emits the matching stdlib macro and pulls in only the screen.asm, controller.asm, or timer.asm file that defines it. screen_size() is the one two-result intrinsic and requires local w, h = screen_size(); codegen emits SCREEN_SIZE and assigns the locals in reverse stack order. plot(x, y) packs (x << 16) | y before calling PLOT. Void intrinsics are statements, while read_key(), quit_requested(), and now_ms() fold into integer expressions. sleep(ms) emits DEO 0x41, the SDL3/WASM host-extension port used by the typography demo.

Acceptance. The CLI golden fixture keeps the device branch dormant so its transcript stays deterministic; a smoke build flips ENABLE to 1 and runs the same generated ROM under SDL3 and WASM. It prints the 320x240 framebuffer size, reads an idle controller, checks the timer, draws/clears, and yields through sleep before halting.

7. Strings as values and string library bindings#

Goal. Store titles/status text, measure it, and print it from variables.

Syntax sketch.

local title = "0XVM TYPE"
print(title)
local n = strlen(title)

Design. A string local reserves two VM cells: addr then length. Every string expression pushes that pair in the same order, and assignment writes the length slot before the address slot. Literals and string locals can be passed to strlen, print_str, strcmp, strfind, strchr, and strcpy; only the bindings that need runtime helpers include stdlib/strings.asm. slice(s, start, count) is compiled inline with constant offsets and emits a new pair clamped to the source bounds. Byte indexing reads one byte from addr + i and is read-only; string values cannot be used in integer arithmetic or returned from functions.

Acceptance. The golden fixture assigns literals to string locals, prints them (including embedded newlines), measures and compares them, indexes and searches them, slices to a shorter string, copies a slice into heap memory, and frees that buffer.

8. Modules/includes#

Goal. Split a large program into files like examples/typography/.

Syntax sketch.

import "font"
import "layout"

Design. import "name" is a top-level statement; the loader resolves name.lua relative to the importing file and splices the module's statements at the import point. Imports may nest, but each file may be imported only once and cycles are rejected. Constants, data tables, functions, and top-level locals share one symbol table, so modules can call each other's functions and use each other's constants. Everything is concatenated into one .asm with globally unique generated labels, so only the root program emits the main ENTER frame; each Lua function keeps its own frame. compile_file performs expansion, while the string-based compile_source helper rejects unresolved imports.

Acceptance. A multi-file golden program imports a nested module, uses its constants, data, functions, and text, and runs through the CLI host. Missing, duplicate, and circular imports produce clear compile errors.

9. Source-line mapping, break/continue, elseif#

Goal. Make large generated programs debuggable and control flow readable.

Design. elseif is parsed as nested If nodes sharing one end, and break/continue jump through a codegen loop-label stack. continue jumps to the condition label in while loops and to the increment label in numeric for loops. Each AST node carries its source line and file; emitted assembly lines are recorded in a .lumap sidecar written by 0xluac -m. 0xdb -m loads that map and overlays it on assembler line metadata, so print_current, list, and line breakpoints can use Lua file/line references. Fallback behavior for assembly sources or ROMs without a map is unchanged.

Acceptance. A golden program uses elseif, break, and continue; a scripted 0xdb session sets a breakpoint with control.lua:9 and steps with Lua line display. Missing loop jumps and missing source metadata remain clear compile errors.

Workflow#

  1. Update the status and notes in this document for the chosen item.
  2. Implement the item in luac/.
  3. Add/extend unit checks in tests/test_luac.py and a golden program under

tests/lua/.

  1. Run make lua-check and make test.
  2. Commit only that item with a focused message, then start the next item.

Progress log#

  • Baseline — initial compiler package and 0xluac CLI committed as

ec42e21.

  • Item 1 — functions with parameters, returns, scopes, forward calls, and

recursion; golden fixture tests/lua/functions.lua.

  • Item 2 — static byte/word arrays, indexing, and compile-time bounds

checks; golden fixture tests/lua/arrays.lua.

  • Item 3 — typed heap allocations, pointer offsets, runtime sizes, and

free; golden fixture tests/lua/heap.lua.

  • Item 4 — shifts, bitwise AND/OR/XOR/NOT, hex literals, and Lua

precedence; golden fixture tests/lua/bitops.lua.

  • Item 5 — EQU constants and initialized byte/word/quad data tables;

golden fixture tests/lua/data.lua. Also corrected static word arrays to reserve four bytes per element.

  • Item 6 — screen/controller/timer intrinsics and sleep; golden fixture

tests/lua/devices.lua plus SDL3/WASM device smoke runs.

  • Item 7 — (addr, len) string locals, stdlib bindings, read-only indexing,

and clamped slicing; golden fixture tests/lua/strings.lua.

  • Item 8 — top-level import, relative module resolution, one-time

expansion, and merged symbol tables; golden fixture tests/lua/modules.lua.

  • Item 9 — elseif, break/continue, AST source metadata, .lumap

sidecars, and 0xdb Lua line breakpoints; golden fixture tests/lua/control.lua.

  • Capstone — examples/typography.lua, a Lua-source graphical text editor

using the font table, layout helpers, caret editing, blink, and timed loop. Its ENABLE constant is flipped for the CLI golden run, and bounded smoke builds run under SDL3 and WASM.

  • Raycaster capstone — examples/raycaster.lua, a fixed-point DDA maze

explorer with shaded walls, collision, minimap, and scripted browser checks.

Capstone demo#

examples/typography.lua is the typography-level program the work items were building toward. It keeps editor state and the text buffer in const data tables, which are writable global VM labels because functions cannot share top-level locals in the current ABI. Caption byte tables replace string arguments, since string values are two-cell (address, length) pairs and are not valid function parameters yet. The program still uses string literals for the intro and completion lines.

make lua-typography-check runs a CLI-safe build (ENABLE = 0), then a bounded SDL3 smoke build (FRAME_MS = 1, MAX_FRAMES = 3) that draws the full editor. make wasm includes the interactive ROM. make wasm-check builds it again with REPORT = 1 so the script can read the state and text labels, then exercises insert, caret movement, backspace, delete, and exit in the browser host. The assembly demo remains unchanged, so its browser editing checks continue to cover the original app too.

Raycaster demo#

examples/raycaster.lua is a second complex program built from the same subset. It uses 8.8 fixed-point player coordinates, 256-entry sine/cosine lookup tables, and integer DDA to cast one ray per screen column. Wall distance selects a colour from near-to-far palettes, and Y-side hits use a darker palette. A cell map, minimap, collision tests, and all mutable player state are const data tables, since top-level locals cannot be shared across functions.

ENABLE defaults to 1 here, so a direct SDL3 run renders the maze; the CLI golden build flips it to 0. The bounded smoke build also sets FRAME_MS = 1 and MAX_FRAMES = 3. make lua-raycaster-check covers the CLI golden and a rendered SDL smoke run. make wasm-check builds a REPORT = 1, FRAME_MS = 0 variant so scripted key presses are consumed without waiting on wall-clock pacing, then checks turn, move, strafe, and exit in the browser host.

docs / Roadmap

0xvm roadmap#

This roadmap tracks the work after the v2 VM core and assembler were complete. Each milestone is validated with make test, which builds the core C tests, runs the CLI conformance transcript, checks 0xdb, and — when their optional toolchains are present — checks the SDL and WASM hosts too.

Done#

  1. Opcode and assembler cleanup — [done].
    • ABI v2 is frozen: 64-bit cells, 64 KiB byte-addressed RAM, 16-bit addresses,

byte-encoded instructions, VMIM v2 ROMs, and a device page for all I/O.

  • 0xasm supports the complete opcode set, expressions, conditionals,

macros, and INCLUDE.

  • All readable pseudo-ops are opt-in macros from stdlib/. They are not VM

opcodes and are not loaded implicitly.

  • make test runs the C unit tests and the golden CLI transcript.
  1. Finish the debugger — [done].
    • 0xdb provides step, next, finish, until, continue, breakpoints,

stack/RAM/frame dumps, source listing, and scripted sessions.

  • Assembler symbols and source paths are exposed as source-level metadata;

the ROM format is unchanged.

  • apps/db/ is split into focused modules behind a shared db.h.
  • Optional follow-up: System inspection ports for sp, fp, tick count,

and top-of-stack for guests that want to inspect themselves.

  1. Prove the host split with a second host — [done].
    • Shared host layer and headless dispatch tests.
    • SDL3 host (0xvm-sdl) exposes Screen, Controller, and timer ports. It is

detected via pkg-config sdl3 and never becomes a core dependency.

  • Console text remains on terminal stdin/stdout in both hosts.
  • examples/paint.asm is an interactive demo of the SDL ports.

Next#

The toolchain, software layer, flagship SDL app, and browser host are complete. The next milestone is a Lua-subset compiler targeting the stdlib runtime.

  1. Grow the software layer — [done].
    • Turned stdlib/ into a tested runtime, still entirely opt-in source macros.

Every addition has a golden test under tests/.

  • Strings: length, compare, concat, substring, find, and copy, all based on

the (addr, len) convention used by PRINT_STR / READ_STR. Numeric formatting stays in the host Console ports.

  • Collections: a dynamic array and a key/value table over an arena rather

than one allocation per entry.

  • Allocator policy: arena/bump wrapper, explicit-free helper, and a

documented refcount pattern.

  • Utilities: a deterministic RNG, min/max/clamp, and bit helpers.
  • Kept the debugger and conformance suite aligned with each addition.
  1. Flagship Snake app — [done].
    • Add one app that exercises the whole stack at once. Snake on 0xvm-sdl

uses Screen, Controller, and timer ports, heap for the body, strings for the score, and RNG for food.

  • Keep console text I/O on terminal stdin/stdout; the SDL host exposes only

Screen, Controller, and timer devices.

  1. Browser / WASM host — [done].
    • Added a browser host behind the same VmDevice callback split so programs

can be loaded from a file.

  • The canvas page boots a baked-in boot.rom (no separate fetch), keeps

Run/Pause, Restart, load-file, screen-size presets, and console controls, and maps keyboard input to the portable Controller codes; the Node smoke check runs Snake headlessly.

  • Added a generated single-page showcase (site/index.html → build/index.html)

with a trimmed embedded host view (site/host.html → build/0xvm-embed.html) that carries the screen, controls, ROM buttons, and console.

  • Kept the core, CLI tools, and native test suite free of host GUI dependencies.
  1. Lua-subset compiler — [next].
    • Compile numbers, strings, tables, if/while/for, and plain functions

to 0xasm text.

  • Target the stdlib/ runtime routines instead of emitting raw heap and

memory manipulation.

  • Emit line/symbol metadata so 0xdb steps through the source language.
  1. Richer debugger — [later].
    • Watch/list expressions and conditional breakpoints once source-level

variable metadata exists.

  • Consider typed source metadata for locals.
  • Consider a lightweight package/import convention on top of INCLUDE.

Non-goals for the near term#

  • No new opcodes; ABI v2 is frozen and the current instruction set is sufficient.
  • No vector/SIMD opcodes; scalar untyped cells remain the model.
  • No host filesystem device; file access is via host-specific ports or offline

tooling.

  • No ABI change to ROMs for debugger metadata.
  • No mandatory dependency added to lib0xvm, 0xvm, or the assembler.