Stag 0.1.0 Formal Reference — Complete language grammar, type system, memory zones, auto-parallelizer, C ABI, inline assembly, CLI flags, worked input/output specifications, diagnostics, and LSP. See also Standard Kit API Reference and C++20 Embedding API.

Stag Language Reference and Manual

This document is the technical specification and programming manual for the Stag programming language, its compiler (stagc), Language Server (stag-lsp), Standard Kit (kit.*), and C++20 embedding interface (include/stag/Stag.hpp).


Table of Contents

  1. Toolchain, Architecture, Installation, and stag-lsp
  2. Lexical Structure, Comments, and Block Styles
  3. Project Style Policy (format.json) and --fmt-experimental (Beta)
  4. Bindings, Mutability, Constants, and Statics
  5. Type System, Coercion, Pointers, Arrays, Slices, and Tuples
  6. Operators, Forward Pipe, and Formatted Strings
  7. Control Flow and Pattern Matching
  8. Functions, Named and Default Arguments, Closures, and main
  9. Records, Unions, Choices, Inline Methods, and attach
  10. Generics, Traits, Operator Overloading, and const func
  11. Ownership, Move Semantics, Drop, and defer
  12. Sealed Zone and Separation Memory Model (SZSM)
  13. Automatic Loop Parallelization (--par) and Optimization Hints
  14. Error Handling (Maybe, Outcome, ?)
  15. Modules and Visibility (use, pub)
  16. Built-in Crash-Isolated Testing (test, --test)
  17. C FFI, Calling Conventions, Inline Assembly, and Intrinsics
  18. Embedded Standard Kit (kit.*) Complete Reference
  19. Runtime Checks, Debugging, Cross-Compilation, Diagnostics, and Emission Outputs
  20. C++20 Embedding and Tooling API (stag/Stag.hpp)

1. Toolchain, Architecture, Installation, and stag-lsp

1.1 Binaries and Installers

A Stag toolchain installation provides two binaries in <prefix>/bin:

  • stagc: ahead-of-time native compiler (LLVM 20+ backend), beta formatter (--fmt-experimental), format.json policy validator, and crash-isolated test runner (--test).
  • stag-lsp: native Language Server Protocol (LSP 3.17) server communicating over stdio using Content-Length framed JSON-RPC 2.0 messages.

stagc embeds all 18 kit.* Standard Kit source modules directly inside the executable. No external runtime or standard library directory is required to compile Stag programs. Final native executable linking invokes clang or gcc found on PATH.

Both Windows (stag-setup-<version>-windows-x64.exe) and Linux (stag-setup-<version>-linux-{x64,arm64}) installers install stagc and prompt the user whether to install stag-lsp (via GUI checkbox or interactive terminal prompt, controllable non-interactively via --with-lsp / --no-lsp). The VS Code extension (stag-vscode) is maintained and distributed separately via the VS Code Marketplace.

1.2 Compiler Pipeline Architecture

diagram
flowchart TD
    SRC["UTF-8 Source Files (.stag) + Embedded kit/*.stag"] --> LEX["1. Lexer (Tokens, Indentation, Comments)"]
    LEX --> PAR["2. Parser (AST, Tri-Style Blocks)"]
    PAR --> MOD["3. ModuleLoader (Transitive 'use' Graph)"]
    PAR --> FMT["Formatter (Beta) / FormatConfig Style Policy (E5000..E5012)"]
    MOD --> SEMA["4. SemanticAnalyzer + ConstEval (Types, Generics, Traits, Moves, HIR)"]
    SEMA --> SZSM["5. MemoryAnalyzer (SZSM Escape/Borrow Proofs + Auto-Parallelizer)"]
    SZSM --> HINTS["6. HintAnalyzer (Auto Hints + Contradiction Warnings W6001..W6008)"]
    HINTS --> CG["7. LLVM CodeGen + ParRuntime (Verified LLVM IR + DWARF/CodeView)"]
    CG --> OPT["8. LLVM PassBuilder Optimizer (-O0..-O3/-Os/-Oz, TargetIRAnalysis, SIMD)"]
    OPT --> BE["9. Backend (.o / .s) + Native Linker (Executable)"]

Each intermediate representation can be inspected directly via --emit=<kind>:

--emit ValuePipeline StageOutput Format
tokensStage 1 (Lexer)Tab-separated line:col, token kind, and lexeme
astStage 2 (Parser)Indented textual AST dump
hirStage 4 (SemanticAnalyzer)Typed HIR with local IDs, types, and desugared control flow
memStage 5 (MemoryAnalyzer)Interprocedural effect summaries, parameter attributes, and loop proofs
parStage 5 (MemoryAnalyzer + --par)Per-loop parallelization decisions, cost estimates, and sequential fallback reasons
hintsStage 6 (HintAnalyzer)Manual and automatically inferred function/branch/loop optimization hints
irStage 7–8 (CodeGen + Optimizer)Verified LLVM IR text (.ll)
asmStage 9 (Backend)Target machine assembly (.s)
objStage 9 (Backend)Native relocatable object file (.o / .obj)
exe (default)Stage 9 (Backend + Linker)Native linked executable

1.3 Compiler Invocation

sh
stagc main.stag -o main                         # compile with -O0 (default)
stagc main.stag -O2 -o main                     # compile with LLVM -O2
stagc main.stag -O3 --cpu=native -o main        # target host CPU & full LLVM SIMD vectorization
stagc main.stag -O3 --cpu=native --features=+avx2,+fma -o main
stagc main.stag --emit=ir -O2 -o -              # emit LLVM IR to stdout
stagc main.stag --emit=asm -O2 -o m.s           # emit target assembly
stagc main.stag --emit=obj -O2 -o m.o           # emit object file
stagc main.stag --emit=ast -o -                 # dump parsed AST
stagc main.stag --emit=hir -o -                 # dump typed HIR
stagc main.stag --emit=mem -o -                 # dump SZSM memory certificates
stagc main.stag --emit=par --par=auto -o -      # dump loop parallelization proofs
stagc main.stag --emit=hints -o -               # dump manual and auto-inferred optimization hints
stagc main.stag --emit=tokens -o -              # dump lexer token stream
stagc main.stag --Werror --verify-only          # treat all warnings as errors and verify IR only
stagc --test main.stag                          # build and run all `test "..."` blocks with crash isolation

Complete CLI flag summary:

FlagArguments / DefaultDescription
-o <path>- for stdout on text emitsOutput file path.
-I <dir>repeatableAdd directory to use module search path.
--kit-path <dir>embedded kit by defaultOverride the embedded Standard Kit (kit.*) directory on disk.
--no-kitoffDisable the embedded Standard Kit (freestanding compilation).
-L <dir> / -l <lib>repeatableForward linker search paths and libraries to the native linker.
--emit=<kind>exeSelect output stage (exe, obj, asm, ir, ast, hir, mem, par, hints, tokens).
-O<level>-O0LLVM optimization pipeline: 0, 1, 2, 3, s, z.
`--cpu=<name\native>`host genericTarget CPU model for codegen and SIMD vectorization (alias -mcpu=).
--features=<list>emptyComma-separated LLVM CPU feature flags, e.g. +avx2,+fma (alias --mattr=).
--par[=<mode>]offAuto-parallelizer mode: off, auto, force, autotune.
`--threads=<N\auto>`autoWorker thread count (1..64) for --par (alias -j).
--WerroroffPromote all warnings (W2xxx, W6xxx) to hard errors (alias --warnings-as-errors).
-goffEmit DWARF v4 (ELF/Mach-O/MinGW) or CodeView (MSVC) debug info.
--uncheckedoffDisable runtime bounds, division, and integer overflow traps (unless forbidden by format.json).
--target=<triple>host tripleCross-compilation LLVM target triple.
--verify-onlyoffRun frontend, analyzers, and LLVM IR verifier without writing output artifacts.
--testoffCompile and execute test "..." blocks in crash-isolated subprocesses.
--filter <substr>emptyWith --test, run only tests whose name contains <substr>.
--listoffWith --test, print discovered test names without executing them.
--fail-fastoffWith --test, stop on the first failing test.
--fmt-experimentaloff[beta] Format .stag files (-i/--in-place, --check, -o).
--format-config <path>auto-discoveredApply format.json style policy during compilation or formatting.
--dump-iroffPrint LLVM IR to stdout in addition to emitting the requested output.
--no-coloroffDisable ANSI escape sequences in diagnostics.
--version / -h, --help—Print version string or usage help.

1.4 Language Server (stag-lsp) and VS Code

stag-lsp links directly against stag_lib (Lexer, Parser, ModuleLoader, SemanticAnalyzer, MemoryAnalyzer, HintAnalyzer, FormatConfig, and Formatter).

