ES
Wysna Handbook

Complete Syntax & Language Reference (v1.1)

Exhaustive reference for every Wysna 1.1 keyword, type, literal, operator precedence, loop, exhaustive match pattern, contract, ARC+CoW rule, module import, C FFI signature, and hard compiler limit.

This page is the complete, single-file syntax and semantics reference for Wysna 1.1, synchronized directly with the normative specification (SPEC.md) and both compiler engines (Selfhost Native SDK and Python Seed).


  • Line comments: # ... runs until the end of the line.
  • Automatic statement termination (ASI): Newlines outside (...) and [...] end statements automatically. You may also separate statements explicitly with ;.
  • Line continuations: Binary operators continuing an expression across lines must sit at the end of the preceding line (a +\n b).
  • Leading unary minus pitfall ([W6001]): Placing -x at the start of a new line after a call or expression (f()\n-x) parses as two statements and emits warning W6001. Wrap multiline arithmetic in parentheses (...).
Category Keywords
Declarations (11) fn, let, mut, struct, enum, import, from, use, pub, priv, extern
Object-Oriented (6) class, interface, extends, implements, this, super
Control Flow (10) if, elif, else, for, while, in, match, return, break, continue
Boolean Literals (2) true, false
Logical Operators (3) and, or, not
  • Contextual / Prelude Identifiers (valid as type or builtin names, not reserved keywords): int, float, u8, bool, str, unit, Some, None, Ok, Err, Weak, opaque, print, len, enumerate, dict_items, int, float, str, ord, chr, slice, join_strings, bytes, args, read_file, write_file, exit, weak, upgrade.

Type Syntax & Literals Key Semantics & Constraints
int 42, 1_000_000, 0xFF, 0b1010_0101 Signed 64-bit two’s-complement (i64) with wrapping +, -, *. / 0 and % 0 trap deterministically (W4001). No i32/u32/u64/BigInt or octal literals.
u8 0..=255 integer literal coercion or u8(x) -> u8? Unsigned 8-bit integer. list[u8] uses a compact packed byte representation in memory.
float 3.14, -0.5 (always require digits on both sides of .) IEEE-754 binary64. NaN != NaN is true, all other NaN comparisons are false. / 0.0 traps (W4001). Cannot be used as a dict key (W2010). No .5, 1., or 1e5.
bool true, false Conditions (if, elif, while, guards) require an explicit bool; no implicit truthiness.
str "hello\n\u{1F680}", """multi\nline""", f"x={x}", f"""...""" Immutable UTF-8 text. len(s) returns Unicode scalar count; s[i] indexes scalar str; bytes(s) returns list[int] raw UTF-8 bytes. Relational </>/<=/>= are disallowed on str.
unit Implicit or () Absence of a value. Functions omitting -> Type default to -> unit. Bare return allowed.
T? Some(val) / None Explicit non-null opt-in. Unwrap with ? in a -> R? function, or coalesce with opt ?? fallback.
T ! E Ok(val) / Err(e), multi-error T ! E1 | E2 Typed recoverable error channel. Unwrap/propagate with ? or recover inline with expr else err { ... }. Cannot hold collections, tuples, fn, T?, T ! E, or unresolved generics (W2001).
list[T] [1, 2, 3], empty let xs: list[int] = [] Copy-on-Write dynamic array. Methods: .append(v), .pop(), .clear(), .contains(v), .is_empty().
dict[K, V] {"a": 1}, empty let m: dict[str, int] = {} Insertion-ordered CoW hash map. Allowed keys K: int, str, bool, enum, or tuple of valid keys. d[k] traps (W4002) if missing; d.get(k) -> V? is safe. Other methods: .contains(k), .is_empty(), .keys(), .values(), .items().
(T1, T2) (1, "ok"), () (tuple[T1, T2]) Immutable fixed-length tuple. Index positionally (.0, .1) or destructure (let (a, b) = pair).
struct Point { x: 1, y: 2 }, spread Point { x: 9, ..base } Pure CoW value record with structural equality (==). All fields must be initialized or supplied via ..base (evaluated once left-to-right).
enum Shape.Circle(1.5), Status.Pending Tagged algebraic union checked exhaustively in match.
class User("alice", 42) Heap-allocated ARC reference object. Supports single inheritance (extends), multi-interface implementation (implements), Weak[C], and reference identity ==.
Weak[C] weak(obj) / upgrade(w) -> C? Non-owning weak reference for breaking ARC retain cycles ([W6002]).
opaque Returned/passed via extern "C" or host handles Opaque foreign pointer (void*).

