Features & Systems Architecture
An engineering deep-dive across all 34 language evolution chunks. Explore Shae's native LLVM 18 SSA generator, Cranelift JIT tiered compilation, zero-copy typed memory buffers, fault-tolerant TLS/mTLS actor cluster mesh, live hot-code reloading, and pure-Shae self-hosting bootstrap pipeline.
Unified Execution & Lowering Topology
From source tokens to SSA register allocation, in-memory JIT machine code, and standalone native object linking.
+---------------------------------------------------------------------------------------------------------+
| SHAE SOURCE CODE (*.shae) |
+---------------------------------------------------------------------------------------------------------+
|
v
+-----------------------------------------------------------+
| Lexer & Pratt Recursive-Descent Parser (src/parser.rs) |
| Self-Parsing Pure-Shae Frontend (lib/compiler/parser.shae)|
+-----------------------------------------------------------+
|
+---------------------------+---------------------------+
| |
v v
+----------------------------------+ +----------------------------------+
| AST Evaluator (src/eval.rs) | | Bytecode Compiler (Chunk 3/11) |
| - Tree-walking evaluation | | - Constant pool allocation |
| - Instant startup (sub-2ms) | | - Local slot resolution |
| - Full language semantics | | - Binary .shaec emission |
+----------------------------------+ +----------------------------------+
| |
| +-----------------------+-----------------------+
| | |
| v v
| +-----------------------------+ +-----------------------------+
| | Stack Bytecode VM (vm.rs) | | Cranelift JIT SSA (jit.rs) |
| | - Local slot resolution | | - In-memory machine code |
| | - Fast CallFrame dispatch | | - JIT_THRESHOLD = 20 calls |
| | - Upvalue closure captures | | - Native float SSA math |
| +-----------------------------+ +-----------------------------+
| | |
+-------------------------------+-----------------------------------------------+
|
v
+-----------------------------------+
| DUAL-ENGINE PARITY BOUNDARY |
| 100% Identical Value Semantics |
+-----------------------------------+
|
+--------------------------------+---------------+-------------------------------+
| | |
v v v
+-------------------------------+ +-------------------------------+ +-------------------------------------------+
| Zero-Copy Typed ByteBuffer | | TLS/mTLS Cluster Actor Mesh | | Direct LLVM 18 SSA & Native Linker |
| (Chunk 29, src/buffer.rs) | | (Chunk 30, actor_cluster.rs) | | (Chunk 28, src/llvm.rs / shae llvm) |
| - Arc<RwLock<Vec<u8>>> | | - Rustls 0.23 mutual TLS | | - Entry block alloca + mem2reg |
| - Zero-heap child slicing | | - ActorMessage::Reload | | - Clang -O2 standalone binary compile |
| - Endian numeric binary I/O | | - ClusterWireMsg::Reload | | - Pure-Shae ELF/PE Linker (linker.shae) |
| - Struct pack/unpack <I2h4s | | - Continuous state migration | | - WebAssembly Emitter (wasm.shae) |
+-------------------------------+ +-------------------------------+ +-------------------------------------------+
LLVM 18 SSA Compiler (shae llvm)
Shae implements direct code generation targeting compliant LLVM 18 Single Static Assignment (SSA) intermediate representation without requiring bulky C library wrapper dependencies.
Entry Block Alloca & Register Promotion
Rather than generating complex φ (phi) nodes directly during AST traversal, Shae's
LLVM frontend emits local variables into the function's %entry basic
block using typed alloca instructions. LLVM's canonical mem2reg optimization pass automatically lifts these stack variables into
hardware SSA virtual registers, ensuring maximum optimization without frontend bloat.
External C ABI Interoperability
The LLVM backend declares standard C ABI runtime symbols (printf, puts, malloc, free, exit), maps
Shae functions to native calling conventions, and generates a standard @main entry point that initializes globals and runs top-level statements.
Clang -O2 Pipeline Integration
Using the -c flag, Shae automatically invokes the system Clang compiler
with -O2 optimization, producing standalone, stripped native executables
ready for deployment.
shae llvm file.shae -o file.ll — Emit raw LLVM 18 IR shae llvm -c file.shae -o binary — Compile native binary via Clang -O2 shae llvm -r file.shae — Compile and run immediately ; ModuleID = 'fibonacci.shae'
target triple = "x86_64-pc-linux-gnu"
target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
declare i32 @printf(i8*, ...)
declare void @exit(i32)
define i64 @fib(i64 %n) {
entry:
%t.0 = icmp sle i64 %n, 1
br i1 %t.0, label %then.1, label %else.2
then.1:
ret i64 %n
else.2:
%t.1 = sub i64 %n, 1
%t.2 = call i64 @fib(i64 %t.1)
%t.3 = sub i64 %n, 2
%t.4 = call i64 @fib(i64 %t.3)
%t.5 = add i64 %t.2, %t.4
ret i64 %t.5
}
define i32 @main() {
entry:
%res = call i64 @fib(i64 20)
ret i32 0
} Cranelift 0.136.2 JIT SSA Engine
High-speed in-memory Just-In-Time machine code generation targeting x86_64 and AArch64 with automatic call-frequency tiering and deoptimization fallbacks.
Tiering Threshold: JIT_THRESHOLD = 20
Shae employs an adaptive tiering strategy. During initial script execution, functions
run on the lightweight Bytecode VM with zero compilation latency. Once any compiled
function reaches JIT_THRESHOLD = 20 invocations, the VM
background-compiles its bytecode into Cranelift SSA IR.
Direct C Function Pointer Execution
Compiled native code is emitted directly into executable memory pages and invoked via
the standard C calling convention:
unsafe extern "C" fn(*const i64, usize, *mut i64) -> i32. This
completely bypasses virtual stack dispatch, opcode fetch-decode loops, and interpreter
call overhead.
Native Float SSA & Deoptimization Fallback
Numerical operations use Cranelift's native 64-bit float registers (
types::F64) and integer registers (types::I64). If dynamic
types diverge at runtime or an unsupported opcode is encountered, execution seamlessly
falls back to the Bytecode VM interpreter.
| Backend Engine | Cranelift 0.136.2 SSA JIT |
|---|---|
| Tiering Threshold |
20 calls (JIT_THRESHOLD = 20)
|
| Memory Access | MachMemFlags::trusted() |
| Target Architectures | x86_64, aarch64 (Apple Silicon / Linux ARM) |
// Hot loop automatically triggers Cranelift JIT tiering
fn compute_pi(iterations) {
let pi = 0.0
let sign = 1.0
let i = 0
while i < iterations {
pi = pi + sign / (2.0 * i + 1.0)
sign = -sign
i = i + 1
}
return pi * 4.0
}
// Invocations 1..19: Bytecode VM execution
// Invocation 20: Cranelift JIT compilation triggered
// Invocations 21+: Direct machine code execution (~80,000 ops/sec)
let result = compute_pi(100000)
print("Approximated Pi: {result}")
Zero-Copy Typed Memory Buffers (std:buffer)
Engineered for high-volume network packet parsing, file formats, and IPC. A thread-safe container sharing underlying storage without heap copies.
Shared Arc Storage & Zero-Allocation Slices
The ByteBuffer struct wraps storage: Arc<RwLock<Vec<u8>>> with local offset and length tracking. Calling buf.slice(start, end) creates a lightweight window pointing to the exact
same storage without copying bytes. Mutating a byte in the child slice updates the
parent buffer immediately.
Endian-Aware Multi-Byte Reads & Writes
Read and write 16-bit, 32-bit, and 64-bit integers and floating-point values with
explicit byte order:
read_u16_le, write_u16_be, read_u32_le, write_i64_be, read_f64_be.
High-Performance Struct Packing Engine
Python-compatible format strings (e.g., <I2h4s for Little-Endian u32,
two i16s, and a 4-byte ASCII string) provide single-step packing and unpacking via pack, unpack, pack_into, and calcsize.
Parent ByteBuffer [ offset: 0, length: 24, storage: Arc<RwLock<Vec<u8>>> ]
|
+---> [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 ]
^ ^
| |
Child Slice ByteBuffer ------------+-------------------------------+
[ offset: 8, length: 8, storage: Arc<RwLock<Vec<u8>>> ]
(Mutating child[0] mutates parent[8] in-place with ZERO memory allocation) use { alloc, pack, unpack, calcsize } from "std:buffer"
// 1. Zero-copy slicing & shared mutation
let parent = alloc(24)
let slice = parent.slice(8, 16)
slice[0] = 255
assert(parent[8] == 255, "Zero-copy mutation verified")
// 2. Endian-aware multi-byte numeric reads/writes
let buf = alloc(32)
buf.write_u16_le(0, 0x1234) // [0x34, 0x12]
buf.write_u16_be(2, 0x1234) // [0x12, 0x34]
buf.write_f64_be(4, 3.1415926535)
// 3. High-performance struct layout packing
let sz = calcsize("<I2h4s") // 12 bytes
let packet = pack("<I2h4s", 4000000000, -800, 1600, "SHAE")
let fields = unpack("<I2h4s", packet)
print("u32: {fields[0]}, i16: {fields[1]}, tag: {fields[3]}")
TLS/mTLS Cluster Mesh & Hot-Code Reloading (std:actor:cluster)
Zero-downtime actor logic swapping, schema migrations, and mutual TLS encryption across distributed clusters.
Zero-Downtime Hot-Code Reloading
In production services, stopping an actor drops active state and pending mailbox
requests. Shae introduces ActorMessage::Reload: an actor handler function
is swapped atomically in place. The actor thread continues executing without dropping
queued FIFO messages.
Live State Schema Migrations
When new code requires a different state schema, pass an optional migration closure: actor.reload(new_handler, migration_fn). The migration function
transforms the active state (e.g., from V2 plain map to V3 versioned schema) before
the new handler processes the next message.
Distributed Cluster Mesh Reload & mTLS Security
Hot reloads propagate across the cluster over encrypted TCP framing using ClusterWireMsg::Reload. The cluster mesh uses Rustls 0.23 for mutual TLS (mTLS): both client and server
authenticate using trusted root CAs (ClusterTlsConfig), completely
isolating rogue nodes.
Primary Node Alpha Worker Node Beta (pricing_engine)
| |
| remote_actor.reload(v2_handler, migration_fn) |
|-------------------------------------------------------------->|
| ClusterWireMsg::Reload { actor_name, handler_code } |
| |
| 1. Enqueue ActorMessage::Reload
| 2. Finish active message
| 3. Execute migration_fn(&mut state)
| 4. Atomically swap handler pointer
| 5. Process remaining FIFO mailbox
| |
|<--------------------------------------------------------------|
| ClusterWireMsg::Reply { correlation_id, status: "ok" } | let actor = use "std:actor"
let cluster = use "std:actor:cluster"
// 1. Spawn initial stateful actor (V1)
let account = actor.spawn({ "balance": 1000, "tx": 0 }, fn(st, msg) {
if msg["op"] == "deposit" {
let next = { "balance": st["balance"] + msg["amount"], "tx": st["tx"] + 1 }
return { "state": next, "reply": next["balance"] }
}
return st
})
// 2. Hot-reload to V2 handler with schema migration
let migration_fn = fn(old_st) {
return {
"schema_version": 2,
"funds": old_st["balance"],
"migrated_tx": old_st["tx"]
}
}
let v2_handler = fn(st, msg) {
if msg["op"] == "deposit" {
let bonus = msg["amount"] / 10 // 10% bonus credit
let new_funds = st["funds"] + msg["amount"] + bonus
let next = { "schema_version": 2, "funds": new_funds, "migrated_tx": st["migrated_tx"] + 1 }
return { "state": next, "reply": { "funds": new_funds, "bonus": bonus } }
}
return st
}
account.reload(v2_handler, migration_fn)
let reply = account.ask({ "op": "deposit", "amount": 200 })
print("Deposited under V2 without losing state: {reply['funds']}") // 1220
Pure-Shae Self-Hosting Bootstrap Pipeline (lib/compiler/)
The complete Shae toolchain—lexer, Pratt parser, bytecode compiler, disassembler, native ELF/PE linker, WebAssembly emitter, and LLVM IR generator—is implemented entirely in pure Shae.
14 Modular Pure-Shae Compiler Units
Divided cleanly across 14 modules in lib/compiler/, the compiler compiles
Shae code from source text into multiple deployment targets without needing the Rust
source compiler:
-
lexer.shae•parser.shae•token.shae•ast.shae: Tokenization & Pratt precedence parsing -
codegen.shae•chunk.shae•opcode.shae: Bytecode compilation & binary serialization -
disasm.shae: Interactive bytecode disassembler -
linker.shae•elf.shae•pe.shae: Direct native 64-bit ELF and PE executable generation -
wasm.shae: Binary WebAssembly module generation -
llvm.shae: Direct LLVM 18 SSA intermediate representation emission -
main.shae: Unified compiler CLI driver
Two-Stage Bit-for-Bit Verified Bootstrap
Verified via tests/stage2_bootstrap_test.rs: Stage 1 compiler compiles
Stage 2 compiler source into bytecode. Stage 2 compiler then compiles itself again.
The resulting bytecode hashes match bit-for-bit, proving deterministic self-hosting
maturity.
use { tokenize } from "./lexer.shae"
use { parse } from "./parser.shae"
use { compile_file_to_shaec } from "./codegen.shae"
use { link_file } from "./linker.shae"
use { emit_wasm_file } from "./wasm.shae"
use { compile_to_llvm } from "./llvm.shae"
fn main() {
let args = args()
if args.len < 2 {
print("Shae Pure Self-Hosting Compiler Suite")
return 1
}
let cmd = args[1]
if cmd == "compile" {
return compile_file_to_shaec(args[2], args[3])
} else if cmd == "link" {
return link_file(args[2], args[3], "elf", null, "x86_64")
} else if cmd == "llvm" {
return compile_to_llvm(args[2], args[3])
}
} Dual-Engine Parity Model (Stack Bytecode VM + AST Evaluator)
Every feature, primitive, and standard library module in Shae is verified to run identically on both execution backends.
Stack Bytecode VM
Default Engine (--vm)
Precompiles AST into compact bytecode chunks (.shaec). Evaluates
instructions on a fast virtual operand stack with indexed local slots, upvalue
capture, and direct jumps.
- Startup Latency: ~3 ms cold start
- Loop Throughput: ~80,000+ ops/sec
- AOT Ready: Direct bytecode serialization
- JIT Integration: Seamless Cranelift tiering
Tree-Walking AST Evaluator
Instant Scripting (--ast)
Traverses the Abstract Syntax Tree directly without bytecode compilation passes. Ideal for rapid one-off scripting, macro transformations, and developer debugging.
- Compilation Delay: 0 ms (Zero compile phase)
- Debug Introspection: Exact source AST spans
- Memory Footprint: Low overhead for single runs
- Engine Parity: 320+ tests pass identically
Evolution Chunks 1–34 Interactive Matrix
Explore all 34 milestones that built the Shae language, from ergonomic primitives to LLVM SSA and distributed actor clustering.
Chunk 1 Language Ergonomics & Core Primitives Core Foundation ↓
Foundational data types, 64-bit integer and floating-point math, radix literals, destructuring, and pattern matching.
- Distinct Value::Int(i64) and Value::Float(f64) primitives
- Radix literals: Hex (0xFF), Binary (0b1010), Octal (0o755), and numeric underscores (1_000_000)
- Bitwise operators: &, |, ^, ~, <<, >>
- Array & struct destructuring: let [a, b, ..rest], let { name, ..extra }
- Pattern matching with arm guards (case p if cond => ...) and ranges (0..10, 1..=10)
- Comprehensive array & string method suites (find, some, flat, pad_start, lines)
// Pattern matching with guards and range conditions
fn classify(val) {
match val {
0 => "zero",
1..=9 => "single digit",
10..=99 if val % 2 == 0 => "even double digit: {val}",
10..=99 => "odd double digit: {val}",
_ => "large number"
}
} Chunk 2 Code Formatter & Linter Polish Core Foundation ↓
Canonical AST-driven source code formatter and static analysis engine detecting dead code, shadowing, and unused variables.
- AST canonical formatter (shae fmt, shae fmt --check) with standard 4-space indentation
- Static linter (shae check) detecting unused variables/parameters with _ prefix suppression
- Dead code detection following unconditional return / throw statements
- Variable shadowing warnings and unreachable pattern match arms
shae fmt --check src/
shae check main.shae Chunk 3 Bytecode VM Foundation — Control Flow Core Foundation ↓
High-throughput stack-based bytecode virtual machine with compile-time local slot resolution and structured jumps.
- Compile-time local variable slot allocation (OpGetLocal, OpSetLocal)
- Jump instructions: OpJump, OpJumpIfFalse, OpLoop
- Low-overhead execution loops for while, for..in, and if/else branching
- Constant pool indexing for strings, numbers, and boolean literals
Chunk 4 Bytecode VM — Call Frames & Closures Core Foundation ↓
Virtual stack CallFrame architecture with lexical upvalue capturing for first-class closures and nested functions.
- Stack-based CallFrame architecture with max recursion depth protection
- Lexical closure upvalue capturing: OpGetUpvalue, OpSetUpvalue, OpCloseUpvalue
- First-class function values and closures passed as parameters
- OpAllocArray and OpAllocMap for fast composite data construction
Chunk 5 Memory Efficiency & Garbage Collection Core Foundation ↓
Mark-and-sweep garbage collector with stack root tracing, eliminating heavy Arc/RwLock overhead for primitive values.
- Mark-and-sweep GC engine with virtual stack and call frame root tracing
- Automatic cyclic reference collection for nested closures and structures
- Elimination of reference counting overhead for hot numeric and string loops
- Configurable GC thresholds and explicit gc_collect() triggers
Chunk 6 Structured Module System Core Foundation ↓
Relative path module resolution with selective symbol imports and standard library system namespaces.
- Relative module imports: use { a, b } from "./module.shae"
- Circular dependency detection with clear diagnostic traces
- Core standard modules: std:fs (file I/O), std:path (path manipulation)
- System interfaces: std:sys (arguments, exit, platform) and std:time (high-res clocks)
use { read, write, exists } from "std:fs"
use { platform, args } from "std:sys"
if exists("config.json") {
let raw = read("config.json")
print("Loaded config on {platform()}: {raw.len} bytes")
} Chunk 7 Concurrency & Async I/O Core Foundation ↓
Message-passing channels and built-in multi-threaded HTTP and TLS web server runtimes.
- Channel-based message passing: channel(capacity), send(), recv()
- Multi-threaded non-blocking HTTP web server: serve(port, handler)
- High-security TLS server runtime: serve_tls(port, cert, key, handler) via Rustls
- JSON serialization built-in: json(obj) and parse_json(str)
Chunk 8 Expanded Standard Library Core Foundation ↓
Cryptographic hash functions, PCRE regular expressions, and standard binary/URL encoding utilities.
- std:crypto: SHA-256, SHA-512, HMAC-SHA256, secure CSPRNG random bytes
- std:regex: PCRE regular expression matching, searching, and capture groups
- std:codec: Base64 encoding/decoding and URL percent-encoding
Chunk 9 Package Manager & Project System Core Foundation ↓
Integrated CLI package manager with deterministic dependency resolution and project manifests.
- CLI package commands: shae pkg init, shae pkg add, shae pkg install
- Declarative shae.toml project manifest and metadata specification
- Deterministic dependency resolution locked via shae.lock
- Semantic versioning (SemVer) dependency graph validation
shae pkg init my-project
shae pkg add @shae/sqlite
shae pkg install Chunk 10 LSP Daemon & Standalone Bundler Core Foundation ↓
Language Server Protocol daemon for editor integration and single-binary application distribution.
- Language Server Protocol daemon (shae lsp) with JSON-RPC standard wire
- Real-time syntax diagnostics, document symbols, and autocompletion
- Single-binary application bundler (shae bundle app.shae -o app)
- Self-contained executable distribution with zero runtime dependencies
Chunk 11 Bytecode Compilation & Serialization Tooling & Pure-Shae Frontend ↓
Ahead-of-time bytecode compilation into binary .shaec containers with disassembler inspection.
- AOT bytecode compilation: shae compile <file.shae> -o <out.shaec>
- Compact binary bytecode container with magic header \x7fSHAE
- Interactive bytecode disassembler: shae disasm <file.shaec>
- Transparent direct loading of precompiled .shaec files via standard use
shae compile server.shae -o server.shaec
shae disasm server.shaec Chunk 12 VM-Backed Interactive REPL Tooling & Pure-Shae Frontend ↓
Persistent VM evaluation loop maintaining global variables across interactive lines with meta-commands.
- Interactive VM session preserving global bindings across input prompts
- Multiline balance checker for nested blocks, braces, and arrays
- Meta commands: :help, :disasm, :globals, :reset, :engine [vm|ast]
- Syntax highlighted token feedback and runtime error caret markers
Chunk 13 Standalone Bundler Bytecode Integration Tooling & Pure-Shae Frontend ↓
Bundling precompiled bytecode into standalone executables with zero startup parse overhead.
- Direct embedding of precompiled bytecode chunks into the standalone binary stub
- Instant startup time (sub-3ms) with zero source parsing or AST allocation
- --strip flag for stripping debug symbols and source protection
- Cross-platform binary output for Linux and macOS
Chunk 14 Actor Concurrency & Supervision Trees Tooling & Pure-Shae Frontend ↓
Lightweight OS-thread actors with unbounded FIFO mailboxes, request-response messaging, and supervision trees.
- Stateful actor processes backed by OS threads and Condvar zero-idle CPU parking
- Unbounded FIFO mailboxes with synchronous request-response: ask(msg, [timeout])
- Global actor registry: actor.register("name", handle) and actor.whereis("name")
- Supervision strategies: OneForOne and AllForOne with sliding restart limits
let actor = use "std:actor"
let counter = actor.spawn(0, fn(state, msg) {
if msg["op"] == "inc" {
let next_val = state + msg["by"]
return { "state": next_val, "reply": next_val }
}
return state
})
let val = counter.ask({ "op": "inc", "by": 5 })
print("Counter incremented: {val}") Chunk 15 Pure-Shae Frontend & Self-Parsing Tooling & Pure-Shae Frontend ↓
Complete lexical analyzer and Pratt recursive-descent parser written entirely in pure Shae.
- Lexer tokenizing all Shae primitives, operators, and raw string literals in pure Shae
- Recursive-descent Pratt parser handling operator precedence and expression trees
- Complete AST node structure generation without Rust intermediaries
- Self-parsing verified via tests/shae/self_parser_test.shae
Chunk 16 Pure-Shae Bytecode Compiler Tooling & Pure-Shae Frontend ↓
Pure-Shae bytecode code generator emitting .shaec bytecode chunks, constant pools, and upvalue descriptors.
- Pure-Shae AST traversal and bytecode instruction generation
- Constant pool deduplication and back-patching for forward jumps
- Upvalue descriptor emission for nested closures and lexical environments
- Direct binary writing to .shaec format conforming to VM specification
Chunk 17 Direct Native Linker (ELF & PE) Tooling & Pure-Shae Frontend ↓
Pure-Shae native object linker producing 64-bit ELF and PE/COFF binaries with zero external C toolchain dependencies.
- Stand-alone 64-bit ELF executable emitter for Linux x86_64
- Portable Executable (PE/COFF) binary emitter for Windows x86_64
- Zero dependency on gcc, clang, ld, or lld toolchains (shae link)
- Direct program header, section table, and entry point layout construction
Chunk 18 WebAssembly & Edge Runtime Target Tooling & Pure-Shae Frontend ↓
Pure-Shae WebAssembly binary emitter and built-in zero-dependency WasmRunner execution runtime.
- Pure-Shae WebAssembly binary emitter generating valid .wasm modules
- Type section, function section, export section, and code section serialization
- In-process zero-dependency WasmRunner interpreter (shae wasm <file> --run)
- Ready for edge deployment in Cloudflare Workers and Fastly Compute
Chunk 19 Distributed Actor Mesh (`std:actor:cluster`) Tooling & Pure-Shae Frontend ↓
Distributed actor clustering over length-delimited TCP with secret cookie handshakes and remote messaging.
- TCP framed wire protocol with 64MB frame overflow protection
- Cluster authentication handshake via shared secret cookie verification
- Remote actor handle abstraction: actor@node with transparent ask/send routing
- Dynamic cluster node discovery, round-robin pools, and bully leader election
Chunk 20 Self-Hosting Bootstrap Pipeline Tooling & Pure-Shae Frontend ↓
Unified pure-Shae compiler driver CLI coordinating lexing, parsing, bytecode, native linking, and WASM generation.
- Central compiler driver entry point written in pure Shae
- Unified interface for --compile, --disasm, --link, --wasm, and --llvm
- Full command-line argument parser and pipeline coordinator
- Self-compiles into standalone compiler binaries
Chunk 21 Cluster Transport Security: TLS & mTLS Enterprise & Native SSA ↓
Mutual TLS (mTLS) wire transport for distributed actor clusters using Rustls 0.23 with root CA peer verification.
- Rustls 0.23 wire encryption with ring cryptography provider
- Mutual TLS (mTLS) client and server certificate verification via root CA
- Rogue peer connection rejection and tamper-proof wire messaging
- Runtime reflection inspection method: node.is_tls()
let cluster = use "std:actor:cluster"
let secure_node = cluster.node("vault_alpha", "0.0.0.0:9443", {
"cookie": "cluster_secret_token",
"tls": {
"cert_path": "/etc/shae/tls/node.crt",
"key_path": "/etc/shae/tls/node.key",
"ca_path": "/etc/shae/tls/ca.crt"
}
})
print("Secure mTLS Cluster Node online: {secure_node.is_tls()}") Chunk 22 First-Class `async` / `await` Coroutines Enterprise & Native SSA ↓
Thread-safe coroutine tasks with idempotent awaiting and standard combinators (spawn, all, race, timeout).
- Thread-safe TaskInner coroutine primitive with idempotent await resolution
- Coroutine combinators: async.spawn, async.all, async.race, async.sleep
- Safe execution timeouts with async.timeout(task, ms)
- Zero thread blocking for timer-based delays
let async = use "std:async"
let task1 = async.spawn(fn() {
async.sleep(50)
return "alpha"
})
let task2 = async.spawn(fn() {
async.sleep(30)
return "beta"
})
let results = await async.all([task1, task2])
print("Async tasks resolved: {results}") // ["alpha", "beta"] Chunk 23 Standard Documentation Engine Enterprise & Native SSA ↓
Static HTML documentation generator parsing item (///) and module-level (!//) doc comments.
- Extraction of doc comments: /// for functions/types and //! for modules
- Generation of static searchable HTML documentation sites (shae doc)
- Markdown export and JSON AST API data model generation
- Cross-linking of standard library and user modules
shae doc src/ -o docs/
shae doc --json > api.json Chunk 24 Package Registry & Publishing Enterprise & Native SSA ↓
Gzip tarball package archive format (.shaepkg) with cryptographic SHA-256 integrity checksums.
- Standard package packaging: shae pkg pack creates .shaepkg tarballs
- Cryptographic SHA-256 integrity checksum generation and verification
- Registry publishing pipeline: shae pkg publish and shae pkg verify
- Zero external archive utilities required
shae pkg pack
shae pkg verify my-package-0.1.0.shaepkg Chunk 25 Pure-Shae Test Runner & Live Doc Server Enterprise & Native SSA ↓
Integrated unit test runner with pattern filtering, assertions, and live HTTP documentation server.
- Built-in test runner: shae test [dir] with regex filtering (-f, --filter)
- Rich assertion suite: assert_eq, assert_ne, assert_throws
- Dual-engine verification (tests execute identically on VM and AST)
- Live HTTP documentation server with instant hot-reload (shae doc --serve --port 8080)
shae test tests/ -f "buffer"
shae doc --serve --port 8080 Chunk 26 Authenticated Symmetric Cryptography Enterprise & Native SSA ↓
Industrial-grade AEAD authenticated ciphers and standard cryptographic key derivation functions.
- AES-256-GCM authenticated encryption and decryption with 128-bit authentication tags
- ChaCha20-Poly1305 high-performance AEAD cipher
- HKDF-SHA256 (HMAC-based Extract-and-Expand Key Derivation Function)
- PBKDF2-HMAC-SHA256 password hashing with configurable iterations
Chunk 27 Stage 2 Self-Hosting Two-Stage Bootstrap Enterprise & Native SSA ↓
Bit-for-bit identical two-stage compiler bootstrap verification across both Bytecode VM and AST Evaluator.
- Stage 1 compiler compiles Stage 2 compiler source into bytecode
- Stage 2 compiler compiles itself again, achieving bit-for-bit identical bytecode hashes
- Full language self-hosting verification executed in automated CI test harness
- Dual-engine parity verified during every stage of compilation
Chunk 28 Direct LLVM SSA Code Generation (`shae llvm`) Enterprise & Native SSA ↓
Direct emission of compliant LLVM 18 SSA IR with entry block allocas, mem2reg promotion, and Clang -O2 native compilation.
- Direct LLVM 18 IR SSA code generation without third-party LLVM C library bindings
- Canonical entry block alloca allocation promoted to hardware registers via mem2reg
- External C runtime interop bindings (printf, puts, malloc, free, exit)
- Clang -O2 integration producing optimized standalone native executables (shae llvm -c)
shae llvm app.shae -o app.ll
shae llvm -c app.shae -o app
shae llvm -r app.shae Chunk 29 Zero-Copy Typed Memory Buffers (`std:buffer`) Enterprise & Native SSA ↓
Arc/RwLock-backed ByteBuffer container with zero-copy slicing, endian binary I/O, and struct pack/unpack engine.
- ByteBuffer container sharing Arc<RwLock<Vec<u8>>> with offset and length pointers
- Sub-slice creation buf.slice(start, end) with zero heap memory allocation
- Bidirectional in-place mutation reflection between slices and parent buffers
- Endian-aware numeric reads/writes (u8..u64, i8..i64, f32, f64 in Little/Big-Endian)
- Struct layout packing engine: pack("<I2h4s", ...), unpack, pack_into, and calcsize
use { alloc, pack, unpack, calcsize } from "std:buffer"
// Allocate 24-byte buffer and slice [8..16) with zero allocations
let parent = alloc(24)
let child = parent.slice(8, 16)
child[0] = 255
print("Parent at byte 8 reflects child slice mutation: {parent[8]}") // 255
// High-speed binary struct packing
let packed = pack("<I2h4s", 4000000000, -800, 1600, "SHAE")
let fields = unpack("<I2h4s", packed)
print("Unpacked struct fields: u32={fields[0]}, tag={fields[3]}") Chunk 30 Hot-Code Reloading for Actors & Clusters Enterprise & Native SSA ↓
Zero-downtime actor handler swapping with continuous state preservation, schema migrations, and remote cluster reload.
- ActorMessage::Reload hot-swaps active handler while preserving daemon state and FIFO mailboxes
- Zero dropped messages or severed client connections during code reloading
- State schema migration via migration_fn(&mut state) transforming in-memory models
- Distributed cluster hot-reload over TCP/TLS mesh via ClusterWireMsg::Reload
let actor = use "std:actor"
let daemon = actor.spawn({ "balance": 1000 }, fn(st, msg) {
if msg["op"] == "deposit" {
return { "state": { "balance": st["balance"] + msg["val"] }, "reply": "v1 ok" }
}
return st
})
// Swap logic to V2 with 10% bonus without dropping messages or restarting thread
let v2_handler = fn(st, msg) {
if msg["op"] == "deposit" {
let bonus = msg["val"] / 10
return { "state": { "balance": st["balance"] + msg["val"] + bonus }, "reply": "v2 bonus added" }
}
return st
}
daemon.reload(v2_handler)
print("Daemon successfully hot-reloaded to V2 with continuous state.") Chunk 31 Benchmark Suite & Showcase (`shae bench`) Enterprise & Native SSA ↓
Automated telemetry benchmark runner reporting iterations, latency, and ops/sec throughput across real workloads.
- CLI benchmark command: shae bench [filter] with ASCII formatted telemetry tables
- Real workloads: Fibonacci (recursive/iterative), ByteBuffer allocation, Actor throughput, collections
- Reporting iterations, total duration, mean latency (µs), and throughput (ops/sec)
- Showcase demo programs in examples/ verifying end-to-end language features
shae bench
shae bench -f "buffer" -i 500 Chunk 32 Gradual Typing & Static Type Checker (`shae check`) Core Foundation ↓
Opt-in gradual static type system supporting type annotations on functions, variables, and return bounds, with nullable union types and compile-time diagnostics.
- Syntax type annotations: fn name(arg: type) -> ret_type and let var: type = val
- Primitive and compound types: int, float, string, bool, list, map, any, null
- Nullable union types: int | null, string | float | any with pipe syntax
- Static analyzer (shae check) validating return type consistency, argument counts, and assignment types
- Full backward compatibility: dynamically typed untyped code remains first-class
- Editor integration via Language Server Protocol (LSP) diagnostics and squiggles
// Gradual static type annotations with nullable union types
fn fetch_record(id: int, fallback: string | null) -> string | null {
if id <= 0 {
return fallback
}
return "record_#" + id
}
let name: string | null = fetch_record(42, null)
print("Fetched: {name}")
// Static checker detects mismatches at compile time:
// $ shae check api.shae
// [OK] Type checking passed with 0 errors shae check src/main.shae Chunk 33 Remote Package Registry & Manager Subsystem (`shae pkg`) Developer Tooling ↓
Production package manager with remote registry HTTP synchronization, .shaepkg archive distribution, SHA-256 integrity verification, and lockfile resolution.
- Subcommands: shae pkg init, shae pkg add <pkg>@<ver>, shae pkg install, shae pkg pack, shae pkg publish, shae pkg verify
- Remote package index resolution over HTTP/HTTPS with automatic tarball download
- Shaepkg archive format (.shaepkg) with gzip compression and embedded metadata manifest
- Cryptographic integrity: SHA-256 checksum verification and zip-slip path traversal attack prevention
- Deterministic dependency resolution with shae.toml and shae.lock synchronization
shae pkg init my_crate
shae pkg add calc@2.0.0 --registry https://registry.shae-lang.org
shae pkg pack
shae pkg publish --registry https://registry.shae-lang.org --token $SHAE_TOKEN Chunk 34 Creative Engine & Space Invaders 2D Showcase (`std:gui`, `std:audio`, `std:ui`) Creative & Multimedia Suite ↓
Integrated multimedia engine with TrueColor ANSI / desktop windowing, real-time waveform audio synthesis, arcade UI widgets, and a complete Space Invaders 2D game.
- std:gui: Multi-mode 24-bit TrueColor ANSI half-block terminal canvas, minifb desktop windowing, sprite blitting, and keyboard polling
- std:audio: Real-time Rodio waveform audio synthesis (sine, square, triangle, sawtooth, white noise) and retro sound triggers (shoot, invader_killed, explosion, step)
- std:ui: Retro arcade HUD rendering, panel containers, score displays, health/lives icons, and immediate-mode UI widgets
- examples/space_invaders.shae: Full 2D arcade game featuring animated alien fleets, bunker degradation, player cannon, and game states
- Shae Studio Web IDE (shae ide): Browser-based graphical IDE with live code editing and preview
use { init, clear, draw_sprite, render, is_key_down } from "std:gui"
use { play_sound } from "std:audio"
use { draw_hud } from "std:ui"
let screen = init(60, 30, "Space Invaders 2D")
let player_x = 28
let score = 0
// Game loop executing at 60 frames per second
while true {
clear(screen, 0x000000)
if is_key_down("Left") { player_x = player_x - 1 }
if is_key_down("Right") { player_x = player_x + 1 }
if is_key_down("Space") { play_sound("shoot") }
draw_hud(screen, score, 3, 1)
draw_sprite(screen, player_x, 26, "player_cannon", 0x33FF33)
render(screen)
} shae run examples/space_invaders.shae
shae ide --port 8080 Explore More of the Shae Toolchain
Read the complete 42-page architectural PDF book, view real-time benchmark telemetry, or install the compiler.