Language Design (wings-lang)

actor / struct / state syntax, static immutable value types, non-blocking ask/tell, send_after timers, and monitor notifications.

wings-lang is a statically typed language tailored for stateful microprocesses: all business values are immutable, actors interact exclusively via asynchronous messages, there is no shared mutable memory, and handlers never block on selective receive or synchronous await.

Evolution Note: During 0.0.x, syntax and built-ins evolve directly toward clarity and conciseness without retaining legacy transitional forms.

Complete Example: Multi-Actor Session Service

The following example (from examples/session-service.wings) demonstrates shared struct definitions, nullable pid<Actor> state, spawn, monitor, send_after, and asynchronous .ask reply callbacks:

struct SessionCommand {
  session_id: int,
  prompt: str,
}

struct SessionStatus {
  alive: bool,
  turns: int,
  restarts: int,
  ticks: int,
  last_reply: str,
}

actor SessionWorker {
  state turns = 0
  state parent: pid = null

  on attach(owner: pid) -> pid {
    parent = owner
    self
  }

  on step(cmd: SessionCommand) -> str {
    if cmd.prompt == "boom" {
      let _ = 1 / 0
    }
    turns += 1
    f"s{cmd.session_id}#{turns}:{cmd.prompt}"
  }

  on ping_parent {
    if !parent.is_null() {
      send_after(5, noop)
    }
  }

  on noop {}
}

actor SessionManager {
  state worker: pid<SessionWorker> = null
  state bound_ok = false
  state turns = 0
  state restarts = 0
  state ticks = 0
  state last_reply = "idle"

  on boot -> bool {
    if worker.is_null() {
      let w = spawn(SessionWorker)
      worker = w
      w.monitor(on_worker_down)
      let _ = w.ask(attach(self), timeout: 500, then: on_attached)
      send_after(10, heartbeat)
    }
    true
  }

  on heartbeat {
    ticks += 1
  }

  on reply on_attached(id: req, status: int, who: pid) {
    if status == 0 && who == worker {
      bound_ok = true
      worker ! ping_parent
    }
  }

  on on_worker_down(dead: pid<SessionWorker>, reason: int) {
    if dead == worker && reason != 0 {
      restarts += 1
      let next = spawn(SessionWorker)
      worker = next
      next.monitor(on_worker_down)
      let _ = next.ask(attach(self), timeout: 500, then: on_attached)
    }
  }

  on dispatch(cmd: SessionCommand) -> bool {
    if worker.is_null() {
      false
    } else {
      let _ = worker.ask(step(cmd), timeout: 500, then: on_step_done)
      true
    }
  }

  on reply on_step_done(id: req, status: int, text: str) {
    if status == 0 {
      turns += 1
      last_reply = text
    } else {
      last_reply = f"err:{status}"
    }
  }

  on status -> SessionStatus => SessionStatus {
    alive: !worker.is_null() && bound_ok,
    turns: turns,
    restarts: restarts,
    ticks: ticks,
    last_reply: last_reply,
  }
}

Type System

Type Description Bounds & Semantics
int 64-bit signed integer (i64) Checked add/sub/mul/neg/div/rem; overflow or division by zero triggers a managed fault rather than wrapping
bool Boolean true / false Supports !, short-circuit && / ||, and == / !=
unit / () Unit value () Result type of one-way handlers and unit expressions
str Immutable UTF-8 string 0..=64 KiB per value; supports escapes, f"..." interpolation, ++, equality, and Unicode scalar .len() / .at(i) / .slice(start, len)
bytes Immutable byte buffer 0..=64 KiB per value; supports bytes.fill(len, byte), .len(), .get(i), .set(i, b), 64-bit endian reads/writes, slicing, and concatenation
[int] Immutable persistent i64 list Supports [a, b, ..tail], .is_empty(), .head(), .tail(), .prepend(v); up to 64 elements across message/reply boundaries
struct Top-level shared or actor-local record Nominal typing; up to 32 schemas per actor and 8 fields per schema; supports named literals and Struct { field: v, ..base } functional updates
pid / pid<Actor> Untyped / statically typed process handle (nullable) Accepts null, supports .is_null() and == / != comparison
req Async request correlation token Returned by .ask and matched inside on reply completion handlers