3. Operators, Precedence & Omitted Operators

Section titled “3. Operators, Precedence & Omitted Operators”

Expressions evaluate strictly left-to-right across all function calls, binary operators, assignments, and composite literals.

Precedence Operators Notes
1 (highest) (...), (a, b) Grouping & tuple construction
2 ., [], (), ?, else { ... }, else err { ... } Member access, indexing, call, propagation, inline recovery
3 await expr Unary prefix; await f()? parses as (await f())?
4 - (unary), not Negation and logical NOT
5 *, /, % Multiplicative (/ and % trap on 0 via W4001)
6 +, - Additive (+ also concatenates str)
7 a..b, a..=b Ascending +1 ranges (.. exclusive, ..= inclusive)
8 <, <=, >, >=, in Ordered comparison (int/float/u8) & membership (x in col)
9 ==, != Value equality for primitives/tuples/structs/enums; identity for class
10 and Short-circuit logical AND
11 or Short-circuit logical OR
12 ?? Optional coalescing on T?
13 (lowest) =, +=, -=, *= Assignments (require let mut binding; W3001 if immutable)
  • Bitwise operators: no &, |, ^, ~, <<, >> (| is only used in error unions T ! E1 | E2 and match alternatives 1 | 2).
  • Increment/decrement & extra compound ops: no ++, --, **, /=, %=.
  • Ternary conditional: no cond ? a : b — use inline if cond { a } else { b }.
  • Operator overloading: not supported.

let immutable = 10 # Type inferred as int; immutable by default
let explicit: float = 3.14
let mut counter = 0 # Mutable binding
counter += 5
let empty_nums: list[int] = [] # Explicit type required for empty collections
let empty_map: dict[str, int] = {}
let (host, port) = ("127.0.0.1", 8080)
pub let (API_VER, MAX_RETRIES) = ("v1", 3) # Exported immutable tuple binding

Trying to reassign an immutable binding emits diagnostic [W3001], which wysna fix --apply can automatically convert to let mut.


5. Control Flow (if, for, while, break, continue, return)

Section titled “5. Control Flow (if, for, while, break, continue, return)”
fn label_temp(c: int) -> str {
if c <= 0 {
return "freezing"
} elif c < 20 {
return "cool"
} else if c < 30 {
return "warm"
} else {
return "hot"
}
}
# Inline value form
let status = if ok { "ready" } else { "blocked" }

for iterates only over list[T], numeric ranges (a..b / a..=b), enumerate(list), dict[K, V], or dict_items(dict):

for i in 0..5 { # 0, 1, 2, 3, 4
print(i)
}
for i in 1..=5 { # 1, 2, 3, 4, 5
print(i)
}
let tags = ["alpha", "beta"]
for tag in tags {
print(tag)
}
for idx, tag in enumerate(tags) {
print(idx, tag)
}
let scores = {"ana": 10, "luis": 20}
for name, pts in scores {
print(name, pts)
}
  • Loop bindings are always immutable.
  • for ch in my_str is invalid (W2001). Iterate over scalar indices (for i in 0..len(s) { let ch = s[i] }) or bytes (for b in bytes(s)).
  • Ranges advance strictly ascending by +1 (start >= end runs 0 iterations). Creating or iterating a range larger than 100_000_000 elements or ending with ..=9_223_372_036_854_775_807 (INT64_MAX) traps with W4003. Use while for reverse loops, custom step sizes, or >100M iterations.
  • There is no C-style for (;;), do ... while, loop, or labeled break/continue.
