Language Reference & Publication Guide

The Shae Language Reference

Complete syntax specification, CLI toolchain, standard library primitives, and the official 42-page publication book. Designed under The Dual-Lens Philosophy: pedagogical clarity paired with silicon-level systems depth.

Official Publication Book 42 Pages • 496 KB The Dual-Lens Philosophy

The Shae Programming Language: From Sand to Supercomputers

By Shae Core Engineering Team • Release v0.7.0 • Verified LaTeX Typeset Edition

The Dual-Lens Philosophy: Every chapter presents concepts through two synchronized perspectives: first an intuitive, visual metaphor (ELI5) that builds conceptual intuition, followed immediately by the deep systems reality—CPU registers, cache lines, virtual stack frames, Bytecode opcodes, LLVM SSA form, and zero-copy memory buffers.

Complete Table of Contents (Chapters 1–16)

16 Chapters • 42 Pages
Ch 1
The Magic of Computers and Why Shae Exists
Foundations & Concepts
From sand to silicon: CPU instructions, clock cycles, operating systems, and the design imperative behind Shae.
Ch 2
The Journey of Code: From Human Text to Silicon Execution
Foundations & Concepts
Tracing a source file through lexing, Pratt parsing, AST construction, bytecode emission, and machine execution.
Ch 3
The First Words: Variables, Memory Boxes, and Scope
Foundations & Concepts
Stack frames, registers, lexical closures, upvalue capturing, and variable mutability semantics.
Ch 4
The Building Blocks: The Complete Type System
Language Syntax
Int(i64), Float(f64), Radix literals (0x, 0b, 0o), strings, UTF-8 grapheme clusters, arrays, and maps.
Ch 5
Making Decisions: Control Flow and Pattern Matching
Language Syntax
Branch prediction, expression-oriented if/else, loops, pattern matching with arm guards, and range patterns.
Ch 6
Actions and Recipes: Functions, Closures, and Pipelines
Language Syntax
First-class functions, anonymous closures, call frames, implicit returns, and the |> pipeline operator.
Ch 7
When Things Go Wrong: Predictable Error Handling
Language Syntax
Structured try/catch/throw exceptions, virtual stack preservation, panic unwinding, and graceful recovery.
Ch 8
Inside the Engine Room: Virtual Machine Architecture & Bytecodes
Virtual Machine & Systems
Dual-engine architecture: stack bytecode VM, dispatch loop, opcodes, call frames, and mark-and-sweep GC.
Ch 9
Concurrency: Fibers, Coroutines, and Channels
Virtual Machine & Systems
Lightweight cooperative fibers, std:async coroutines, task combinators (all, race), and CSP channels.
Ch 10
The Actor Model & Distributed Clustering (std:actor & std:actor:cluster)
Virtual Machine & Systems
Erlang-style lightweight thread actors, FIFO mailboxes, supervision trees, TLS/mTLS cluster mesh, and hot-code reloading.
Ch 11
Raw Systems Programming & Zero-Copy Memory (std:buffer)
Advanced Systems
Contiguous ByteBuffer, shared Arc slicing without allocations, endian numeric I/O, and struct pack/unpack.
Ch 12
Direct LLVM SSA Compilation & Native Machine Code (shae llvm)
Advanced Systems
Direct LLVM 18 SSA IR generation, mem2reg promotion, C ABI interop, and Clang -O2 native compilation.
Ch 13
The Holy Grail: The Self-Hosting Compiler Pipeline
Advanced Systems
The 14-module pure-Shae compiler suite in lib/compiler/, self-parsing, self-codegen, and Stage 2 bit-for-bit identity.
Ch 14
The Developer Tooling Ecosystem
Toolchain & Ecosystem
The CLI suite: shae fmt, shae check linter, shae test runner, shae bench telemetry, and shae doc generator.
Ch 15
Cross-Platform Distribution & The Universal Installer
Toolchain & Ecosystem
Precompiled binary matrix for Linux, macOS, and Windows, install.sh mechanics, and VS Code LSP extension.
Ch 16
Complete Syntax Grammar & Vocabulary Glossary
Reference & Index
Exhaustive EBNF grammar specification, opcode dictionary, standard library index, and engineering glossary.
Command Line Toolchain

Unified CLI Commands (shae)

The single static binary contains the execution runtime, compiler, linter, formatter, doc server, and test runner.