State, Functions & Control Flow

  • Multiple state Bindings: Each actor may declare up to 8 state fields (with type inference from initializers). Assignments during a handler mutate candidate state only; state updates and replies commit atomically only on normal handler return, preserving prior committed state on arithmetic faults, quota exhaustion, or budget cancellation.
  • Statements & Expressions: Statements separate via newlines or ;; supports let bindings, nested struct field updates, if / else if / else, while loops, pipe expressions x |> fn_call(arg), and compound assignments (+=, -=, *=, /=, %=, ++=).
  • Managed Functions & Bounded Recursion: Actor-local fn items operate on parameters, local bindings, and sibling fn calls (without implicitly mutating actor state), supporting both direct and mutual recursion. Every call validates remaining native stack space and execution step budgets while maintaining exact cross-frame GC roots.

Messaging, Timers & Monitoring

  • One-Way Casts vs. Typed Requests:
    • on msg(args...) { ... } (without ->) accepts asynchronous one-way casts;
    • on msg(args...) -> ReplyType { ... } (including -> ()) handles request-reply calls, with on msg -> T => expr shorthand for single-expression handlers.
  • Cross-Actor Operations:
    • spawn(TargetActor) creates a child actor and returns pid<TargetActor> (self refers to the current actor).
    • target ! msg(args...) or target.tell(msg(args...)) enqueues a non-blocking one-way message.
    • target.ask(msg(args...), timeout: ms, then: on_done) issues a non-blocking request and delivers on reply on_done(id: req, status: int, value: ReplyType) upon completion, failure, or timeout.
  • Timers, Monitors & Hostcalls:
    • send_after(delay_ms, msg(args...)) schedules a delayed one-way message to self.
    • target.monitor(on_down_handler) (or monitor(target_pid, on_down_handler)) returns (), watches a target actor, and delivers on_down_handler(dead: pid<TargetActor>, reason: int) once if the target has already exited or terminates later.
    • hostcall(capability, payload, timeout_ms) -> bytes invokes an explicitly granted host capability from inside a handler under quota, payload-size, and timeout bounds.
  • Effect Commit Boundary: spawn, ! / .tell, .ask, send_after, monitor, and hostcall take effect and charge quotas immediately at the call site; if the handler subsequently faults, already-dispatched messages and spawned children are not rolled back (no cross-process distributed transactions).

Next-Stage Syntax Evolution Design (0.1 Plan, Not Yet Implemented)

Status Note: This section specifies the planned 0.1 syntax evolution for wings-lang. None of the features below are implemented in the compiler or runtime yet; the sections above describe the currently verified 0.0.x subset enforced in CI.

Design Principles & Non-Goals

  1. Preserve Runtime Invariants: All business values remain immutable with zero shared mutable memory across actors; every new value representation must support bounded, exact GC root scanning and cross-message boundary validation.
  2. Keep the Non-Blocking Event Model (Non-Goal): Wings will not add blocking selective receive or synchronous await. Handlers never hold native coroutine stacks across remote waits, preserving 100% stack-pool return for idle microprocesses and keeping resident memory low.
  3. Keep the Surface Area Restrained (Non-Goal): Wings will not add traits/inheritance, macro systems, implicit type coercions, or complex lifetime annotations; syntax additions focus strictly on high-frequency, statically verifiable stateful-actor patterns.
  4. Zero Legacy Baggage: As 0.1 features land, transitional 0.0.x forms (raw status: int in on reply, implicitly nullable pid<Actor> = null, let _ = 1 / 0 fault triggers) are removed outright rather than maintained in parallel.

Phased Feature Specification

Phase 1: Ergonomic Foundation (Frontend / IR / LSP)

Removes recurring boilerplate and fragile idioms without changing the managed C ABI or VM heap layout:

