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.
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
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. |
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.
Integers & Radix Literals
64-bit signed integers with decimal, hex, binary, octal, and digit separator notation.
Pattern Matching & Arm Guards
Exhaustive pattern matching supporting integer ranges, variant extraction, and conditional guards.
Destructuring & Rest Bindings
Extracting nested values from arrays and maps with rest bindings (..rest).
Functional Pipelines (|>)
Elixir-style data forward pipe passing the evaluated left operand as the first argument.
Predictable Error Handling
Structured try/catch/throw with full call-stack frame retention and typed errors.
Standard Library Specifications
Built directly into the binary runtime with zero external package dependencies.
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) 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] }) 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) 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) 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") 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]) 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) 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() 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)