Command Syntax Arguments Behavior & Pipeline Execution
shae <file.shae> — Executes a Shae source file through the high-performance stack Bytecode VM.
shae run <file.shae> — Explicit invocation of the bytecode execution engine.
shae — Launches the interactive VM REPL with persistent globals, multiline input, and :disasm.
shae check <file.shae> — Runs static analysis and gradual type checking: verifies return types, parameter types, union bounds, dead code, and variable typos.
shae fmt <file.shae> [--check] Canonical 4-space AST code formatter. --check verifies formatting without writing.
shae compile <file.shae> -o <out.shaec> AOT compiles source into serialized bytecode with \x7fSHAE magic header.
shae disasm <file.shaec> — Disassembles bytecode into human-readable opcodes, constants, and upvalue capture tables.
shae llvm <file.shae> [-c] [-o bin] [-r] Emits direct LLVM 18 SSA IR. -c compiles to standalone binary via Clang -O2; -r runs immediately.
shae test [path] [-f pattern] Discovers and executes test files (*_test.shae) with built-in assertion diagnostics.
shae bench [filter] [-i iters] Executes language microbenchmark suite with ops/sec throughput and average latency reports.
shae doc [path] [--serve --port 8080] Extracts /// and //! comments into static HTML, Markdown, or serves live documentation server.
shae lsp — Runs the Language Server Protocol daemon for VS Code, providing live diagnostics and completions.
shae pkg <cmd> init|add|install|pack|publish|verify Deterministic package manager managing dependencies via shae.toml and shae.lock, with remote HTTP registry support.
shae ide [--port 8080] Launches Shae Studio Web IDE with integrated code editor, compiler runner, and interactive visual canvas.
shae wasm <file.shae> [--run] Pure-Shae WebAssembly binary (.wasm) compiler and built-in WasmRunner interpreter.
Core Language Syntax

Syntax Primitives & Patterns

Modern expression-oriented ergonomics without boilerplate ceremony.

Gradual Type Annotations

Opt-in static typing on function parameters, return bounds, and variable bindings with nullable union types.

fn divide(numerator: float, denominator: float) -> float | null {
    if denominator == 0.0 {
        return null
    }
    return numerator / denominator
}

let result: float | null = divide(10.0, 2.0)
print("Result: {result}")

// Compile-time verification:
// $ shae check math.shae
// [OK] Type checking passed with 0 errors

Integers & Radix Literals

64-bit signed integers with decimal, hex, binary, octal, and digit separator notation.

let dec = 42
let hex = 0xFF        // 255
let bin = 0b1010_0110 // 166
let oct = 0o755       // 493
let large = 1_000_000 // Underscore separators

Pattern Matching & Arm Guards

Exhaustive pattern matching supporting integer ranges, variant extraction, and conditional guards.

match event {
    { type: "login", user } if user.is_admin => "Admin session: {user.name}",
    { type: "login", user } => "Standard session: {user.name}",
    { code: 400..=499 } => "Client error",
    _ => "Unhandled"
}

Destructuring & Rest Bindings

Extracting nested values from arrays and maps with rest bindings (..rest).

let [first, second, ..tail] = [10, 20, 30, 40, 50]
print("First: {first}, tail length: {tail.length}")

let { host, port, ..opts } = { host: "127.0.0.1", port: 8080, timeout: 5000 }
print("Connecting to {host}:{port}")

Functional Pipelines (|>)

Elixir-style data forward pipe passing the evaluated left operand as the first argument.

let processed = [5, 12, 8, 130, 44]
    |> filter(fn(x) { x >= 10 })
    |> map(fn(x) { x * 2 })
    |> sort()
    |> reverse()

Predictable Error Handling

Structured try/catch/throw with full call-stack frame retention and typed errors.

try {
    let raw = read_file("missing_file.json")
    let data = json_parse(raw)
} catch err {
    print("Handled file error: {err}")
}
Native Modules

Standard Library Specifications

Built directly into the binary runtime with zero external package dependencies.

Zero-Copy Memory Chunk 29

std:buffer

High-throughput contiguous byte buffers with zero-copy slicing, endian binary I/O, and C-struct packing.

ByteBuffer.new(size: Int) -> ByteBuffer

Allocates a raw contiguous byte buffer initialized to zero.

let buf = ByteBuffer.new(1024)
buf.slice(start: Int, end: Int) -> ByteBuffer

Creates a child slice referencing the identical Arc<RwLock<Vec<u8>>> memory without heap allocation.

let sub = buf.slice(8, 24) // Mutating sub mutates buf in-place
buf.read_u32_le(offset: Int) / buf.write_u32_le(offset, val) -> Int

Reads or writes a 32-bit unsigned integer in Little-Endian byte order. Also supports u8..u64, i8..i64, f32, f64 in _le and _be.

buf.write_u32_le(0, 0xDEADBEEF)
let val = buf.read_u32_le(0)
pack(fmt: String, ...values) -> ByteBuffer