Feature Syntax Example Semantics & Compile-Time Rules
struct field shorthand SessionStatus { alive, turns, ..prev } Omits : name when a field matches a binding of the same name in scope; orthogonal to ..base functional updates
Duration literals 10ms, 500ms, 2s, 1m Folded at compile time into checked int millisecond constants for send_after, .ask(..., timeout: ...), and supervisor windows; zero runtime cost
Managed fault primitive fail fail("invalid prompt") Replaces let _ = 1 / 0; has never type ! (valid in any expression branch), rolls back uncommitted state, keeps already-sent effects, and attaches a bounded diagnostic string
List iteration for for item in items { ... } Read-only traversal over immutable lists; lowered in frontend/IR to a safepoint-checked while loop with zero iterator heap allocation

Phase 2: Type-Safety Leap (ADTs, Exhaustive Matching & No Magic Numbers)

Eliminates ad-hoc boolean flags and raw status == 0 / reason != 0 integer codes from actor state machines:

  1. Algebraic Data Types (enum):
    • Supports unit variants and payload variants (named or positional):
      enum WorkerState {
        Idle,
        Busy(req_id: req, started_at: int),
        Crashed(reason: ExitReason),
      }
    • Bounded by schema and field limits aligned with struct; stored on the managed heap as tagged fixed-layout records so the exact GC scans active reference fields by tag.
  2. Exhaustive match Expressions:
    • Pattern destructuring and binding over enum, T?, bool, and int with mandatory compile-time exhaustiveness and reachability checking:
      match res {
        Reply.Ok(text) => { turns += 1; last_reply = text }
        Reply.Timeout => { last_reply = "timeout" }
        Reply.Failed(reason) => { last_reply = f"failed:{reason}" }
        _ => { last_reply = "unavailable" }
      }
  3. General Nullable Types T? & Null Coalescing ??:
    • Replaces implicitly nullable pid<Actor> = null with explicit T? across arbitrary value types (e.g. pid<SessionWorker>?, str?, int?), supporting null, if let x = opt, match, and short-circuit opt ?? fallback.
  4. Typed Reply<T> and ExitReason:
    • Replaces raw integer status codes in on reply with on reply on_done(id: req, res: Reply<T>) using built-in enums:
      enum Reply<T> {
        Ok(T),
        Timeout,
        Dead,
        Failed(ExitReason),
        MailboxFull,
      }
      
      enum ExitReason {
        Normal,
        Fault(str),
        OutOfMemory,
        BudgetExceeded,
        Killed,
      }
    • Upgrades monitor down handlers to on on_worker_down(dead: pid<SessionWorker>, reason: ExitReason).

Phase 3: Multi-File Module System (Roadmap M1)

Scales wings-lang from single-file programs to modular multi-file applications integrated with build-app and wings-lsp:

  • Private-by-Default + pub Exports: Top-level struct, enum, actor, and fn items are file-private unless marked pub.
  • Static Explicit import:
    import "./types.wings" { SessionCommand, SessionStatus }
    import "./worker.wings" { SessionWorker }
  • Acyclic Module Graph: Import cycles are rejected at compile time; modules are resolved in topological order with zero dynamic runtime loading overhead.
  • Toolchain Integration: Multi-file source tables in wings-source, cross-module resolution in wings-sema, cross-file go-to-definition/diagnostics in wings-lsp, and automatic dependency discovery from entry files in build-app.

Phase 4: Parameterized Spawn, Declarative Supervision & Generic Lists (Roadmap M2)