fn countdown_skip_even(start: int) -> int {
let mut n = start
let mut sum = 0
while n > 0 {
n -= 1
if n == 1 {
break
}
if n % 2 == 0 {
continue
}
sum += n
}
return sum
}

Every match expression must cover all possible shapes statically ([W2003] lists uncovered families). Unreachable arms emit [W6003].

struct Point {
x: int
y: int
}
enum Event {
Tick(int),
Move(Point),
Close,
}
fn describe_number(x: int) -> str {
return match x {
0 => "zero",
1 | 2 => "one or two",
3..=9 => "single digit",
v if v < 0 => "negative",
_ => "large",
}
}
fn handle_event(ev: Event) -> str {
return match ev {
Event.Tick(0) => "tick-0",
Event.Tick(n) => f"tick-{n}",
Event.Move(Point { x: 0, y }) => f"vertical-{y}",
Event.Move(Point { x, .. }) => f"move-x-{x}",
Event.Close => "closed",
}
}
fn match_tuple(pair: (int, int)) -> str {
return match pair {
(0, 0) => "origin",
(x, 0) => f"x={x}",
(_, y) => f"y={y}",
}
}
  • Guards (if cond) filter a matched arm at runtime and do not satisfy static exhaustiveness by themselves.
  • Tuple patterns require parentheses ((a, b)). Both _ => and * => match any remaining value.

7. Functions, Lambdas, Contracts & Static Attributes

Section titled “7. Functions, Lambdas, Contracts & Static Attributes”
pub struct Route {
method: str
path: str
}
@Route(method: "POST", path: "/orders")
@must_use
pub fn apply_discount(price_cents: int, pct: int) -> int
requires price_cents >= 0, pct >= 0 and pct <= 100
ensures result >= 0 and result <= price_cents
{
let discount = (price_cents * pct) / 100
return price_cents - discount
}
@deprecated("Use apply_discount instead")
pub fn old_discount(price_cents: int) -> int {
return apply_discount(price_cents, 10)
}
  • Generics & bounds: fn max_by[T: Show](a: T, b: T) -> str { ... }.
  • Lambdas: Single-expression |x: int| => x * 2 or block |a: int, b: int| -> int { return a + b }. Outer bindings are captured as immutable snapshots (mutating a captured variable inside a closure fails with W3001).
  • Contracts: requires runs on entry; ensures binds the return value as result and runs on normal returns. Failures trap cleanly with [W4005].
  • Built-in attributes: @must_use (W6005 when return value is ignored), @deprecated("reason") (W6004 on call sites), plus user-defined @StructName(field: lit) metadata exposed via wysna inspect / wysna schema.

8. Records (struct), Sum Types (enum) & OOP (class, interface)

Section titled “8. Records (struct), Sum Types (enum) & OOP (class, interface)”
interface Printable {
fn label() -> str
}
class Entity {
pub id: int
fn init(id: int) {
this.id = id
}
}
class Account extends Entity implements Printable {
pub owner: str
priv balance_cents: int
fn init(id: int, owner: str, balance_cents: int) {
super.init(id)
this.owner = owner
this.balance_cents = balance_cents
}
pub fn label() -> str {
return f"{this.owner}#{this.id}"
}
}
struct Port {
value: int requires value >= 1 and value <= 65535
}
  • Class constructors must be named fn init(...) (W3004, autofixed by wysna fix). Subclasses must call super.init(...).
  • Weak references: Break retain cycles between classes using Weak[Node] via let w = weak(node) and match upgrade(w) { Some(n) => ..., None => ... }. Cyclic strong references emit [W6002].