Packs values into a binary buffer according to format string (<I2h4s = LE 32-bit int, two 16-bit ints, 4-char string).

let packet = pack("<I2h4s", 1001, 20, -5, "SHAE")
unpack(fmt: String, buf: ByteBuffer, [offset]) -> Array

Unpacks raw binary buffer into an array of typed Shae values according to format specifier.

let [id, x, y, tag] = unpack("<I2h4s", packet)
Distributed Actors & Mesh Chunks 14, 19, 21, 30

std:actor & std:actor:cluster

Lightweight thread actors, FIFO mailboxes, supervision trees, TLS/mTLS cluster mesh, and hot-code reloading.

spawn_actor(handler: Function, [initial_state]) -> ActorHandle

Spawns an independent actor thread with an unbounded FIFO message mailbox and zero-idle CPU consumption.

let counter = spawn_actor(fn(state, msg) { state + msg }, 0)
actor.send(msg: Any) -> nil

Asynchronously enqueues a message into the actor mailbox (fire-and-forget).

counter.send(5)
actor.ask(msg: Any, [timeout_ms: Int]) -> Any

Sends a message and synchronously awaits reply with an automatic correlation ID and timeout protection.

let total = counter.ask("get_state", 1000)
actor.reload(new_handler: Function, [migration_fn]) -> nil

Hot-swaps actor handler function at runtime while preserving active thread execution, state, and queued messages (Chunk 30).

actor.reload(new_handler, fn(state) { { count: state.total } })
ClusterNode.new(config: Map) -> ClusterNode

Initializes a distributed cluster node with Rustls 0.23 mutual TLS (mTLS) encryption, cookie auth, and TCP framing.

let node = ClusterNode.new({ name: "alpha", bind: "0.0.0.0:9001", tls_cert: "cert.pem", tls_key: "key.pem" })
node.actor(remote_uri: String) -> RemoteActorHandle

Returns a handle to an actor hosted on a remote cluster node. Supports ask and send over length-delimited TLS framing.

let worker = node.actor("calc@10.0.0.2:9001")
let res = await worker.ask({ op: "sum", data: [1, 2, 3] })
Native Coroutines Chunk 22

std:async

First-class asynchronous coroutines with cooperative scheduling and parallel combinators.

async.spawn(func: Function) -> Task

Spawns a cooperative non-blocking asynchronous task returning an awaitable handle.

let task = async.spawn(fn() { fetch("https://api.example.com/data") })
await task -> Any

Suspends coroutine execution until task resolves, returning value or throwing on error.

let result = await task
async.all(tasks: Array) -> Array

Runs an array of tasks concurrently, resolving when all succeed.

let [user, posts] = await async.all([taskUser, taskPosts])
async.race(tasks: Array) -> Any

Returns value of first task to resolve, cancelling or ignoring remaining tasks.

let fastResult = await async.race([primaryTask, backupTask])
async.sleep(ms: Int) -> nil

Non-blocking cooperative sleep yielding thread to other coroutines.

await async.sleep(250)
Authenticated Ciphers Chunks 8 & 26

std:crypto

Industrial authenticated encryption (AES-256-GCM, ChaCha20-Poly1305), HKDF, PBKDF2, SHA-2/3, and HMAC.

crypto.sha256(data: String | ByteBuffer) -> String

Computes SHA-256 cryptographic digest returning lowercase hex string.

let hash = crypto.sha256("payload")
crypto.hmac_sha256(key: String, data: String) -> String

Computes Hash-based Message Authentication Code with SHA-256.

let mac = crypto.hmac_sha256("secret_key", "message")
crypto.aes_gcm_encrypt(key, nonce, plaintext, [aad]) -> ByteBuffer

Authenticated symmetric encryption using AES-256-GCM with 128-bit authentication tag.

let ciphertext = crypto.aes_gcm_encrypt(key, nonce, "sensitive payload")
crypto.chacha20_poly1305_encrypt(key, nonce, plaintext, [aad]) -> ByteBuffer

High-speed industrial AEAD cipher combining ChaCha20 stream cipher with Poly1305 authenticator.

let ct = crypto.chacha20_poly1305_encrypt(key, nonce, raw_data)
crypto.hkdf(salt, ikm, info, length) -> ByteBuffer

HMAC-based Extract-and-Expand Key Derivation Function (RFC 5869).

let subkey = crypto.hkdf(salt, master_key, "encryption", 32)
Built-in Servers Chunk 7

std:http & Web

High-throughput non-blocking multi-threaded HTTP/HTTPS server and built-in HTTP client.

serve(port: Int, handler: Function) -> nil

Starts concurrent HTTP server on specified port. Connections are distributed across worker threads.