Eliminates post-spawn half-initialized windows (boot / attach handshakes), replaces manual monitor restart boilerplate, and generalizes list payloads:

  1. Parameterized spawn (Actor Constructor Arguments):
    • Actors declare immutable constructor parameters usable directly in state initializers:
      actor SessionWorker(owner: pid<SessionManager>) {
        state parent = owner
        state turns = 0
      }
    • Callers write spawn(SessionWorker(self)); constructor arguments undergo cross-message validation and quota accounting so the child starts fully initialized.
  2. Declarative supervisor Trees:
    • Replaces hand-rolled monitor + restart counters with declarative supervision specs lowered directly to wings-vm’s bounded restart engine:
      supervisor SessionSupervisor {
        strategy: one_for_one
        max_restarts: 5
        within: 30s
      
        child worker: SessionWorker(self) restart: transient
      }
    • Supports one_for_one / one_for_all strategies and permanent / transient / temporary child restart policies, propagating termination upward when restart intensity exceeds the configured window.
  3. Generic Immutable Lists [T]:
    • Generalizes [int] to [T] for any managed value type (e.g. [str], [SessionCommand], [pid<SessionWorker>]), preserving persistent list semantics, cross-message element bounds, and exact GC traversal.

Before / After Preview (SessionService in 0.1 Target Syntax)

Rewriting the session service example from the top of this page using the planned 0.1 syntax:

pub struct SessionCommand {
  session_id: int,
  prompt: str,
}

pub struct SessionStatus {
  alive: bool,
  turns: int,
  restarts: int,
  ticks: int,
  last_reply: str,
}

pub actor SessionWorker(owner: pid<SessionManager>) {
  state parent = owner
  state turns = 0

  on step(cmd: SessionCommand) -> str {
    if cmd.prompt == "boom" {
      fail("boom requested")
    }
    turns += 1
    f"s{cmd.session_id}#{turns}:{cmd.prompt}"
  }
}

pub actor SessionManager {
  state worker: pid<SessionWorker>? = null
  state turns = 0
  state restarts = 0
  state ticks = 0
  state last_reply = "idle"

  on boot -> bool {
    if worker == null {
      let w = spawn(SessionWorker(self))
      worker = w
      w.monitor(on_worker_down)
      send_after(10ms, heartbeat(1))
    }
    true
  }

  on heartbeat(delta: int) {
    ticks += delta
  }

  on dispatch(cmd: SessionCommand) -> bool {
    if let w = worker {
      w.ask(step(cmd), timeout: 500ms, then: on_step_done)
      true
    } else {
      false
    }
  }

  on reply on_step_done(id: req, res: Reply<str>) {
    match res {
      Reply.Ok(text) => {
        turns += 1
        last_reply = text
      }
      Reply.Timeout => { last_reply = "err:timeout" }
      Reply.Failed(reason) => { last_reply = f"err:{reason}" }
      _ => { last_reply = "err:unavailable" }
    }
  }

  on on_worker_down(dead: pid<SessionWorker>, reason: ExitReason) {
    match reason {
      ExitReason.Normal => {}
      _ => {
        if worker == dead {
          restarts += 1
          let next = spawn(SessionWorker(self))
          worker = next
          next.monitor(on_worker_down)
        }
      }
    }
  }

  on status -> SessionStatus => SessionStatus {
    alive: worker != null,
    turns,
    restarts,
    ticks,
    last_reply,
  }
}

Implementation Sequence & Crate Boundaries

All phases strictly preserve the acyclic workspace graph (wings-lsp never depends on IR/Cranelift/VM; wings-vm never depends on frontend/sema/IR/Cranelift/wings-compile):

Phase Target Milestone Primary Crates Core Acceptance Criteria
Phase 1 0.1-alpha wings-syntax, wings-sema, wings-ir, wings-lsp End-to-end tests and LSP completion/diagnostics for field shorthand, duration literals, fail, and for with zero extra runtime allocations
Phase 2 0.1-beta Full compiler pipeline + wings-abi, wings-vm Exact GC root verification for enum payloads, static exhaustiveness checks for match, and migration of existing examples to Reply<T> / ExitReason
Phase 3 M1 wings-source, wings-syntax, wings-sema, wings-compile, wings-lsp Topological multi-file import/pub compilation, import-cycle rejection, cross-file LSP diagnostics, and build-app multi-file bundling
Phase 4 M2 Full compiler pipeline + wings-abi, wings-vm Quota-checked parameterized spawn, bounded restart verification for declarative supervisor trees, and exact GC / cross-message codec for [T]