9. Nullability (T?) & Error Channels (T ! E)

Section titled “9. Nullability (T?) & Error Channels (T ! E)”
enum ConfigError {
MissingKey(str),
InvalidPort,
}
fn parse_port(raw: str?) -> int ! ConfigError {
let text = raw else {
return Err(ConfigError.MissingKey("PORT"))
}
if text == "0" {
return Err(ConfigError.InvalidPort)
}
return Ok(8080)
}
fn boot() -> int ! ConfigError {
let port = parse_port(Some("8080"))? # Propagates Err(ConfigError)
return Ok(port)
}
fn boot_with_default() -> int {
return parse_port(None) else err {
eprint("Config warning:", err)
3000
}
}
  • ? inside a -> T ! E function unwraps Ok(v) or returns Err(e) early (and widens into compatible error unions E1 | E2).
  • ? inside a -> T? function unwraps Some(v) or returns None early.
  • expr ?? fallback evaluates fallback lazily only when expr is None.

10. Concurrency (async fn, await & CPU Workers)

Section titled “10. Concurrency (async fn, await & CPU Workers)”
import "std/async"
async fn fetch_metric(seed: int) -> int {
return seed * 2
}
fn pure_worker(x: int) -> int {
return x * x
}
fn main() -> unit {
let a = await fetch_metric(21)
let task = std.async.spawn(pure_worker, 12)
print(a, task.wait())
}
  • async fn lowers to deterministic stackless CPS coroutines.
  • CPU workers (std/async.spawn, std/async.run_group, std/algorithms.parallel_*) isolate memory by deep-copying pure values up to depth 256 (W4003) and reject class, interface, Weak[T], opaque handles, extern "C", and nested worker spawns (W2014 / W2015).

# Standard library (26 std/* modules)
import "std/json"
import "std/text" as txt
from "std/path" use { join, basename }
# Local modules relative to sources.root or current file
import "./router"
from "./helpers" use parse_id
# Installed dependencies from wysna.toml [dependencies.<alias>]
import "pkg/http-router/lib" as router
from "pkg/http-router/router" use { Router, route }
# Re-exporting modules cleanly from a package barrel (src/lib.wysna)
pub import "./router"
  • Top-level declarations are module-private by default. Use pub to export and priv for explicit encapsulation inside classes ([W3002]).
  • For creating, publishing, and installing reusable packages (wysna init --lib, wysna add, wysna install), see the Packages, Libraries & Frameworks Guide.

extern "C" fn sqlite3_libversion() -> str
extern "C" fn add_i32(a: int32, b: int32) -> int32
  • Allowed FFI types: int, int32, int64, float, double, bool, u8, str, opaque, unit.
  • Native compilation links external libraries with --include-dir, --link, --library-dir, and --library. FFI is rejected in wasi-command and browser-library (W2013). See C FFI & External Libraries.

13. Diagnostic Code Families & Built-in Prelude

Section titled “13. Diagnostic Code Families & Built-in Prelude”
Code Family Scope
W0xxx Lexical & syntax diagnostics (W0001–W0006; up to 100 errors recovered per parse)
W1xxx Symbol lookup, duplicates, module resolution/cycles, ambiguous names (W1001–W1005)
W2xxx Type checking, non-exhaustive match (W2003), arity (W2005), dict keys (W2010), workers (W2014/W2015)
W3xxx Immutability (W3001), visibility (W3002), OOP/interface contracts (W3003), fn init (W3004)
W4xxx Deterministic runtime traps: div/mod zero (W4001), bounds/missing key (W4002), panic (W4003), quota (W4004), requires/ensures (W4005)
W5xxx Toolchain, CLI usage (W5002), I/O (W5003/W5004), stale lock/hash (W5005), sandbox policy (W5006)
W6xxx Static lints (W6001–W6005) & checked architecture contract rules (W6101/W6102)

Full searchable catalog: Diagnostic Error Codes (Wxxxx).