serve(8080, fn(req) {
    if req.path == "/status" {
        return { status: 200, headers: { "Content-Type": "application/json" }, body: json({ ok: true }) }
    }
    return { status: 404, body: "Not found" }
})
serve_tls(port: Int, cert: String, key: String, handler: Function) -> nil

Rustls-backed HTTPS server supporting ALPN HTTP/1.1 with zero OpenSSL dependencies.

serve_tls(8443, "cert.pem", "key.pem", fn(req) { { status: 200, body: "Secure" } })
fetch(url: String, [options: Map]) -> String

Executes HTTP client request, returning response body as string.

let body = fetch("https://api.github.com/zen")
Embedded Database Chunk 6

std:sqlite

Zero-dependency embedded SQL database with transactions and prepared parameter bindings.

sqlite.open(path: String) -> Database

Opens an on-disk or in-memory (:memory:) SQLite database.

let db = sqlite.open("app.db")
db.execute(sql: String, [params: Array]) -> Int

Executes DDL or DML statement with parameterized bindings, returning rows affected.

db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
db.query(sql: String, [params: Array]) -> Array<Map>

Executes SQL SELECT statement returning array of row maps.

let rows = db.query("SELECT * FROM users WHERE id = ?", [42])
Creative 2D Graphics Chunk 34

std:gui

Multi-mode graphics engine supporting 24-bit TrueColor ANSI half-block terminal rendering, desktop windowing, and sprite blitting.

gui.init(width: Int, height: Int, title: String) -> GuiWindow

Initializes a graphics rendering window or virtual terminal canvas.

let win = gui.init(60, 30, "Space Invaders 2D")
gui.clear(win: GuiWindow, color_hex: Int)

Clears the window buffer with a 24-bit RGB hexadecimal color (e.g. 0x000000).

gui.clear(win, 0x0A0E1A)
gui.draw_sprite(win: GuiWindow, x: Int, y: Int, sprite_data: String, color: Int)

Blits a multi-line ascii/pixel sprite onto the framebuffer at (x, y).

gui.draw_sprite(win, 28, 26, "player_cannon", 0x33FF33)
gui.draw_text(win: GuiWindow, x: Int, y: Int, text: String, color: Int)

Renders text onto the display buffer with ANSI/TrueColor font styling.

gui.draw_text(win, 2, 1, "SCORE: 001420", 0xFFFFFF)
gui.is_key_down(key_name: String) -> Bool

Polls whether a specific keyboard key (Left, Right, Space, Escape, etc.) is currently pressed.

if gui.is_key_down("Space") { fire_laser() }
gui.render(win: GuiWindow)

Flushes the backbuffer to the physical display or terminal using ANSI half-block rendering.

gui.render(win)
Waveform Audio Synthesis Chunk 34

std:audio

Real-time multi-waveform audio synthesis engine with volume envelopes and retro arcade sound triggers.

audio.init() -> AudioEngine

Initializes the hardware audio playback thread and Rodio audio sink.

let sound = audio.init()
audio.play_sound(sound_name: String)

Triggers a built-in retro arcade sound FX: "shoot", "invader_killed", "explosion", or "step".

audio.play_sound("shoot")
audio.play_tone(frequency_hz: Float, duration_ms: Int, wave_type: String)

Synthesizes an immediate waveform tone: "sine", "square", "triangle", "sawtooth", or "noise".

audio.play_tone(440.0, 150, "square")
audio.set_volume(volume: Float)

Sets the master audio playback volume (0.0 to 1.0).

audio.set_volume(0.85)
audio.sound_names() -> Array<String>

Returns the list of all registered retro sound effect names.

let sounds = audio.sound_names()
Arcade UI & Widgets Chunk 34

std:ui

Arcade HUD layout engine, retro typography, and immediate-mode UI widgets.

ui.draw_panel(gui: GuiWindow, x: Int, y: Int, w: Int, h: Int, title: String)

Renders a framed arcade panel border with title header.

ui.draw_panel(win, 0, 0, 60, 30, "SPACE INVADERS")
ui.draw_hud(gui: GuiWindow, score: Int, lives: Int, wave: Int)

Draws the standardized arcade heads-up display with score, remaining lives, and wave counter.

ui.draw_hud(win, score, lives, wave)
ui.draw_score(gui: GuiWindow, x: Int, y: Int, score: Int, label: String)

Draws zero-padded numeric arcade score text (e.g. SCORE: 001500).

ui.draw_score(win, 2, 1, 1500, "SCORE")
ui.draw_lives_icons(gui: GuiWindow, x: Int, y: Int, lives: Int, max_lives: Int)

Draws graphical tank/heart icons representing remaining player lives.

ui.draw_lives_icons(win, 48, 1, 3, 3)