diagram
sequenceDiagram
    participant IDE as VS Code (stag-vscode)
    participant LSP as stag-lsp (stdio JSON-RPC 2.0)
    participant FE as stag_lib Frontend + Analyzers
    IDE->>LSP: initialize (rootUri, capabilities)
    LSP-->>IDE: serverInfo (stag-lsp) + capabilities
    IDE->>LSP: textDocument/didOpen / didChange
    LSP->>FE: Lex -> Parse -> ModuleLoader -> Sema -> SZSM -> Hints -> FormatConfig
    FE-->>LSP: AnalysisSnapshot (cached last-good HIR + live diagnostics)
    LSP-->>IDE: textDocument/publishDiagnostics
    IDE->>LSP: textDocument/completion (triggers: '.', '@', '(')
    LSP-->>IDE: CompletionList (kit modules, fields, methods, locals, hints)
    IDE->>LSP: textDocument/hover / definition / signatureHelp / formatting
    LSP-->>IDE: Markdown hover / Location (incl. materialized kit/*.stag) / TextEdits

Capabilities:

  • Live Diagnostics (textDocument/publishDiagnostics): runs on open, change, and save across syntax, type checking, move checking, SZSM escape/borrow analysis, optimization hint checks (W6001..W6008), and sibling format.json rules.
  • Autocomplete (textDocument/completion, triggers ., @, and ():
  • @: completes optimization hints (@inline, @noinline, @hot, @cold, @pure, @likely, @unlikely, @vectorize, @novectorize, @unroll, @nounroll, @parallel, @noparallel, @hint).
  • use / use kit.: completes all 18 embedded Standard Kit modules (alloc, args, check, hash, io, json, list, math, maybe, mem, outcome, path, rand, scribe, sys, table, text, time).
  • use kit.json (: completes exported pub symbols of the module.
  • <module>.: completes exported functions, records, choices, traits, constants, and statics with full Stag signatures (e.g. Outcome[Text, i32]).
  • <Type>.: completes choice variants and static/associated methods (including generic types such as List[i64].).
  • <expr>.: resolves the receiver's inferred HIR type (preserving the last valid type-checked snapshot while editing an incomplete line), auto-unwraps *T / *mut T, and completes record fields, attached/trait methods, slice/string .len/.ptr, zone methods, and tuple indices .0, .1, ...
  • General scope: in-scope locals and parameters with inferred types, module declarations, selective imports, keywords, primitive types, and intrinsics.
  • Hover (textDocument/hover): displays inferred types for locals, parameters, expressions, fields, and constants; full signatures for functions and methods; full field/variant layouts for records, choices, and traits; and documentation for primitive types and intrinsics.
  • Go-to-Definition (textDocument/definition): jumps to local bindings, parameters, functions, methods, records, choices, traits, fields, variants, constants, statics, and use targets. Embedded kit/*.stag modules are materialized into a versioned temporary directory (<temp>/stag-lsp-kit-<version>/kit/...) so Go-to-Definition opens Standard Kit sources directly in the editor.
  • Signature Help (textDocument/signatureHelp, triggers ( and ,): shows active parameter position inside function and method calls.
  • Document Symbols (textDocument/documentSymbol): hierarchical outline of declarations, fields, variants, methods, and test blocks.
  • Formatting (textDocument/formatting): runs the built-in Stag formatter (beta; CLI flag stagc --fmt-experimental) respecting any discovered format.json.

Binary discovery order in stag-vscode:

  1. Explicit stag.lsp.path setting (if non-empty and exists).
  2. stag-lsp / stag-lsp.exe on PATH.
  3. Standard install locations: - Windows: %LOCALAPPDATA%\Stag\bin\stag-lsp.exe, %ProgramFiles%\Stag\bin\stag-lsp.exe, %USERPROFILE%\.stag\bin\stag-lsp.exe - Linux / macOS: ~/.local/bin/stag-lsp, ~/.stag/bin/stag-lsp, /usr/local/bin/stag-lsp, /usr/bin/stag-lsp

VS Code settings exposed by stag-vscode:

SettingDefaultDescription
stag.lsp.enabledtrueEnable or disable stag-lsp.
stag.lsp.path""Explicit path to stag-lsp executable; auto-detected when empty.

Command palette entry: Stag: Restart Language Server (stag.restartLsp).


2. Lexical Structure, Comments, and Block Styles

2.1 Encoding and Whitespace

  • Source files must be valid UTF-8 (an optional leading UTF-8 BOM is accepted).
  • Non-ASCII bytes are valid inside string literals and comments, and rejected in identifiers/operators (E0001, E0010).
  • Mixing tabs and spaces for indentation within the same file is a lexical error (E1008).
  • Unindenting to a column that does not match an enclosing indentation level is an error (E1009).
  • A trailing backslash \ immediately followed by a newline performs explicit line continuation.
  • Inside parentheses (...) and brackets [...], newlines and indentation changes are ignored so multi-line expressions and parameter lists can wrap freely.

2.2 Comments

  • Line comments: // ... until end of line.
  • Nestable block comments: /* ... /* nested */ ... */. Unterminated block comments emit E0002.

2.3 Literals

  • Integers: decimal (42, 1_000_000), hexadecimal (0xFF, 0x10_u64), binary (0b1010_0101), octal (0o755). Optional type suffix: i8, i16, i32, i64, u8, u16, u32, u64. Un-suffixed integer literals default to i64 unless constrained by context.
  • Floats: 3.14, 1e-9, 2.5E+4, optional suffix f32 or f64 (default f64).
  • Booleans: true, false.
  • Null pointer: null.
  • Strings: "..." supporting \n, \r, \t, \\, \", \', \0, and \xHH. Type is str.
  • Formatted strings: f"..." (see Section 6.3).

2.4 Reserved Keywords

func, extern, use, pub, attach, trait, for, in, self, defer, record, union, choice, const, static, var, mut, if, elif, then, else, match, case, loop, while, do, zone, pass, break, continue, return, as, asm, sizeof, alignof, true, false, null, i8, i16, i32, i64, u8, u16, u32, u64, f32, f64, bool, unit, never, str.

end, test, packed, and type are contextual and may still be used as normal variable or field identifiers where unambiguous.

2.5 Tri-Style Block Syntax and Optional Semicolons

Stag defaults to off-side indentation blocks introduced by :, and also supports { ... } brace blocks and optional contextual end terminators. Semicolons ; are optional statement terminators (and may be used to separate multiple statements on a single line).

All three block styles compile to the exact same HIR and LLVM IR:

stag
// 1. Default indentation style
func clamp_indent(x: i64, hi: i64) -> i64:
    if x < 0:
        return 0
    elif x > hi:
        return hi
    x

// 2. Brace style
func clamp_braces(x: i64, hi: i64) -> i64 {
    if x < 0 {
        return 0;
    } elif x > hi {
        return hi;
    }
    x
}

// 3. Explicit `end` style
func clamp_end(x: i64, hi: i64) -> i64:
    if x < 0:
        return 0
    elif x > hi:
        return hi
    end
    x
end

Indented : blocks and match: expressions may also be nested cleanly inside { ... } brace blocks. Empty blocks use pass in indentation mode (or {} in brace mode).


3. Project Style Policy (format.json) and --fmt-experimental (Beta)

Stag includes a built-in canonical formatter (stagc --fmt) and an 18-rule style enforcement engine driven by format.json.

3.1 Discovery and Activation

  1. Explicit flag: stagc --format-config path/to/format.json ... or stagc --fmt --format-config path/to/format.json ....
  2. Automatic discovery: when compiling or formatting <dir>/file.stag without --format-config, stagc and stag-lsp automatically look for a sibling <dir>/format.json. If found and "enforce": true, violations fail compilation (E5001..E5012).

3.2 Complete format.json Schema (All 18 Keys)

All keys are optional; unspecified keys take their default values. Unknown keys or invalid values emit an error (E5000).

KeyTypeAllowed ValuesDefaultEnforcement & Formatter Behavior
block_stylestring"any", "indent", "braces", "end""any"E5001: requires all blocks to match the chosen style. --fmt automatically converts between indent, braces, and end with zero semantic change.
semicolonsstring"optional", "required", "forbidden""optional"E5002: enforces presence or absence of trailing ; on statements. --fmt inserts or strips ; accordingly.
indent_stylestring"spaces", "tabs""spaces"E5003: checks leading indentation characters. --fmt outputs spaces or tabs.
indent_widthint1..164E5003: checks indentation width per level (when indent_style is "spaces"). --fmt uses this width.
max_line_lengthint>= 0 (0 = unlimited)0E5004: rejects lines exceeding this column count.
max_fn_statementsint>= 0 (0 = unlimited)0E5005: rejects functions exceeding this statement count.
max_fn_paramsint>= 0 (0 = unlimited)0E5006: rejects functions with more than this many parameters.
max_nesting_depthint>= 0 (0 = unlimited)0E5007: rejects control-flow nesting deeper than this limit.
max_file_linesint>= 0 (0 = unlimited)0E5008: rejects files with more than this many lines.
require_return_typebooltrue, falsefalseE5009: requires explicit -> Type on all function declarations (including -> unit).
no_trailing_whitespacebooltrue, falsefalseE5010: rejects trailing spaces or tabs at end of lines.
require_final_newlinebooltrue, falsefalseE5010: requires non-empty files to end with \n.
naming_functionsstring"any", "snake_case", "camelCase", "PascalCase", "UPPER_SNAKE""any"E5011: checks function and method names (extern functions are exempted so C symbol names remain valid).
naming_typesstring"any", "snake_case", "camelCase", "PascalCase", "UPPER_SNAKE""any"E5011: checks record, union, choice, and trait names.
naming_constantsstring"any", "snake_case", "camelCase", "PascalCase", "UPPER_SNAKE""any"E5011: checks const and static names.
disallow_uncheckedbooltrue, falsefalseE5012: forbids compiling with --unchecked.
forbid_unused_warningsbooltrue, falsefalseE5012: promotes all compiler warnings (W2001..W2003, etc.) to errors.
enforcebooltrue, falsetrueWhen false, format.json still guides --fmt formatting without failing compilation on violations.

3.3 Example format.json

json
{
  "block_style": "indent",
  "semicolons": "forbidden",
  "indent_style": "spaces",
  "indent_width": 4,
  "max_line_length": 120,
  "max_fn_statements": 80,
  "max_fn_params": 8,
  "max_nesting_depth": 6,
  "max_file_lines": 1500,
  "require_return_type": false,
  "no_trailing_whitespace": true,
  "require_final_newline": true,
  "naming_functions": "snake_case",
  "naming_types": "PascalCase",
  "naming_constants": "UPPER_SNAKE",
  "disallow_unchecked": true,
  "forbid_unused_warnings": false,
  "enforce": true
}

3.4 Formatter CLI Usage (Beta)

The built-in formatter is currently marked beta and is enabled via --fmt-experimental (passing --fmt alone exits with status 2 and prints a beta notice). Before emitting formatted output, formatSource runs an internal re-parse safety verification (E1999) so parse-clean inputs are never corrupted.

sh
stagc --fmt-experimental file.stag                             # print formatted output to stdout
stagc --fmt-experimental -i file1.stag file2.stag              # format files in place
stagc --fmt-experimental --check file.stag                     # exit non-zero if formatting differs
stagc --fmt-experimental --format-config format.json -i a.stag # reformat to match policy (e.g. indent <-> braces)

Input / Output example (block_style: "indent", semicolons: "optional"):

Input:

stag
func  add( a:i64,b:i64 ) -> i64 {
    var  res:i64 = a+b;
    return res;
}

Output (stagc --fmt-experimental -o - input.stag):

stag
func add(a: i64, b: i64) -> i64:
    var res: i64 = a + b
    return res

4. Bindings, Mutability, Constants, and Statics

4.1 Local Bindings

  • Immutable binding (:=): ``stag x := 42 // inferred i64 y: u32 := 10u32 // explicit type annotation ``
  • Mutable binding (var): ``stag var count = 0 var total: f64 = 0.0 count += 1 ``
  • Unused immutable variables trigger W2001; mutable var bindings that are never mutated trigger W2003. Prefixing a name with _ (e.g. _tmp := ...) or discarding via _ := expr suppresses unused warnings.
  • Local variables may shadow outer bindings in inner scopes.

4.2 Compile-Time Constants (const)

stag
pub const MAX_BUFFER: i64 = 4096
const MASK: u64 = (1u64 << 16u64) - 1u64

const declarations require an explicit type and an initializer evaluable at compile time (including calls to const func). They are inlined as compile-time constants and have no runtime storage address.

4.3 Module Globals (static and static var)

stag
static VERSION_MAJOR: i32 = 0i32     // immutable, placed in .rodata
static var REQUEST_COUNT: i64 = 0    // mutable, placed in .data

static initializers must be compile-time constant expressions. Mutable static var globals are reset per test subprocess under stagc --test.


5. Type System, Coercion, Pointers, Arrays, Slices, and Tuples

5.1 Primitive Types

TypeWidth / Representation
i8, i16, i32, i64Two's-complement signed integers (8, 16, 32, 64 bits).
u8, u16, u32, u64Unsigned integers (8, 16, 32, 64 bits).
f32, f64IEEE-754 single and double precision floating point.
bool1-byte boolean (true / false).
unitZero-sized empty type ().
neverBottom type for diverging expressions (return, break, continue, trap()). Coerces to any expected type.
strFat pointer { ptr: *u8, len: i64 } referencing immutable UTF-8 bytes.

5.2 Lossless Widening Coercion vs Explicit Casts (as)

Stag performs implicit numeric widening only when the conversion is mathematically injective (lossless across the entire source domain):

  • Signed widening: i8 -> i16 -> i32 -> i64
  • Unsigned widening: u8 -> u16 -> u32 -> u64
  • Unsigned to wider signed: u8 -> i16 | i32 | i64, u16 -> i32 | i64, u32 -> i64
  • Float widening: f32 -> f64

Narrowing (i64 -> i32), sign changes (i64 -> u64), and integer/float conversions (i64 -> f64, f64 -> i64) are never implicit and require an explicit as cast:

stag
a: i8 := 10i8
b: i64 := a          // valid lossless widening
c: i32 := b as i32   // explicit narrowing cast
d: f64 := b as f64   // explicit int-to-float cast

5.3 Pointers (*T, *mut T)

  • Immutable pointer: *T, created with &place.
  • Mutable pointer: *mut T, created with &mut place (requires a mutable binding or mutable dereference).
  • Dereference: *ptr (reading or writing *ptr = val for *mut T).
  • Automatic dereference on field access and method calls: p.field and p.method() work directly on *T and *mut T.
  • Safe implicit mutability downgrade: *mut T coerces automatically to *T, and []mut T coerces automatically to []T.
  • Null pointer: null as *T or null as *mut T. Comparing p == null / p != null is supported directly.

5.4 Fixed-Size Arrays ([N]T) and Slices ([]T, []mut T)

stag
var arr: [4]i64 = [1, 2, 3, 4]
zeros := [0u8; 64]           // repeat syntax: 64 bytes of 0u8
s: []i64 := arr[1..3]        // half-open slice [1, 3) -> elements 2, 3
si: []i64 := arr[1..=3]      // inclusive slice [1, 3] -> elements 2, 3, 4
all: []mut i64 := arr[..]    // full mutable slice
n := s.len                   // i64 element count
p := s.ptr                   // *i64 data pointer

Indexing arr[i] and slicing arr[lo..hi] perform runtime bounds checks unless --unchecked is passed.

5.5 Anonymous Tuples and Recursive Destructuring

stag
func divmod(a: i64, b: i64) -> (i64, i64):
    (a / b, a % b)

func demo():
    pair := divmod(17, 5)
    q := pair.0
    r := pair.1

    // Destructuring with nested tuples, mutability, and wildcards
    nested := (10, (20, 30))
    (var a, (_, b)) := nested
    a += b

Tuple elements are tracked independently by SZSM separation analysis (t.0 and t.1 are disjoint places) and support moving Drop elements out cleanly without double-drop.


6. Operators, Forward Pipe, and Formatted Strings

6.1 Operator Precedence (Highest to Lowest)

  1. Postfix: x.f, x.m(...), x[i], x[a..b], f(...), x?
  2. Unary: -x, !x, ~x, &x, &mut x, *x, sizeof(T), alignof(T)
  3. Cast: x as T
  4. Multiplicative: *, /, %
  5. Additive: +, -
  6. Bitwise shift: <<, >>
  7. Bitwise AND: &
  8. Bitwise XOR: ^
  9. Bitwise OR: |
  10. Range: a..b, a..=b
  11. Forward pipe: a |> f
  12. Comparison: ==, !=, <, <=, >, >=
  13. Logical AND: && (short-circuiting)
  14. Logical OR: || (short-circuiting)
  15. Assignment: =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=

6.2 Forward Pipe (|>)

x |> f passes x as the first argument to f(x); x |> f(a, b) passes x as the first argument f(x, a, b).

stag
use kit.math

res := -12 |> math.abs_i64 |> math.clamp_i64(0, 10) // 10

6.3 Formatted Strings (f"...")

f"..." builds an owned kit.text.Text value by formatting interpolated {expr} segments using kit.scribe.Show (implemented for primitives, bool, str, Text, and any user type implementing Show). Escaped braces are written {{ and }}.

stag
use kit.text (Text)

name := Text.from_str("stag")
n := 42
msg := f"lang={name}, n={n}, {{ok}}" // borrows `name` without moving it

7. Control Flow and Pattern Matching

7.1 if / elif / else

if is an expression. An inline expression form uses then:

stag
sign := if x < 0 then -1 elif x > 0 then 1 else 0

val := if ready:
    compute()
else:
    0

7.2 match / case

Subject matching supports integers, booleans, strings, choice variants (unit, tuple, and record variants), and else: wildcard arms:

stag
choice Shape:
    Empty
    Circle(f64)
    Rect { w: f64, h: f64 }

func area(s: *Shape) -> f64:
    match s:
        case Shape.Empty: 0.0
        case Shape.Circle(r): 3.14159265 * (*r) * (*r)
        case Shape.Rect { w, h }: (*w) * (*h)
  • Borrowed pointer matching: matching a *Choice or *mut Choice binds payload fields as *Payload / *mut Payload without moving or copying owned Drop payloads.
  • Opt-in pattern dereference (*v): for non-Drop payloads inside *Choice, case Shape.Circle(*r): binds r: f64 directly by value.
  • Guarded match: (subjectless): ``stag grade := match: case score >= 90: "A" case score >= 80: "B" else: "C" ``

7.3 Loops, Ranges, and Labels

stag
// Counted range loops
for i in 0..10:
    work(i)

for i in 0..=10:
    work(i)

// Slice iteration
for elem in slice:
    use(elem)

// Iterator protocol (any type with `next(mut self) -> Maybe[Item]`)
for entry in table.iter():
    use(entry.key, entry.val)

// While and infinite loops
while cond:
    step()

val := @outer loop:
    for i in 0..10:
        if i == 7:
            break @outer i * 10

7.4 Block Expressions (do:)

do: introduces a scoped block expression whose value is its final expression:

stag
res := do:
    tmp := a + b
    tmp * 2

8. Functions, Named and Default Arguments, Closures, and main

8.1 Functions

stag
func add(a: i64, b: i64) -> i64:
    a + b

// Single-expression shorthand
func square(x: i64) -> i64 = x * x

8.2 Named and Default Arguments

Parameters may declare default values (any expression valid in default position). Call sites may pass arguments positionally or by name (param = value) in any order after positional arguments, across free functions, methods, and generic calls (E2170..E2173):

stag
func connect(host: str, port: i64 = 8080, retries: i64 = 3) -> i64:
    port + retries

func demo():
    a := connect("localhost")
    b := connect("localhost", retries = 5)
    c := connect(port = 443, host = "example.com")

Named arguments are not allowed on indirect function-pointer calls (E2151).

8.3 Function Pointers and Closures

stag
func apply(x: i64, f: func(i64) -> i64) -> i64 = f(x)

func demo() -> i64:
    apply(20, func(v: i64) -> i64 = v + 2)

Stateless closures convert directly to func(...) -> ... function pointers.

8.4 main Entry Point

main may take either no parameters or CLI arguments as []str, and return i32 or unit:

stag
func main() -> i32:
    0i32

func main(argv: []str) -> i32:
    if argv.len > 1 then 0i32 else 1i32

9. Records, Unions, Choices, Inline Methods, and attach

9.1 Records and Unions

stag
pub record Vec2:
    x: f64
    y: f64

    pub func zero() -> Vec2 = Vec2 { x: 0.0, y: 0.0 }

    pub func dot(in self, other: Vec2) -> f64 = self.x * other.x + self.y * other.y

    pub func scale(mut self, k: f64):
        self.x *= k
        self.y *= k

Receiver kinds:

  • in self: immutable borrow (*Self)
  • mut self: mutable borrow (*mut Self)
  • self: move / by-value (Self)
  • No self: associated static function (Vec2.zero())

Layout modifiers:

  • extern record Name: — C ABI struct layout.
  • packed record Name: — 1-byte packed alignment.
  • union Name: / extern union Name: — overlapping fields (C union layout).
  • extern record Opaque (bodyless) — opaque foreign struct usable only behind pointers.

9.2 Choices (Tagged Unions / ADTs)

stag
pub choice Token:
    Eof
    Int(i64)
    Ident { start: i64, len: i64 }

9.3 attach Blocks

Methods and trait implementations can be written either inline inside record/choice or externally via attach:

stag
attach Vec2:
    pub func len_sq(in self) -> f64 = self.x * self.x + self.y * self.y

10. Generics, Traits, Operator Overloading, and const func

10.1 Parametric Generics ([T])

Stag uses square brackets [T] for generic parameters and explicit type arguments everywhere (with bidirectional type inference):

stag
pub record Pair[A, B]:
    first: A
    second: B

attach[A, B] Pair[A, B]:
    pub func new(first: A, second: B) -> Pair[A, B]:
        Pair[A, B] { first: first, second: second }

    pub func map_first[C](in self, f: func(*A) -> C) -> Pair[C, B]:
        Pair[C, B] { first: f(&self.first), second: self.second }

All generics are monomorphized at compile time with zero runtime heap-wrapping.

10.2 Traits, Supertraits, and Associated Types

stag
pub trait Eq:
    func eq(in self, other: *Self) -> bool

pub trait Ord : Eq:
    func cmp(in self, other: *Self) -> i32

pub trait Add:
    type Output
    func add(in self, rhs: Self) -> Self.Output

Conformance uses attach Type : Trait::

stag
attach Vec2 : Eq:
    func eq(in self, o: *Vec2) -> bool = self.x == o.x && self.y == o.y

10.3 Built-in Operator Overloading Traits

The compiler prelude defines the following traits, which wire directly to operators:

TraitMethodOperator
Add (type Output)add(in self, rhs: Self) -> Self.Output+
Sub (type Output)sub(in self, rhs: Self) -> Self.Output-
Mul (type Output)mul(in self, rhs: Self) -> Self.Output*
Div (type Output)div(in self, rhs: Self) -> Self.Output/
Rem (type Output)rem(in self, rhs: Self) -> Self.Output%
Neg (type Output)neg(in self) -> Self.Outputunary -
Eqeq(in self, other: *Self) -> bool==, !=
Ord : Eqcmp(in self, other: *Self) -> i32<, <=, >, >=
Index (type Output)index(in self, idx: i64) -> *Self.Outputx[i]
IndexMutindex_mut(mut self, idx: i64) -> *mut Self.Outputx[i] = v
Dropdrop(mut self)deterministic scope exit

10.4 Compile-Time Execution (const func)

Functions marked const func are evaluated deterministically on the HIR interpreter when called in const or static initializers:

stag
const func factorial(n: i64) -> i64:
    if n <= 1 then 1 else n * factorial(n - 1)

const FACT10: i64 = factorial(10)

11. Ownership, Move Semantics, Drop, and defer

11.1 Drop RAII and Move Checking

Any type that implements Drop (or contains a field/variant implementing Drop, such as Text, List[T], Table[K, V], Json, File) has move semantics:

  • Passing or assigning a Drop value by value moves ownership; subsequent use emits E2133.
  • Non-Drop values are trivially copyable.
  • Compiler-generated recursive drop glue destroys owned fields and active choice variants deterministically in reverse declaration order (LIFO).
  • Static drop-flag elision (AlwaysLive, AlwaysMoved, Dynamic) eliminates runtime drop flags whenever liveness is statically known.

11.2 defer and defer if

defer schedules a cleanup block to run on every exit from the enclosing block (normal fallthrough, return, break, continue, or ?), strictly interleaved in LIFO order with local Drop destructors:

stag
func process() -> i64:
    var ok = false
    defer:
        cleanup_always()
    defer if !ok:
        rollback_on_failure()
    work()
    ok = true
    0

12. Sealed Zone and Separation Memory Model (SZSM)

SZSM provides deterministic region allocation and static memory-safety proofs without garbage collection or lifetime annotations.

12.1 Lexical Zones (zone)

stag
func build_histogram(data: []i64) -> i64:
    zone scratch:
        bins := scratch.alloc_zeroed[i64](256)
        for v in data:
            idx := v & 255
            bins[idx] += 1
        var best: i64 = 0
        for i in 0..256:
            if bins[i] > best:
                best = bins[i]
        best
    // `scratch` is bulk-reclaimed in O(1) here; all zone-allocated Drop objects are dropped LIFO.

Zone operations:

  • z.alloc[T](count: i64) -> []mut T — uninitialized array allocation in z.
  • z.alloc_zeroed[T](count: i64) -> []mut T — zero-initialized array allocation in z.
  • z.new[T](value: T) -> *mut T — allocates and initializes a single value in z.
  • z.bytes(count: i64) -> []mut u8 — raw byte slice in z.

Implementation: each zone starts with a 4 KB inline stack bump slab (zero syscalls for typical scratch workloads) and spills automatically to chained heap slabs if exceeded.

12.2 Borrowed Zone Parameters (in z: zone)

Functions may accept a caller's zone without allocating their own:

stag
func alloc_pair(in z: zone, a: i64, b: i64) -> []mut i64:
    buf := z.alloc[i64](2)
    buf[0] = a
    buf[1] = b
    buf

12.3 Static Safety Proofs and --emit=mem

SZSM statically proves:

  • No stack or zone pointer escape (E4001, E4005, E4006): pointers/slices originating from a local or zone cannot be returned past their owning region or stored into longer-lived globals/outer pointers.
  • Separation and non-lexical live borrows (E4004): disjoint record fields (s.a vs s.b), tuple slots (t.0 vs t.1), and symbolic disjoint slices (arr[0..mid] vs arr[mid..n]) can be mutably borrowed simultaneously, while overlapping aliasing conflicts are rejected.
  • Static Drop-Flag Elision: classifies every Drop local as AlwaysLive, AlwaysMoved, or Dynamic to eliminate unnecessary runtime drop flags.
  • LLVM Optimization Attributes: fixed-point interprocedural effect inference emits LLVM noalias, readonly, writeonly, captures(none), and memory(...) attributes automatically. Inspect proofs with stagc --emit=mem file.stag.
text
Region Lifetime Nesting (SZSM):
+-----------------------------------------------------------+
| Global / Static Region                                    |
|  +-----------------------------------------------------+  |
|  | Function Stack Frame                                |  |
|  |  +-----------------------------------------------+  |  |
|  |  | zone scratch: (4 KB stack slab -> heap spill) |  |  |
|  |  |   buf := scratch.alloc[i64](64)               |  |  |
|  |  |   // valid inside 'scratch'                   |  |  |
|  |  +-----------------------------------------------+  |  |
|  |  // E4001 if pointer/slice from 'scratch' escapes   |  |
|  +-----------------------------------------------------+  |
+-----------------------------------------------------------+

13. Automatic Loop Parallelization (--par) and Optimization Hints

Built on SZSM, stagc automatically proves and parallelizes data-race-free loops when --par is enabled.

13.1 Modes and Flags

FlagBehavior
--par=off (default)Single-threaded code generation.
--par=auto (or --par)Parallelizes proved loops whose runtime trip count exceeds the static break-even threshold.
--par=forceParallelizes all proved loops with min_trips = 2 (useful for verification and stress testing).
--par=autotuneRuns an online per-(site, size-bucket) A/B empirical autotuner selecting sequential vs parallel at runtime.
`--threads=<N\auto>, -j <N\auto>`Sets worker count (1..64 or auto). Overridable at runtime via STAG_THREADS=<N>.
--emit=parPrints the formal proof certificate or exact sequential fallback reason for every loop.

Set STAG_PAR_STATS=1 in the environment to log runtime autotuner measurements to stderr.

13.2 What the Prover Accepts

  • Bernstein independence (W(i) ∩ W(j) = ∅ and W(i) ∩ R(j) = ∅ for i != j):
  • Single- and multi-dimensional affine indexing, including propagated immutable temporaries (row := i * cols, plane := i * rows * cols, interleaved (i * cols + j) * 4 + c).
  • Shifted 2D stencils (dst[(i - 1) * w + j] = src[i * w + j - 1] + src[i * w + j + 1]), interior inner bounds (for j in 1..w - 1:, <=), and DP / wavefront inner loops (for i in 1..h: for j in 1..w - 1: dp[i * w + j] = dp[(i - 1) * w + j - 1] + ... with formal row-boundary disjointness proofs).
  • Power-of-2 bit-shift and bitmask indexing (img[(i << 2) | (c & 3)]).
  • Field-sensitive Array-of-Structs separation (ps[i].vx += ps[(i + 1) % n].mass) and distinct struct-embedded array fields (sim.next[i] = sim.cur[i - 1] + sim.cur[i + 1]).
  • Raw pointer arithmetic (ptr_offset(base, affine_idx), ptr_read, ptr_write) and fresh heap allocations (malloc/calloc/alloc_* propagated through slice_from_raw).
  • Loop-local stack array slices (tmp := [0; 4]; helper(tmp[..])) proved thread-private.
  • Disjoint sub-slice row arguments (process_row(grid[i*cols..(i+1)*cols])) and pre-loop split slices (left := a[0..mid], right := a[mid..n]).
  • O(1) Runtime Alias-Disjointness Multiversioning: when distinct slice/array containers are MayAlias (not statically proven overlapping), stagc emits an O(1) runtime address-range disjointness check (endA <=u startB || endB <=u startA) that executes the parallel worker path when disjoint and falls back safely to the exact sequential loop when overlapping.
  • GCD / Bézout non-divisibility (a[2*i] = a[2*i+3]) and reverse indexing (dst[n-1-i] = src[i]).
  • Inclusive ranges (for i in lo..=hi:), ascending, descending (i -= step), strided, swapped-bound (n > i), and all concrete integer counter widths (i8..u64).
  • Calls to pure hardware math intrinsics (kit.math.sqrt, fma_f64, sin_f64, etc.) and pure libm functions.
  • Automatic 2D Rectangular Loop Collapse: fuses small statically-known outer loops (1..32 outer trips) into a single [0, R*C) region to saturate all cores, while keeping large or dynamic 2D stencils uncollapsed so inner loops vectorize at full native SIMD width.
  • Exact Associative Monoid Reductions (up to 16 simultaneous):
  • Integer +=, signed -=, *=, &=, |=, ^=, min, max (via if, if..then..else, or pure math.min_i64 / math.max_i64 calls), expanded forms (acc = acc + x), and boolean monoids (&&, ||, sticky if cond: found = true).
  • Per-worker 128-byte-aligned reduction slots merged deterministically in ascending worker order (bit-identical across 1–64 threads).
  • Guided Dynamic Work-Stealing & Zero-Lock Hot Barrier: automatically enabled (sched=guided) for triangular, branch-skewed, CSR/irregular inner loops, and loops calling pure helpers that contain loops (e.g. primality testing). Captured read-only scalars, pointers, and slice handles are SSA-promoted inside parallel workers for full SIMD vectorization, backed by a zero-lock Dekker spin-then-park runtime barrier.

13.3 Soundness Rejections and Runtime Multiversioning Flow

diagram
flowchart LR
    LOOP["Counted Loop in HIR"] --> PROOF{"Bernstein / Reduction Proof"}
    PROOF -- "Unproven / Impure / Conflict" --> SEQ["Sequential Loop"]
    PROOF -- "Disjoint Proven Statically" --> TRIP{"trip_count >= min_trips?"}
    PROOF -- "MayAlias Containers" --> GUARD{"O(1) Runtime Disjoint Guard\nendA <=u startB || endB <=u startA"}
    GUARD -- "Overlap" --> SEQ
    GUARD -- "Disjoint" --> TRIP
    TRIP -- "No" --> SEQ
    TRIP -- "Yes" --> PAR["ParRuntime Worker Pool (1..64 threads)\nSSA-Promoted Env + Dekker Barrier"]

The prover keeps loops sequential whenever safety cannot be proven, including: impure or unknown external calls, indirect function-pointer calls, statically overlapping writes (e.g. in-place transpose, in-place reverse, or same-raw-pointer slices), overlapping union fields, non-associative floating-point reductions, unsigned subtraction underflow risks, and early break/return.

13.4 Optimization Hints (Manual & Automatic) and --emit=hints

Stag includes a dedicated optimization-hint pass (HintAnalyzer, executed after SZSM MemoryAnalyzer and before LLVM CodeGen). Hints can be placed manually before functions, methods, if statements, or loops using @name or grouped @hint(...), and are also inferred automatically when omitted:

stag
@inline
@hot
func dot_step(a: f64, b: f64, acc: f64) -> f64 = math.fma_f64(a, b, acc)

func compute(dst: []mut f64, src: []f64):
    @hint(vectorize, unroll(4), parallel)
    for i in 0..dst.len:
        @unlikely
        if src[i] < 0.0:
            dst[i] = 0.0
        else:
            dst[i] = math.sqrt(src[i])
HintValid TargetsEffect
@inline / @noinlinefunc, methodEmit LLVM alwaysinline (or inlinehint if auto-inferred) / noinline.
@hot / @coldfunc, methodEmit LLVM hot / cold function attributes for code layout and optimization priority.
@purefunc, methodMark side-effect-free functions with LLVM memory(none) (also inferred automatically from SZSM).
@likely / @unlikelyifEmit LLVM !prof branch weights (2000:1 / 1:2000). Auto-inferred for trapping branches and null-pointer guards.
@vectorize / @novectorizefor, while, loopEnable or disable LLVM SIMD loop vectorization metadata (llvm.loop.vectorize.enable).
@unroll / @unroll(N) / @nounrollfor, while, loopFull unroll, factor-N unroll (N in 2..64), or disable unrolling (llvm.loop.unroll.*).
@parallel / @noparallelfor, while, loopOverride static cost break-even on a proved loop (@parallel) or keep a loop sequential (@noparallel).

Contradiction & Suspicious Hint Warnings (W6001..W6008): When a manual hint contradicts compiler analysis, stagc emits a diagnostic explaining the mismatch (e.g. W6001 for @inline on recursive/large functions, W6002 for @cold on loop-called functions or @hot on trapping functions, W6003 for @likely/@unlikely contradicting traps, W6004 for @pure on mutating functions, W6005 for @vectorize on dependent loops, W6006 for dubious @unroll, W6007 for @parallel on loops with unproven memory safety, and W6008 for conflicting hints on the same item). For safe hints, stagc still honors the user's manual hint alongside the warning; for @parallel on non-provably-safe loops, stagc emits W6007 and keeps the loop sequential to guarantee race freedom. Inspect all inferred and manual hints with stagc --emit=hints file.stag.

13.5 Native CPU Targeting and Full SIMD Vectorization

Pass --cpu=native (or a specific LLVM CPU name such as --cpu=znver4, --cpu=skylake, --cpu=apple-m2) and optional --features=+avx2,+fma alongside -O2 or -O3:

sh
stagc kernel.stag -O3 --cpu=native --par=auto -o kernel

stagc queries the host CPU model and hardware ISA features, attaches target-cpu and target-features to all generated functions, and wires TargetIRAnalysis into LLVM's PassBuilder so LLVM's Loop Vectorizer and SLP Vectorizer emit native SIMD instructions (such as AVX2/AVX-512 vsqrtpd and vfmadd* or ARM NEON vector instructions).


14. Error Handling (Maybe, Outcome, ?)

stag
use kit.maybe (Maybe)
use kit.outcome (Outcome)
use kit.text (Text)

func parse_port(s: str) -> Outcome[i64, Text]:
    t := Text.from_str(s)
    match t.parse_i64():
        case Outcome.Ok(v):
            if v < 1 || v > 65535:
                return Outcome.Err(Text.from_str("port out of range"))
            Outcome.Ok(v)
        case Outcome.Err(_):
            Outcome.Err(Text.from_str("invalid integer"))

func load_port(raw: str) -> Outcome[i64, Text]:
    p := parse_port(raw)?    // early-returns Outcome.Err on failure
    Outcome.Ok(p)

Postfix ? works on any 2-variant choice with variants Some/None or Ok/Err (including inside const func). All defer blocks and local Drop destructors execute cleanly on ? early return.


15. Modules and Visibility (use, pub)

stag
use kit.json                     // namespace import: json.parse(...)
use kit.json as j                // aliased namespace import: j.parse(...)
use kit.json (Json, parse)       // selective symbol import
use mypkg.utils (helper)         // resolves mypkg/utils.stag relative to importer or -I dirs
  • Declarations are module-private by default; mark exported functions, records, choices, traits, methods, constants, and statics with pub.
  • Override embedded Standard Kit lookup with --kit-path <dir> or disable it completely with --no-kit.

16. Built-in Crash-Isolated Testing (test, --test)

stag
use kit.check

test "arithmetic invariant":
    check.eq_i64(2 + 2, 4, "addition")

Running stagc --test file.stag:

  • Compiles all test "...": blocks in the root module into a test binary.
  • Executes each test in an isolated child subprocess so trap(), bounds violations, division by zero, or static var mutations in one test cannot corrupt subsequent tests.
  • Reports per-test pass/fail status, exit code, and elapsed milliseconds.
  • Supports --filter <substr>, --list, --fail-fast, and -o <path> (emit standalone test executable).
  • Rejects non-unit test bodies (E2010), empty names (E1092), and duplicate test names (E2165).

17. C FFI, Calling Conventions, Inline Assembly, and Intrinsics

17.1 External Functions and Globals

stag
extern func strlen(s: *u8) -> u64
extern func printf(fmt: *u8, ...) -> i32

extern "win64" func fast_entry(x: i64) -> i64
extern "sysv64" func unix_entry(x: i64) -> i64

extern "C":
    func custom_init(flags: u32) -> i32
    static var errno_val: i32

Supported calling conventions: "C" (target default), "win64", "sysv64", "stdcall", "fastcall".

17.2 Inline Assembly (asm)

stag
func rdtsc_low() -> u64:
    var lo: u32 = 0u32
    asm("rdtsc", "=a"(lo))
    lo as u64

17.3 Built-in Compiler Intrinsics

  • ptr_offset[T](ptr: *T, count: i64) -> *T (and *mut T -> *mut T)
  • ptr_read[T](ptr: *T) -> T
  • ptr_write[T](ptr: *mut T, value: T)
  • mem_copy[T](dst: *mut T, src: *T, count: i64)
  • mem_move[T](dst: *mut T, src: *T, count: i64)
  • mem_set(dst: *mut u8, byte: u8, count: i64)
  • str_from_raw(ptr: *u8, len: i64) -> str
  • slice_from_raw[T](ptr: *T, len: i64) -> []T (and *mut T -> []mut T)
  • drop_in_place[T](ptr: *mut T)
  • sizeof(T) -> i64, alignof(T) -> i64
  • trap() -> never

18. Embedded Standard Kit (kit.*) Complete Reference

All 18 modules are embedded inside stagc and require no external dependencies beyond standard C libc/libm.

kit.maybe

  • choice Maybe[T]: None, Some(T).
  • Methods: is_some, is_none, unwrap, unwrap_or, as_ref, as_mut.

kit.outcome

  • choice Outcome[T, E]: Ok(T), Err(E).
  • Methods: is_ok, is_err, unwrap, unwrap_or, unwrap_err, ok, err.

kit.mem

  • size_of[T](), align_of[T](), swap[T](a, b), replace[T](dst, val), zero_bytes(dst, len), bytes_eq(a, b, len), bytes_cmp(a, b, len).

kit.alloc

  • alloc_bytes(n), alloc_zeroed(n), realloc_bytes(p, n), dealloc_bytes(p), alloc_array[T](n), realloc_array[T](p, n), dealloc_array[T](p).

kit.hash

  • record Hasher: new, write_u8, write_u64, write_i64, write_bytes (8-byte word hashing), write_str, finish.
  • trait Hash, func hash_of[T: Hash](v: *T) -> u64.
  • Built-in Eq and Hash implementations for i8..u64, bool, and str.

kit.list

  • record List[T] (Drop, Index, IndexMut): new, with_cap, len, cap, is_empty, reserve, push, pop, get, get_mut, first, last, insert, remove, swap_remove, reverse, sort_by, find_index, contains_by, clear, as_slice, as_mut_slice, iter (ListIter[T]).

kit.text

  • record Text (Drop, Eq, Ord, Add, Hash, NUL-terminated UTF-8): new, with_cap, from_str, from_cstr, clone, len, cap, is_empty, reserve, push_byte, push_raw, push_repeat, push_str, push_u64, push_i64, push_f64, clear, as_str, as_cstr, as_bytes, byte_at, substr, eq_str, starts_with, ends_with, find, contains, trim_start, trim_end, trim, to_upper, to_lower, split, replace_str, parse_u64, parse_i64.

kit.table

  • record Table[K: Eq + Hash, V] (Drop, open-addressing linear probing with tombstones): new, with_cap, len, cap, is_empty, reserve, set, get, get_mut, has, del, find_by_hash[Q], get_by_hash[Q], get_mut_by_hash[Q], del_by_hash[Q], clear, iter (TableIter[K, V] yielding TableEntry[K, V]).

kit.scribe

  • trait Show: show(in self, out: *mut Text).
  • Built-in Show implementations for primitives, bool, str, Text, and formatting helpers format_i64, format_u64, format_f64, format_bool.

kit.io

  • Console: print, println, eprint, eprintln, flush, read_line.
  • File (Drop): open_read, open_write, open_append, read_all, write_str, write_bytes, flush, close.
  • Convenience helpers: read_file, read_lines, write_file, append_file, file_exists, remove_file.

kit.sys

  • exit_process(code: i32) -> never, abort_process() -> never, env_get(name: str) -> Maybe[Text], env_has(name: str) -> bool.

kit.math

  • Constants: PI, TAU, E, SQRT2.
  • Integer utilities (const func): abs_i64, min_i64, max_i64, clamp_i64, gcd_i64, lcm_i64, pow_i64.
  • Hardware-intrinsic floating-point operations (exact IEEE-754, auto-vectorizable, and pure for --par): sqrt, sqrt_f64, sqrt_f32, fma_f64, fma_f32, abs_f64, abs_f32, floor_f64, ceil_f64, round_f64, trunc_f64, sin_f64, cos_f64, exp_f64, ln_f64, log10_f64, pow_f64.
  • Additional floating-point helpers: min_f64, max_f64, clamp_f64, lerp_f64, tan_f64, asin_f64, acos_f64, atan_f64, atan2_f64, fmod_f64, hypot_f64.

kit.args

  • count() -> i64, get(idx: i64) -> Maybe[str], all() -> List[Text].

kit.path

  • join(a, b), file_name(p), stem(p), extension(p), has_extension(p, ext), parent(p), is_absolute(p), normalize_slashes(p).

kit.time

  • Constants: NANOS_PER_MICRO, NANOS_PER_MILLI, NANOS_PER_SECOND, MICROS_PER_MILLI, MICROS_PER_SECOND, MILLIS_PER_SECOND.
  • Wall-clock Unix epoch: unix_seconds(), unix_millis(), unix_micros(), unix_nanos(), now_ms(), now_us(), now_ns(), diff_seconds(end, start).
  • Monotonic clock: monotonic_ns(), monotonic_us(), monotonic_ms(), monotonic_seconds().
  • Sleep: sleep_ns(ns), sleep_us(us), sleep_ms(ms), sleep_seconds(sec).
  • record Duration: zero, from_nanos, from_micros, from_millis, from_seconds, as_nanos, as_micros, as_millis, as_millis_f64, as_seconds, is_zero, add, sub.
  • record Timer: start, elapsed_ns, elapsed_us, elapsed_ms, elapsed_ms_f64, elapsed_seconds, elapsed, lap_ns, lap_ms, lap, reset.

kit.check

  • Test assertions: fail, assert, ok, eq_i32, eq_i64, ne_i64, lt_i64, le_i64, gt_i64, ge_i64, eq_u64, eq_bool, eq_str, ne_str, contains_str, eq_text, near_f64, eq[T: Eq], ne[T: Eq], is_some, is_none, is_ok, is_err.

kit.rand

  • record Rng: from_seed(u64), next_u64(), next_i64(), next_f64(), range_u64(bound), range_i64(lo, hi), shuffle[T](list).

kit.json

  • RFC 8259 parser, zero-DOM validator, DOM, RFC 6901 JSON Pointer, and compact / pretty serializer.
  • const DEFAULT_MAX_DEPTH: i64 = 128.
  • choice Json: Null, Bool(bool), Int(i64), Num(f64), Str(Text), Arr(List[Json]), Obj(Table[Text, Json]) (implements Eq).
  • Entry points: parse(input), parse_with_max_depth(input, max_depth), validate(input), validate_with_max_depth(input, max_depth).
  • Constructors: Json.null_val(), bool_val, int_val, float_val, str_val, text_val, array, array_with_cap, object, object_with_cap.
  • Predicates: is_null, is_bool, is_int, is_float, is_number, is_str, is_array, is_object.
  • Accessors: as_bool, as_int, as_i64, as_f64, as_num, as_str, as_arr, as_arr_mut, as_obj, as_obj_mut, get_index, get_index_mut, get_key, get_key_mut, has_key, len, is_empty.
  • Mutators: push, set, remove_key.
  • RFC 6901 JSON Pointer: pointer(path: str) -> Maybe[*Json], pointer_mut(path: str) -> Maybe[*mut Json].
  • Cloning & comparison: clone(), equals(other) / ==.
  • Serialization: write_to, write_pretty_to(out, indent), stringify, stringify_with_cap(cap), stringify_pretty(indent), stringify_pretty_with_cap(indent, cap).

19. Runtime Checks, Debugging, Cross-Compilation, Diagnostics, and Emission Outputs

19.1 Runtime Safety Checks

Enabled by default (disable with --unchecked unless forbidden by format.json):

  • Array and slice bounds checking (trap() on out-of-bounds).
  • Division/remainder by zero and signed INT_MIN / -1 overflow trap.
  • Checked integer overflow on +, -, * (llvm.sadd/uadd/ssub/usub/smul/umul.with.overflow).

19.2 Debugging (-g)

stagc -g -O0 file.stag -o app emits DWARF v4 metadata on ELF/Mach-O/MinGW targets and CodeView on Windows MSVC targets, compatible with gdb, lldb, and Visual Studio / CodeLLDB.

19.3 Cross-Compilation (--target)

stagc --target=<triple> --emit=obj -O2 file.stag -o file.o supports LLVM target triples including x86_64-unknown-linux-gnu, aarch64-unknown-linux-gnu, x86_64-pc-windows-gnu, x86_64-pc-windows-msvc, aarch64-apple-darwin, riscv64-unknown-linux-gnu, and wasm32-unknown-unknown.

19.4 Diagnostic Format, --Werror, and Code Ranges

Diagnostics are formatted in Stag's CLI layout:

text
ERROR E2024 (main.stag:4:12): <message>
  4 :     ...
    :     ^^^^^
  help: ...
summary: 1 error, 0 warnings

Pass --Werror (or --warnings-as-errors) to promote all compiler warnings (W2001..W2099, W6001..W6008) to hard errors.

RangeSubsystem
E0001..E0099Lexer (UTF-8, unterminated literals/comments, invalid escapes).
E1000..E1099Parser (indentation, syntax, recursion depth E1099, test names E1092).
E1100..E1101Removed legacy syntax diagnostics.
E1999Internal formatter safety verification failure (original source preserved).
E2000..E2199Semantic analyzer (types, moves E2133, named/default args E2151/E2170..E2173, generics, traits, duplicate tests E2165, recursion depth E2195).
W2001..W2099Semantic warnings (unused bindings, unreachable code, unmutated var).
E4001..E4009SZSM memory analyzer (escape E4001, overlapping mutable borrow E4004, zone violations E4005..E4006).
E5000..E5012format.json policy engine violations.
E6001..E6003Optimization hint syntax/target/argument errors (@name validation).
W6001..W6008Optimization hint contradiction and suspicious-hint warnings (HintAnalyzer).
E8001..E8009Backend, LLVM target lookup, object emission, and linker errors.

19.5 Exact Input / Output Examples for Compiler Emission Modes

Given the following input program sample.stag:

stag
func scale_add(dst: []mut i64, src: []i64, k: i64):
    for i in 0..dst.len:
        dst[i] = src[i] * k + 1

func main() -> i32:
    var out: [4]i64 = [0, 0, 0, 0]
    inp: [4]i64 := [1, 2, 3, 4]
    scale_add(out[..], inp[..], 3)
    return out[3] as i32
  • stagc sample.stag --emit=tokens -o - (excerpt):
text
1:1	func	func
1:6	IDENT	scale_add
1:15	(	(
1:16	IDENT	dst
1:19	:	:
1:21	[	[
1:22	]	]
1:23	mut	mut
1:27	i64	i64
...
1:52	NEWLINE
2:1	INDENT
2:5	for	for
  • stagc sample.stag --emit=ast -o - (excerpt):
text
Program
  Fn scale_add(dst: []mut i64, src: []i64, k: i64) -> unit
    Block
      Tail
        For i
          Range
            IntLit 0
            Field .len
              Ident dst
          Block
            Tail
              Assign =
                Index []
                  Ident dst
                  Ident i
                Binary +
                  Binary *
                    Index []
                      Ident src
                      Ident i
                    Ident k
                  IntLit 1
  • stagc sample.stag --emit=mem -o -:
text
=== Stag Memory & Parallelism Proof Certificates (SZSM v0.1.0) ===
func scale_add:
  effect: ArgMemReadWrite
  param dst ([]mut i64): writeonly nocapture
  param src ([]i64): readonly nocapture
  loop #0 (iv=i): [PAR-PROVED: Independent] — Bernstein-proved: W(i) ∩ W(j) = ∅ and W(i) ∩ R(j) = ∅ for all i != j
func main:
  effect: Pure
  • stagc sample.stag --emit=par --par=auto -o -:
text
=== Stag Auto-Parallelization Report (v0.1.0, mode=auto) ===
func scale_add:
  loop #0 (iv=i): [PARALLELIZED site #0 | PAR-PROVED: Independent] cost~8cyc/iter, min_trips=14063
    proof: Bernstein-proved: W(i) ∩ W(j) = ∅ and W(i) ∩ R(j) = ∅ for all i != j
Summary: 1 loop(s) analyzed, 1 mathematically proved parallel-safe, 1 scheduled for parallel execution.
  • stagc sample.stag --emit=hints -o -:
text
=== Stag Optimization Hint Report (v0.1.0) ===
  scale_add [loop #0]: @vectorize (auto) - innermost Bernstein-proved independent/reduction loop
Summary: 1 hint(s) (1 auto, 0 manual)

20. C++20 Embedding and Tooling API (stag/Stag.hpp)

External C++20 tools (linters, static analyzers, language servers, documentation generators, refactoring utilities, and custom LLVM backends) can embed any stage of the Stag compiler by including <stag/Stag.hpp> and linking against the stag_lib library target.

All public types, option structs, result objects, input/output formats, lifetime and thread-safety contracts, CMake integration snippets, and complete examples are documented in docs/EMBEDDING_API.md.


21. Worked End-to-End Input/Output Specifications

This section provides complete, self-contained compiler inputs, exact command-line invocations, and exact expected outputs across core language subsystems.

21.1 Generic Data Structures, Traits, and Monomorphization

Input (ring_stats.stag):

stag
use kit.io (Console)
use kit.list (List)
use kit.scribe (Show, to_text)
use kit.text (Text)

pub record Summary[T]:
    count: i64
    min_val: T
    max_val: T

attach[T: Ord] Summary[T]:
    pub func from_slice(xs: []T) -> Summary[T]:
        var lo = xs[0]
        var hi = xs[0]
        for i in 1..xs.len:
            if xs[i].cmp(&lo) < 0i32:
                lo = xs[i]
            if xs[i].cmp(&hi) > 0i32:
                hi = xs[i]
        Summary[T] { count: xs.len, min_val: lo, max_val: hi }

func main() -> i32:
    var vals = List[i64].new()
    vals.push(42)
    vals.push(-7)
    vals.push(19)
    vals.push(104)
    s := Summary[i64].from_slice(vals.as_slice())
    line := f"count={s.count} min={s.min_val} max={s.max_val}"
    Console.println(line.as_str())
    0i32

Command & Expected Output:

text
$ stagc ring_stats.stag -O2 -o ring_stats && ./ring_stats
count=4 min=-7 max=104
  • Monomorphization contract: Summary[i64] is lowered to a concrete LLVM struct { i64, i64, i64 } with zero dynamic dispatch or boxing.

21.2 Algebraic Data Types (choice), Exhaustive match, and ? Propagation

Input (expr_eval.stag):

stag
use kit.io (Console)
use kit.outcome (Outcome)
use kit.text (Text)

choice Op:
    Add(i64, i64)
    Div(i64, i64)

func eval(op: Op) -> Outcome[i64, str]:
    match op:
        case Op.Add(a, b): Outcome.Ok(a + b)
        case Op.Div(_, 0): Outcome.Err("division by zero")
        case Op.Div(a, b): Outcome.Ok(a / b)

func run_pipeline(x: i64, y: i64) -> Outcome[i64, str]:
    sum := eval(Op.Add(x, y))?
    quot := eval(Op.Div(sum, y))?
    Outcome.Ok(quot)

func main() -> i32:
    match run_pipeline(20, 5):
        case Outcome.Ok(v):
            msg := f"ok={v}"
            Console.println(msg.as_str())
        case Outcome.Err(e):
            Console.println(e)
    match run_pipeline(20, 0):
        case Outcome.Ok(_):
            Console.println("unexpected")
        case Outcome.Err(e):
            msg := f"err={e}"
            Console.println(msg.as_str())
    0i32

Command & Expected Output:

text
$ stagc expr_eval.stag -O2 -o expr_eval && ./expr_eval
ok=5
err=division by zero
  • Exhaustiveness rule: Omitting any Op variant without a wildcard case _: fails semantic analysis with a compile-time error before code generation.

21.3 Arena zone Scoping and Compile-Time Escape Rejection

Valid Input (zone_ok.stag):

stag
use kit.io (Console)

func sum_in_zone(n: i64) -> i64:
    var total: i64 = 0
    zone scratch:
        var buf: [4]i64 = [n, n + 1, n + 2, n + 3]
        for i in 0..4:
            total += buf[i]
    total

func main() -> i32:
    ans := sum_in_zone(10)
    msg := f"zone_sum={ans}"
    Console.println(msg.as_str())
    0i32

Command & Expected Output:

text
$ stagc zone_ok.stag -O2 -o zone_ok && ./zone_ok
zone_sum=46

Invalid Input (pointer escaping a zone):

stag
func bad_escape() -> *i64:
    var leaked: *i64 = null
    zone z:
        x := 99
        leaked = &x
    leaked

Expected Compiler Diagnostic (non-zero exit):

text
ERROR E5xxx: pointer to zone-allocated value 'x' escapes zone 'z'

21.4 C ABI Interoperability (extern record, extern union, packed)

C Translation Unit (math_c.c):

c
#include <stdint.h>

typedef struct { int64_t x; int64_t y; } Vec2C;
typedef union { uint32_t bits; float f; } FloatBits;

Vec2C c_add_vec2(Vec2C a, Vec2C b) {
    Vec2C out = { a.x + b.x, a.y + b.y };
    return out;
}

float c_next_float_bits(FloatBits v) {
    v.f += 1.0f;
    return v.f;
}

Stag Caller (main.stag):

stag
use kit.io (Console)

extern record Vec2C:
    x: i64
    y: i64

extern union FloatBits:
    bits: u32
    f: f32

extern func c_add_vec2(a: Vec2C, b: Vec2C) -> Vec2C
extern func c_next_float_bits(v: FloatBits) -> f32

func main() -> i32:
    v := c_add_vec2(Vec2C { x: 10, y: 20 }, Vec2C { x: 5, y: 7 })
    f := c_next_float_bits(FloatBits { bits: 1065353216u32 }) // IEEE-754 1.0f32
    msg := f"vec=({v.x},{v.y}) next_f={f}"
    Console.println(msg.as_str())
    0i32

Commands & Expected Output:

text
$ clang -O2 -c math_c.c -o math_c.o
$ stagc main.stag math_c.o -O2 -o c_interop && ./c_interop
vec=(15,27) next_f=2

21.5 Built-In Test Runner (--test) Input/Output Contract

Input (math_unit.stag):

stag
use kit.check
use kit.math

test "gcd and lcm identities":
    check.eq_i64(math.gcd_i64(48, 18), 6, "gcd(48, 18)")
    check.eq_i64(math.lcm_i64(12, 18), 36, "lcm(12, 18)")

test "clamp enforces bounds":
    check.eq_i64(math.clamp_i64(-5, 0, 10), 0, "lower clamp")
    check.eq_i64(math.clamp_i64(42, 0, 10), 10, "upper clamp")

Command & Expected Output:

text
$ stagc --test -O2 --no-color math_unit.stag
[PASS] gcd and lcm identities
[PASS] clamp enforces bounds
Summary: 2 passed, 0 failed (total 2) in 24.1 ms.
  • Each test block runs in a crash-isolated child process so a trap or signal in one test never aborts subsequent test cases.
  • Use --list to print discovered test names, --filter <substr> to select a subset, and --fail-fast to halt on the first failure.

22. Diagnostic Code Reference & Editor Integration

22.1 Diagnostic Code Taxonomy

All diagnostics emitted by stagc and stag-lsp belong to a stable, phase-partitioned code space. Pass --Werror to treat all warnings as fatal errors.

RangePhaseExamples
E1000–E1999Lexer & ParserInvalid token literal, mismatched indentation level, unexpected token, unclosed delimiter
E2000–E2999Semantic AnalysisUndefined identifier (E2015), argument count mismatch (E2025), unknown module alias (E2024), invalid inline asm (E2050–E2056), missing method (E2085), unsupported target calling convention (E2098), generic inference failure (E2102)
E3000–E3999Module LoaderModule file not found, cyclic module dependency, duplicate import binding
E4000–E4999Constant EvaluationNon-constant initializer in const/static, compile-time overflow or division by zero
E5000–E5999Memory & Move AnalysisUse-after-move of owned value, pointer escaping lexical zone or local stack frame
E6000–E6999Style & Formatterformat.json naming/annotation violation, formatter syntax/round-trip error
E8000–E8999Backend & LinkerTarget machine creation failure (E8002), object/asm write error (E8003–E8005), missing linker (E8006), linker failure (E8007), parallel runtime compilation failure (E8012)
E9000–E9999Internal VerificationPost-codegen or post-optimization LLVM IR verification failure (E9001–E9002)
W1000–W5999General WarningsUnused locals/parameters/imports, unreachable statements, implicit narrowing notices
W6001–W6008Hint ContradictionsContradictory @inline, @hot/@cold, @likely/@unlikely, @pure, @vectorize, @unroll, or @parallel annotations

22.2 Visual Studio Code Extension

The official Visual Studio Code extension is published on the Visual Studio Marketplace under identifier stag-lang.stag-lang: