Skip to content

The language ​

From the spec

This page is spec/language.md, the specification the compiler and the backends are written from. It is rebuilt from the spec with every deploy (how).

Weft is markup-kit's language: one statically typed language for a component's code, its {expressions} and its handlers, for modules, and for server code. It reads like TypeScript and behaves like values in Rust or Swift: every value is a copy, and the only way to change something you don't own is to hand it over with &.

This spec is what the compiler, the JS backend, the VM and conformance/lang/ are written from. Where it says "error", the compiler rejects the program with a diagnostic; where it says "fails", a function gives its caller an error value (Errors); where it says "panics", the program has a bug and the turn ends (Panics). The goals and the architecture are in docs/plan.md.

Files ​

  • A file is .weft, UTF-8 (a byte-order mark is skipped).
  • A component is its Weft code, then a line ---, then its markup (README.md, Markup). The --- line holds only --- (trailing spaces allowed). Either part may be empty: a markup-only component starts with ---, and a component with no markup ends with ---.
  • A module is a file of Weft code only: a file without a --- line.
  • Only the first --- line counts, and only one outside a string or comment; below it, --- is markup text.
  • There is no <script> tag: a .weft file starting with <script> (or <script module>) is an error, and so is <script> in markup.
  • The formatter writes the code, then --- on the line after the code's last line (never a blank line before it), then the markup from the next line, unindented.

Projects, ids and programs ​

  • A project is a directory tree of .weft files whose root holds weft.toml. A file's id is its path from the root without .weft (lib/dates, server/api).

  • weft.toml holds only what tools need before any code runs (weft-check's config.rs); everything else about a project is Weft (its theme is theme.weft, what user code may import is named by the code that runs it). Every key is optional, so an empty file is a project:

    toml
    main = "server/main.weft"   # the program `weft run` runs; an app (routes/) serves without one
    component = "Overlay"       # what a window opens (desktop.md)
    site = "https://example.com" # the app's address, for its sitemap (std/app.md)
    
    [db]                        # std/db (std/db.md, Migrations)
    schema = "db/schema"        # the module exporting the schema, and which export,
    export = "app"              #   when the project exports several
    url = "$DATABASE_URL"       # `$NAME` reads the environment
    live = true                 # std/live's Postgres triggers (std/live.md)
    dialects = ["sqlite", "postgres"]   # what `weft db migrate` writes (all three by default)
    
    [test.replace]              # `weft test` swaps modules by id (Tests)
    "lib/server/db" = "lib/server/db.test"

    The package manager's tables ([package], [dependencies], …) share the file (docs/packages.md). An unknown key is an error, so a typo never drops a setting; tools that write the file edit it in place (toml_edit), keeping its comments and order. A project still holding a weft.json gets an error saying how to move it.

  • Imports name a file by its id ("lib/dates"), relative to the importing file ("./row", "../lib/dates"), or the standard library ("std/http"). A component is imported by its default export: import Row from "./Row"; a capitalised tag names a primitive of the schema or a component in scope.

  • The project's own code reaches the standard library directly: it imports std/http, std/db, std/s3, std/live and std/process as it needs, like any module. Restrictions apply to user code: code an app lets its users write (and plugins, an agent's code) runs through std/sandbox, which loads it (from the app's database, S3 or a mounted tree, or as text), checks it, and runs it with only what that run gives it: the app's components and functions it may use (imports, under the labels it sees them by), the capabilities it is handed (functions scoped to the user's rows, an S3 prefix) and its own fuel, memory and deadline. Sandboxed code can import no I/O module; it reaches only what it was given.

  • Resources live in modules. A module's top level runs once per process and may await, so a connection is made once and imported wherever it's needed; nothing is passed around:

    weft
    // lib/server/db.weft
    import { postgres } from "std/db"
    import { env } from "std/process"
    import { app } from "db/schema"
    export let db = try await postgres(app, env("DATABASE_URL")!)   // a failure fails the module's load
    weft
    // server/main.weft
    import { router, json, serve } from "std/http"
    import { db } from "lib/server/db"
    
    let open = db.as(null)
    let api = router()
      .get("/todos", async req => json(try await open.sql"select id, title, done from todos where shared = {true}"))
    try await serve({ port: 8080 }, api)
  • Running code. weft run <file> runs a file: its top level is the program, so a server is just code that calls serve (above), and a script is code that does its work. weft run on a project runs the entry its weft.toml names (main = "server/main.weft"), or, in an app (a project with routes/), the app framework. weft dev runs the same with hot swap and the development tools (editor-protocol.md). Arguments, the environment and the exit code come from std/process (args(), env(name), exit(code)).

  • Tests can replace a module by id (an in-memory SQLite for lib/server/db), so code that imports resources stays testable without passing them in.

  • The app framework is built in and optional: a project with a routes/ directory is an app, whose pages, layouts, endpoints and component lookup come from where files sit (app.md). Everything in this spec holds with or without it.

Lexical structure ​

  • Comments: // … to the end of the line, /* … */ (not nested). /// before a declaration is its doc comment.

  • Identifiers: Unicode ID_Start (plus $, _) then ID_Continue (plus $, U+200C, U+200D). Names starting with __ are reserved for the runtime: error.

  • Reserved words (never a binding name): as async await break continue defer else export fail false fn for if import in is let match mut null return true try type while, and JS's words Weft doesn't use (const function class enum extends new super this var void with yield delete typeof instanceof switch case default do debugger throw catch finally), so that code moved from JS gets a clear error ("write let", "write fn", "write fail", "use try", "use defer") instead of a confusing one.

  • Contextual words are keywords only where the grammar expects them and names elsewhere: prop bind derived effect query mutation action global context provide from escaping key of test where it (of only after a for pattern; where only after a type; it only inside a where condition).

  • Any word, reserved or not, is a valid field name after . and as a record key (event.type, { for: x }, { constructor: 1 }), except names starting with __ (error, including __proto__). Records have no prototype: a field exists only if the type declares it.

  • Numbers: decimal (1, 1.5, .5, 1e-3), 0x, 0o, 0b, with _ between digits. All are number (IEEE-754 double). No BigInt, no legacy octal.

  • Strings: "…" or '…' with JS's escapes (\n \t \\ \" \' \u{…} \uXXXX \xXX, line continuation). Template strings `a ${expr} b`, no tags.

  • Semicolons are optional. A newline ends a statement when the statement is complete there, except:

    • inside ( ) or [ ];
    • when the line ends with a token that can't end an expression (a binary operator, =, ,, ., ?., (, [, {, =>, :, ?);
    • when the next line starts with ., ?., ?, :, or a binary operator (+ - * / % ** == != < <= > >= && || ?? & | ^ << >> >>> is as).

    A line starting with (, [, !, a string or a template starts a new statement (unlike JS); a resulting expression with no effect is a warning. return, fail, break and continue take their operand on the same line (fail alone is an error), and postfix ++/-- must be on their operand's line. These restrictions win over the continuation rules: return followed by a line starting with + 1 returns nothing (and the next line is an error). The formatter writes no semicolons.

  • Generic calls: f<…>( is a generic call when < type arguments > parse and ( follows immediately; otherwise < is a comparison. This never depends on what f resolves to (the formatter parses without types).

  • Arrows: ( … ) is parsed speculatively as a parameter list; it is an arrow exactly when => follows on the same line. There is no comma operator, so (a, b) alone is an error.

  • Braces: at the start of a statement, right after =>, and after the head of if, else, while, for, match and defer, { opens a block; a record there needs parentheses (x => ({ a: x })).

  • Control flow has no parentheses, and its bodies always have braces: if done { … } else { … }, while busy { … }, for t of todos { … }, match shape { … }. A head ends at the { that opens its body, so a record or named-construction literal at the top level of a head needs parentheses (if t == (Todo { … }) { … }).

  • Ranges: a..b and a..=b; in a slice either end may be left out (xs[..3], s[2..]).

  • Tagged strings: a name (or a . path of names) followed directly by a string, with no space, is a tagged string: sql"select * from todos where id = {id}". Inside a tagged string {expr} interpolates and {{, }} write braces (a lone } is an error); {2,} and {2,5} (digits, a comma, optional digits: no expression reads so) are text, and \p{…}, \P{…} one escape (a regex's repetition and property, std/regex.md); the usual escapes hold, and like any string it ends on its line.

  • Attributes: @name or @name(args) before a record type's field or before a type declaration (@primary @default(uuid) id: string). @deprecated(until: "2027-06-01", use: "heading") also goes before any other top-level declaration (a function, a let, a prop), or before a file's imports, its --- or at its end (the file itself); its arguments are named, both optional, until a YYYY-MM-DD date (user-files.md, Deprecations). In code, @ appears only there.

Syntax details ​

How the parser resolves what the rules above leave open (weft-syntax):

  • A file is a component when one of its lines, outside a string or comment, is --- (trailing spaces or tabs allowed, a \r\n ending too), else a module.
  • A fraction needs digits after the dot (1.5, .5): 1.toFixed(2) is a method call on 1, and 1..3 is a range.
  • A contextual word starts a declaration only when what that declaration needs follows on the same line (prop x, prop bind x, derived x, effect {, provide x, global x, context x, query fn, mutation fn, action fn); elsewhere it is a name. let and let mut bind one pattern each (let a = 1, b = 2 is an error).
  • Arrows have no return type annotation ((a): T => … is an error): annotate what they return, or write an fn.
  • else goes on the line of the } it follows (} else {); a line starting with else is an error.
  • Record types separate fields with ,, ; or a line break; the formatter writes ,.
  • A tag is a name directly followed by " or '; from never is one, so import { x } from"id" stays an import.
  • if let takes any pattern, with an optional guard before the =: if let n if n > 2 = count { … }. It is a statement only (in a value, use match); else goes on the line of the } as for if. In let p = e else { … } the else goes on the line of e.
  • A match arm's guard ends at the arm's =>, which never makes an arrow of it: n if ready => … and n if (a || b) => … are guards (in code and in @match).
  • A file's syntax tree nests at most 1,000 deep: brackets, blocks, operators, operator chains (a + b + …, a.b.c…) and tags each add levels. Deeper is one error there, and the rest of that code region (or of the markup) is not parsed, so no later pass walks an unbounded tree (std/sandbox parses user code).
  • where after a type takes the rest of its line as the condition (a record type's field ends at its , or line break), and binds loosest: string | number where … conditions the union. Attributes go before everything else of a declaration: @table("todos") export type Todo = { … }, @primary id: string.
  • A type parameter's bound follows a :: fn f<T: data>(…), type Cache<K: key, V> = Map<K, V>.
  • In a type-test pattern n is T, T has no top-level | (| separates alternatives: n is number | s is string).
  • Inside any markup { … }, line breaks end nothing.
  • try is a prefix operator over a unary expression, taking a following as T into its operand: try await t, try f().g(), try x as T; try f() + 1 is (try f()) + 1. else goes on the line of its operand, and its fallback reaches as far right as an expression does (try f() else 0 + 1 falls back to 1); else e => expr binds the error (the fallback is an expression, not a block). fail takes the rest of its line as its operand.
  • let a, b = try f() (a declaration with two names, or _, before the =) is the two-binding form; let mut a, b makes both writable. R ! E is the loosest type operator: A | B ! C | D is (A | B) ! (C | D), and a function type's result takes it whole ((x: T) => R ! E).
  • Parentheses around a whole head are an ordinary parenthesised expression (if (ready) { … } parses); the formatter drops them unless the head needs them (a record literal at its top level).
  • A range outside a slice needs both ends; a..b..c is an error.
  • In a type alias, Name { … } at the top level of its union is a variant, and so is a bare capitalised name there that names no type in scope (type Toggle = On | Off); anywhere else Name { … } in a type is an error.
  • Markup: @render f(x) ends at the ) closing its call; @let x = e at the end of its line (a line break inside brackets doesn't end it) or a }. Inside a block's { … }, a } in text closes the block unless a tag opened inside the block is still open (write {"}"} for a literal one). @else, @empty, @then and @catch go right after the } they follow (whitespace and line breaks between are allowed); elsewhere they are an error, and so is one written without its @ (} else {). @@ is an escape only before a block's word (@@if shows @if); elsewhere @@ is text as written.

Types ​

typevalues
numberIEEE-754 doubles
stringsequences of UTF-16 code units (lone surrogates allowed)
booleantrue, false
nullnull, the only absence (there is no undefined)
literal types"open", 3, true; only finite numbers make literal types, and -0's type is 0 (the value keeps its sign)
T | Uunions; T? is T | null
T[]lists
[A, B]tuples: fixed length, typed per position
{ a: A, b?: B }records: named fields; b?: B is a field of type B? that a literal may leave out (it is then null)
Map<K, V>, Set<T>insertion-ordered; keys are number, string, boolean, null or literal unions of them, compared as SameValueZero (one NaN key, 0 and -0 the same). A record or list key is an error with a fix-it to a string key
(a: A, mut b: B) => Rfunctions; async (a: A) => R returns Task<R>
query (a: A) => R, mutation (a: A) => R, action (a: A) => Ra server function of that kind (The server), called as a Task<R>
Task<T>an async result
Snippet<[A, B]>a piece of markup taking those parameters (@snippet, shown with @render); Snippet takes none. Not data
Rangea..b (a ≤ i < b) or a..=b, of numbers; iterable, and data ({ start, end, inclusive })
Bytesan immutable sequence of bytes (files, images, HTTP bodies, S3 objects); data; std.md, Bytes
R ! Ea result: what a fallible function or task gives, a value of R or a failure with an E (Errors)
Async<T, E>an async derived value: { pending: boolean, value: T?, error: E? } (Reactivity); Async<T> is Async<T, never>
Partsa tagged string's literal parts (below)
Query<F>a closure received as a typed expression tree (Functions)
jsondynamic data: null, booleans, numbers, strings, json[], string-keyed records of json
Handle<"kind">an opaque host object (a reader, an element), typed by the schema
Error{ name: string, message: string, data: json }
voida function returning nothing; never for one that never returns
  • Data types are the types with no function or Task inside: they can be serialized, converted to json, sent between client and server and stored. Only primitive types can be map keys (above). Handles are data inside one process and can't cross to the server. Functions can be compared (== by identity) but aren't data.

  • Aliases: type Name<P> = T, at the top level, exported with export type. An alias may be recursive when the recursion passes through a list, a map or a ? (type Tree = { value: number, children: Tree[] }, type Node = { next: Node? }); type T = { next: T } has no values and is an error.

  • Postfix type operators bind left to right: string?[] is a list of nullable strings, string[]? a nullable list.

  • Structural typing. Record types are compared by their fields, unions by their members. A record with more fields converts to a record type with fewer: the value is projected to the target's fields (the others are gone, not hidden). Conversion happens only where a value is stored, returned or passed to a parameter of a different record type, and it allocates. Projection applies to records at the top level only; inside a list, map, set or tuple it is an error (fix-it: .map(t => ({ id: t.id }))).

  • Subtyping without projection (a literal type to its base type, a type to a union containing it, T to T?) goes through lists, tuples, maps, sets and function results: 1[] is a number[]. Copies make this covariance sound. Function parameters are contravariant. There is no retroactive widening: a value keeps the type it was given, and an annotation only gives context to the literal it annotates.

  • A record literal with a field the expected type lacks is an error, as in TS. Converting a wider record to a discriminated union projects it to the member its tag selects.

  • No conversion through a borrow. The argument of a mut parameter, the place of a bind: or prop bind, and the list of @for mut must have exactly the declared type.

  • Discriminated unions: a union of records sharing a field of distinct literal types (kind). A union with two or more record members must be discriminated (error otherwise). Testing the tag narrows (below), and the tag decides which member a wider record converts to.

  • Variants are the short way to write one:

    weft
    type Shape = Circle { r: number } | Rect { w: number, h: number } | Empty

    is the union { kind: "Circle", r: number } | { kind: "Rect", w: number, h: number } | { kind: "Empty" }: the same values, in json and on the wire. A variant is made by name (Circle { r: 2 }, Empty) and matched by name (Circle { r } => …); a made variant has its union's type (Shape), as a variant does in Rust or Swift. Variant names are in scope wherever their type is (declared or imported); an unqualified name means the variant of the type the context expects (an annotation, a parameter, a match's value) when that type has one, else the only variant of that name in scope; when two types in scope have it and the context doesn't decide, write Shape.Circle (error otherwise). A variant's name can't also be a type's or a value's (type Taken = Taken is an error; the standard library's one-variant error types, NetworkError { … }, are the exception). Variants of a generic alias are made and matched as records ({ kind: "Some", value: x }) for now.

  • Named construction: a record type alias makes its values by name, Todo { id, title, done: false }: every field of Todo must be given (optional ones may be left out), and no other. It is a record literal checked against Todo, with the error at the field.

  • Validating types add a condition to a type:

    weft
    type Email = string where it.includes("@") && it.length <= 254
    type Age = number where it.isInteger() && 0 <= it && it < 150
    type Signup = { email: Email, age: Age, name: string where it.trim() != "" }

    it is the value; the condition is a pure boolean expression (Reactivity, purity), which may call the module's pure functions. A validating type is a subtype of its base (Email is a string: it shows, compares, slices and converts to json as one); a base value becomes one only through a check: x as Email (fails with a CastError naming the type and the failed field path), x is Email (narrows), or a literal the compiler checks at compile time. Every place a value crosses into a program checks it the same way, all the way down: as from json, a server function's arguments and results, form input, database rows. Conditions nest: a record type's fields check their own.

    Settled details: the base must be data, and a validating type has no type parameters. Two validating types are different types even over one base (an Email isn't a Username); a validating type over another (type Work = Email where it.endsWith("@acme.com")) is a subtype of it and checks both, the inner first. The compile-time check applies to any compile-time constant (a literal, a list or record of them, a constant let): the compiler evaluates the condition when it uses only it, constants, operators, the prelude's pure string, number and list methods, and module functions whose body is one return; otherwise, or when it fails, the literal is an error (fix-it: … as T). as names the type and the path to the failing value in its TypeError (value.age is not a valid Age).

  • Attributes are data the compiler keeps on a type or a field: @name or @name(args), where each argument is a compile-time constant or a name, kept as a reference and never called at the declaration (@default(uuid): the library calls uuid when it needs a default). A library declares the attributes it reads (export attribute default<T>(value: T), export attribute primary); an unknown attribute, or arguments of the wrong type, are errors. They change nothing by themselves: libraries read them at compile time (std/db's schema) or at run time through fields<T>() (std.md), as forms, json renaming and std/ai do.

    Settled details: an argument is a constant (a literal, -n, a template without substitutions, or a list or record of them) or a name (uuid, users.id), kept as the reference <module id>.<name> (prelude.uuid for a prelude name). An attribute's one type parameter, if it has one, is the type of what it is written on (@default(0) on a string field is an error); a reference to a function fits a parameter its result fits (the library calls it). Attributes are their own namespace: @primary names an attribute declared in the file or imported by name (import { primary } from "std/db"), never a value. One site can't have the same attribute twice. Attributes are part of the type (fields<T>() sees them) but change no relation: record types that differ only in attributes are assignable to each other.

  • Generics: fn first<T>(xs: T[]): T? and generic aliases. Type arguments are inferred from the arguments, or written first<string>(xs). Inference reads the arguments and the expected type: a literal argument for a parameter such as [K, V][] is checked as tuples (Map([["a", 1]]) is Map<string, number>), let s: Set<1 | 2> = Set([1]) takes its type argument from the context, and an optional parameter infers like a required one. Without a bound, a generic body can use only what every type supports: passing, storing and ==. is, as, match type tests, showing in a template, and what needs data (json.stringify, conversion to json, map keys, a server function's parameters) are errors on a value of an unbounded type parameter, so implementations can erase generics. Whether one monomorphizes is not observable.

  • Two bounds lift that: T: data (only data types) allows json.stringify and conversion to json, == structurally, fields<T>(), and is/as tests against a concrete data type; T: key (only map-key types, which are primitives) allows all of that plus map keys, set items and showing in a template. fn cache<K: key, V: data>(…). T: animatable (std/motion, motion.md) takes numbers, and records, tuples and lists of them. There are no other bounds and no traits. Server functions stay non-generic. Bounds go on generic aliases' parameters too; a type argument that doesn't meet its bound is an error at the call (or the use), and a data parameter used as a map key is an invalid-key error (bound it key).

  • No any, no unknown, no classes, no interfaces, no enums (variants and unions of literals are the enums).

Inference ​

  • Locals, state and derived values are inferred from their initializer; let x: T = … states it. Literals keep their type: let n = 1 is 1, and fn circle(r: number) { return { kind: "circle", r } } returns { kind: "circle", r: number }, which fits Shape.

  • An unannotated let mut's type comes from its uses in its scope (the function, the component or the module) when its initializer is a literal or a union of literals ("all", 0, c ? "a" : "b", another such let mut):

    • only literals assigned (filter = "done", null): it is their union with the initializer's, so let mut filter = "all" fits Filter where it's passed to label(f: Filter), and let mut open = false with open = true somewhere is boolean;
    • a use that needs an exact type (bind: of it, & of it for a mut parameter, bind: of an @for mut item of it, whose list is then a list of that type) gives that type, when the initializer fits it;
    • otherwise, any other assignment (filter = s, n += 1, n++) widens it to its base type (string, number); an error that widening causes elsewhere is reported at that assignment, with the fix-it to annotate the let mut with the type the use needs.

    A list or record literal of literals (let mut xs = [1], let mut r = { n: 1 }) widens to its base type unless an exact use decides. There are no run-time checks: the uses only decide the type the checker gives the binding. Annotate a let mut to state it: let mut filter: Filter = "all".

  • An empty [], {}, Map() or Set() initialising an unannotated let mut gets its type the same way: from an exact use, then a type expected where it is read (an argument, a return, a prop, an annotated let), then what is added to it (push, unshift, insert, xs[i] = x; a set's add; a map's set and m[k] = v, widened), then a value assigned to it. With nothing in scope to decide it, it is an error with the fix-it : T[] (: T, : Map<K, V>, : Set<T>).

  • let mut x = null is an error asking for a type (let x = null is null). c ? 1 : "a" and if c { 1 } else { "a" } are number | string. Destructuring a list (let [a, b] = xs) gives T? per position; a tuple gives its exact types.

  • Function parameters and props are annotated, except arrow parameters whose type the context gives (xs.filter(t => t.done); a union with exactly one function type in it gives that one, as std/motion's animate(el, (t, dt) => …) does) and props whose default decides their type (prop count = 0 is number).

  • Return types are inferred when omitted, except for recursive functions.

  • [] and {} take their type from context; with none (let xs = []), error: "annotate the list's item type" (a let mut's uses are its context, above).

Narrowing ​

Flow-sensitive, as in TS, over let bindings, parameters and let mut locals not written in between (a let mut local that any closure writes is narrowed only until the next call):

  • x != null / x == null, x is T, x.kind == "circle" on a discriminated union, match arms, if let and let … else (Statements);
  • &&, ||, !, early return/fail/break/continue: after if x == null || c { break }, x isn't null (a false || has every side false, and c is checked with x already narrowed, also when it compares a field of x: if x == null || x.name == "end" { return });
  • a state field or a path into one is narrowed only until the next call or await (they may change it).

Values ​

Every value is a value. Assigning, passing, storing, returning and capturing all give the receiver its own value; changing one never changes another. Implementations share storage and copy only when one side writes (copy-on-write over reference counting; the JS backend uses a sticky "shared" bit), so a copy costs nothing until a write. None of this is observable except as speed. For the JS backend's bit: storing a value in a second place marks it shared, and copying one level marks every value that level contains shared, so a write deeper down copies its own level too.

Consequences, all guaranteed:

  • No aliasing: let mut b = a; b.x = 1 leaves a unchanged. So does pushing a into a list and changing the list.
  • No cycles: a value can't contain itself, so reference counting frees everything, deterministically.
  • No identity: == is structural; there is no === (error, with a fix-it to ==).
  • let is deep: neither the binding nor anything inside the value can change (let xs = [1]; xs.push(2) is an error with the fix-it "make it let mut"). let mut bindings and their contents can.

Places ​

A place is a path that can be written: a let mut local, a mut parameter, a state field, a writable prop (prop bind), a global, followed by any .field, [index] or [key] steps (todos[i].title).

  • Assignment (= += -= *= /= %= **= &= |= ^= <<= >>= >>>= &&= ||= ??=), ++, -- and mutating methods (push, sort, set…) take a place. Assignment, ++ and -- are statements; an arrow whose body is one (() => count += 1) is a void arrow with that statement as its body. A call with a & argument or a mutably borrowed receiver is an expression, whose value is its result (let last = xs.pop()).
  • A &place argument's index steps are evaluated with the other arguments, left to right, and the place is resolved (bounds-checked) when the call begins.
  • Writing xs[i] with i outside 0 … length - 1 or not an integer panics (RangeError); writing a map's key adds it.
  • Writing through a field of null panics (TypeError); the type checker makes this need a ! or a narrowing first.

Parameters: borrows ​

RustWeftat the callin the callee
&Tx: T (the default)f(a)read-only: can't be assigned or changed
&mut Tmut x: Tf(&a), a a placechanges go to the caller's place, in place
owned—storing, returning or capturing a parameter gives a copy
  • A plain parameter behaves exactly as a copy. Implementations pass it without copying and keep it that way unless the callee could see the original change (then they copy).
  • & is required at the call site for a mut parameter, and only there. & of something that isn't a place (a let, a prop, a temporary, a read-only parameter) is an error. A mut parameter can't have a default.
  • A method call's receiver is borrowed mutably without & when the method changes it: todos.push(x), todo.toggle() (below, Methods). Such a receiver must be a place (getTodo().toggle() is an error).
  • Exclusivity, the only borrow rule, checked at compile time:
    • two & arguments of one call can't overlap: one place a prefix of the other (swap(&a, &a), f(&a, &a.x)). Index steps overlap unless both are distinct constants (swap(&xs[0], &xs[1]) is fine; swap(&xs[i], &xs[j]) isn't: use xs.swap(i, j));
    • a plain argument overlapping a & one is passed as a copy taken before the call;
    • the same holds for a non-escaping closure argument: a plain argument or receiver overlapping a place the closure writes is passed as a copy (xs.forEach(x => { xs.push(x) }) iterates the old xs); a & argument or mutably borrowed receiver overlapping one is an error (xs.sort((a, b) => { xs.push(a); … }));
    • while a & borrow of a state field, prop bind or global is live, the callee, everything it calls, and the closures and functions passed at that call can't read or write that field by name. Error at the call, naming both sites (and suggesting the access move after the call);
    • where that can't be seen statically (the call goes through a function value: a prop, a stored callback, a parameter), the check is dynamic: the field is marked borrowed for the call, and reading or writing it by name panics (TypeError: "todos is borrowed by update"). Borrows of locals need no dynamic check;
    • an async function can't have mut parameters (a borrow can't live across an await).
  • There are no lifetimes: a borrow lives exactly as long as the call.

Closures ​

  • A closure that runs during the call it's passed to (the default for function-typed parameters, like filter's and forEach's) reads and writes the enclosing function's locals in place: xs.forEach(x => { total += x }) works. The call's & arguments can't overlap a local the closure writes.
  • A closure that runs later escapes: it is stored, returned, put in a record, passed to a parameter marked escaping (fn later(f: escaping () => void)), passed as a prop or event handler, or given to a timer, an effect's cleanup, then, or a lib function. It captures copies of the locals it reads when it's created, and can't write them (error: "this closure runs later and can't change total; make it state, or return the value").
  • A closure bound to a let local (or a nested fn) doesn't escape as long as it is only called or passed to non-escaping parameters; otherwise it does. The compiler decides this from the function's body alone.
  • An async closure or nested function always escapes: it runs past the call that started it.
  • Component state, globals and module lets are reached by name, never captured: an escaping closure (a handler, a timer) reads their current value when it runs and can write state.
  • An escaping closure keeps its instance's state readable. Called after the instance unmounts, it runs and reads the state as it was at unmount; its writes to that state are discarded and start no turn. The same holds for an effect's cleanup.
  • Closures compare by identity: a copy keeps it; each evaluation of a closure expression makes a new one.
  • Storing a non-escaping parameter is an error with the fix-it f: escaping () => void.
  • A closure can't capture itself; recursion needs an fn declaration.
  • Function types carry their parameters' modes; escaping belongs to a parameter's type, not the function's.

Expressions ​

literalsnumbers, strings, templates, true, false, null, [a, ...xs], { a, b: 1, ...r } (later fields win, as in JS: { ...todo, done: true } is todo with done replaced, the field keeping the spread's type, which the new value must fit; a field named twice is an error), [a, b] tuples by context, named construction Todo { … }, variants Circle { r: 2 }, Empty
rangesa..b, a..=b on numbers (a Range, std.md); xs[a..b], s[a..b] slice exactly as slice(a, b) does, xs[a..=b] as slice(a, b + 1); either end may be left out (xs[..3], xs[2..], xs[..=3])
ifif c { a } else { b } as an expression: each branch one expression, else required (else if chains)
arithmetic+ - * / % ** on numbers; + also joins two strings. "a" + 1 is an error with a fix-it to a template
bitwise& | ^ ~ << >> >>> on numbers, through 32-bit integers as in JS
comparison< <= > >= on two numbers or two strings (by UTF-16 code units)
equality==, != on any two values of related types: structural (lists by items, records by fields, maps and sets by entries regardless of order); numbers as IEEE (NaN != NaN, 0 == -0), inside lists and records too; functions by identity; handles by the host object. An implementation may answer true at once when both sides share storage, except for values containing NaN, which == never equals
logic&& || ! on booleans only; ?? on T?; c ? a : b with c boolean
optionala?.b, a?.[i], f?.(x) on T?; a! asserts non-null (panics with TypeError)
memberr.field (static; if r's type has a field m, r.m(…) calls it), xs[i] (panics with RangeError out of range), xs.at(i) (T?, negative from the end), m.get(k) (V?). Strings have no s[i] (but slices, s[1..3]): s.at(i) gives one code unit as string?
callsf(a, &b); x.f(…) (below, Methods); spreads into rest parameters f(...xs)
typesx is T (a run-time test, narrowing); x as T (checked: T ! CastError, Errors; when x's type already fits T it checks nothing and can't fail). Precedence of <; the type after them can't end in ? (test null separately)
asyncawait t inside async functions, handlers and the top level
functions(a: A, b) => expr, async (a) => { … }
matchan expression (below)
tagged stringstag"text {x} more" calls tag(parts, x): parts: Parts holds the literal pieces (parts.strings, one more than the values; a tag may cache what it derives from them, but their identity isn't observable); then each {expr} value as the remaining arguments, typed by tag's rest parameter. Any function taking (parts: Parts, ...values: T[]) is a tag
  • Precedence, loosest first: arrow =>; ? : (right); .. ..= (not chained); ??; ||; &&; |; ^; &; == !=; < <= > >= is as; << >> >>>; + -; * / %; ** (right; a unary operand on its left is an error, as in JS); unary ! - + ~ await; postfix !, calls, ., ?., [ ]. ?? mixed with || or && without parentheses is an error. Unary - and + take numbers only (+x is x).
  • Conditions are booleans. if xs.length { … } is an error with a fix-it to xs.length > 0; if x { … } on a T? is an error with a fix-it to x != null.
  • No coercion anywhere. Arithmetic on a T? needs a narrowing or ??.
  • Templates and text show string as is, number by Number::toString (shortest round-trip, -0 → "0"), booleans as true/false, null as nothing. Showing a list, record, map, function or handle is an error (join it, or json.stringify it). A json value shows what it holds when that is a primitive, and nothing for a list or record.
  • Evaluation order is left to right, arguments before the call, the right side of an assignment before the place's steps are written.
  • as and is test a primitive type, a literal or null on any value; a record type only on json (j as Todo checks every field of Todo with the right type and projects away the rest; a missing optional field becomes null; nested records and lists are checked the same way, all the way down) or on a discriminated union (by its tag). x as T requires T to be a member of x's type, or x: json.
  • json: j.k and j["k"] read a key, j[i] an index, giving json (null when absent or the wrong shape). A json place can be written (j["a"] = 1; TypeError if j isn't a record). Every data type converts to json implicitly; json converts to another type only with as.
  • Construction: Map<K, V>(), Map([[k, v]]), Set<T>(), Set([a, b]), Error("message"), Error({ name, message, data }). There is no new.
  • Tags checked at compile time: a standard-library tag may carry a check the compiler runs on the literal parts and the values' types (std/db's sql checks the query against the schema and gives the rows' type). Only the standard library declares such checks for now; any other tag is an ordinary function.
  • An unused Task (not awaited, stored, returned or passed) is a warning, except a call made as a statement, which starts the task and lets it run (fire and forget; a rejection is reported when the queue drains).

match ​

weft
let area = match shape {
  Circle { r } => PI * r * r,                 // `import { PI } from "std/math"`
  Rect { w, h } => w * h,
  Empty => 0,
}
match key {
  "Enter" | "Return" => submit(),
  k if k.length == 1 => insert(k),
  _ => {},
}
  • Patterns: literals, null, _, a binding name, p | q, variants (Circle { r }, Empty, Shape.Circle { r }), record patterns ({ kind: "rect", w }, unlisted fields ignored), list and tuple patterns ([first, ...rest], []), ranges of numbers (0..10, 10..=20), type tests (n is number), and pattern if guard.
  • A list or tuple pattern without ...rest matches exactly that length; with one, at least the fixed items. Every alternative of p | q binds the same names with the same types. A guarded arm never counts toward exhaustiveness.
  • Arms are separated by , or a newline; a trailing comma is allowed. Arms are tried in order. The arms must cover the type (error naming a missing case); a _ that covers nothing is a warning. A match used as a value needs every arm to give one.

Statements ​

weft
let total = 0..n                     // a Range
let mut sum = 0
for i of 0..n { sum += i }
for t of todos { log(t.title) }
for [key, value] of counts { … }
for mut t of todos { t.done = false }
outer: for row of grid { for cell of row { if cell == 0 { break outer } } }
while queue.length > 0 { step() }
if left == 0 { celebrate() } else if left < 3 { nudge() } else { wait() }
defer { done() }                     // runs when the block exits
  • let and let mut, with destructuring (let { a, b: [x, y] } = r, let mut [lo, hi] = pair).
  • if let pattern = e { … } else { … } runs its block when e matches the pattern (any match pattern), with the pattern's names bound there: if let Circle { r } = shape { draw(r) }. A plain name against a T? matches when the value isn't null and binds it as T: if let user = session.user { greet(user) }. else if let chains. A guard may follow the pattern: if let n if n > 0 = count { … }.
  • let pattern = e else { … } binds the pattern's names for the rest of the block, or runs the else block, which must leave it (return, fail, break, continue): let user = await currentUser() else { return unauthorized() }. With a plain name against T?, the binding is T.
  • if/else if/else, while, for x of xs, for (x, i) of xs (with the index; lists, tuples, strings and json), for [k, v] of m (a map, or a json object: std.md, json), for i of a..b, for mut x of xs (each item as a place; xs must be one), break, continue (labels on loops), return, fail, defer, match, blocks, assignments, calls. There is no C-style for (use a range) and no do.
  • A declaration's own initialiser doesn't see it: there its name means the outer one (let now = now() calls the prelude's now; at the top level this holds for prelude names, other self-references are errors).
  • Scopes are blocks. A name can't be used before its declaration, except fn declarations, which are visible in their whole block (so top-level functions may call each other). Redeclaring a name in the same scope is an error; shadowing an outer one is allowed.
  • for x of xs iterates a copy of xs taken when the loop starts: changing xs in the body doesn't change the iteration. Strings iterate by code point; maps as [key, value]; sets by item; ranges by number. A union of list types iterates too (A[] | B[], its items A | B).
  • In for mut x of xs, the body can't read, write or pass xs or anything overlapping it except through x (error at the access).
  • Calling an fn declaration, or taking it as a value, before a declaration it uses in the same block is an error.
  • const, function, switch, do, var, delete (use m.delete(k)), with, for in, new and class are errors with a pointer to the replacement.
  • Errors are values (below, Errors): fail, try and defer. There is no throw, catch or finally.

Errors ​

Errors are values, as in Go and Zig: a function's type says how it can fail, the caller must handle or pass on every failure, and bugs are a different thing (panics, below).

weft
type LoadError = NotFound { id: string } | Offline

fn load(id: string): Todo ! LoadError {             // can fail with a LoadError (inferred when left out)
  let row = try db.query.todos.first({ id })         // one binding: on error, return it to my caller
  if row == null { fail NotFound { id } }            // fail: return an error
  return row
}

let todo, err = try load(id)                         // two bindings: I handle it
if err != null {
  return match err { NotFound { id } => notFound(id), Offline => retryLater() }
}
show(todo)                                           // narrowed: a Todo here

let count = try parseNumber(text) else 0             // a fallback instead of the error
let n = try parseNumber(text) else e => report(e)    // … that can use it
defer conn.close()                                   // runs when the block exits, however it exits
  • Fallible functions. A function's result type may carry an error type: R ! E, where E is a data type (usually a union of variants; Error, { name, message, data }, is the general one). Left out, it is inferred: the union of what the body fails with and what its trys pass on; a function with neither can't fail. Function types carry it ((id: string) => Todo ! LoadError), and so do tasks (async fn → Task<R ! E>). A recursive fallible function writes it.

  • fail e ends the function with the error e, as return ends it with a value; e must fit the error type.

  • A fallible call must be handled: its result goes through try (error otherwise, naming what the call can fail with):

    • try f(), anywhere an expression goes: on error, the enclosing function fails with it (its error type grows to include it). let x = try f() is the common form; foo(try bar()) works too.
    • let value, err = try f() (two bindings, a declaration in a block only: a module's or component's top level declares one name per let, so it handles an error with try … else): never fails; err is the error or null, and value the result when err is null (null otherwise). After a check that leaves the block when err != null, value is narrowed to R.
    • try f() else fallback gives fallback on error; try f() else e => expr can use the error. Neither fails.
    • try await t and let v, err = try await t for tasks.
  • Where a failure can go. Propagation needs a function to fail: in a handler, an effect, a component's top level or markup, try must take two bindings or an else (error otherwise, with a fix-it). A module's top level may propagate: its load fails, and a program run by weft run reports the error and exits with code 1. A server function's errors reach the client typed: the client's call is R ! E | NetworkError.

  • Errors are data: compared with ==, converted to json, sent over the network, matched exhaustively. The standard library's modules define their errors as variants (std/json's SyntaxError, std/http's NetworkError…).

  • defer s (a statement or a block) runs s when the enclosing block exits — normally, by return, break, continue, fail, or a try passing an error on — in reverse order of the defers. It doesn't run on a panic or a stop.

  • x as T is fallible: T ! CastError, with CastError { path: string, expected: string } naming the failed field path (value.people[1].age) and the type expected there. x is T stays a test.

  • Written results. In a declaration, a result written without ! still has its error type inferred (fn f(): number may fail); : number ! never says it can't. In a function type (a parameter's, an alias, a field), no ! means it can't fail. A function that calls itself and fails writes its error type (inference).

  • Error polymorphism. A type parameter may stand for an error type: fn map<T, U, E>(xs: T[], f: (x: T) => U ! E): U[] ! E fails with what f fails with, and can't fail when f can't (E is inferred as never). The prelude's methods that run a callback during the call are declared so (std.md): a failing callback ends the method at once and the call fails with its error. Escaping callbacks (timers, handlers, then) can't fail.

  • Closures infer their error type from their body. Where the expected function type can't fail (an event handler, an escaping callback, a parameter typed () => R), a try passing an error on inside is an error (propagation-forbidden). An async function whose task can fail is a function that can fail: given there (onpress={save}), or its task returned from an arrow there (onpress={() => save()}), it is an error as a fallible sync function is (E2029), since the task's error would be dropped.

  • Representation. A function that can't fail fits a function type that can (() => R is a () => R ! E): a success is the value itself.

  • Two bindings: value is R? and err is E?; a check that err is null (the then of if err == null, or the code after if err != null { return … }) makes value an R. let value: T, err = try f() types R.

  • try on something that can't fail is a warning (needless-try). A task's error that nothing awaits is reported when the queue drains (not a panic); a cancelled run's error is dropped. Calling an async fallible function isn't itself fallible (it gives the Task<R ! E>); the await is.

  • defer is checked where it is written and runs at its block's exit, reading variables as they are then; a return's value is evaluated before the defers run, last first; a loop body's defers run at the end of each iteration; a panic skips the ones not yet run. Its body can't return, fail, await, pass an error on (handle each fallible call there), or break/continue out of itself; defer belongs in a block, not a module's or component's top level (defer).

  • Error types are data, compared and matched like any data. The prelude's are CastError { path, expected } (as; paths are rooted at a fixed value: value.people[1].age) and HostError { name, message } (the host's lib calls, schema.md); every other is its module's, imported by name to be written or matched (import type { SyntaxError } from "std/json"), and flows without the import. Each is a one-variant type (ParseError { input }). Several error types together make a union (ParseError | LoadError matches NotFound, Offline and ParseError).

  • No explicit panic: code can't raise one; bugs come from the runtime and the prelude (the standard library's own Weft code panics through its internal std/$runtime).

Panics ​

A panic is a bug, not an error: an index out of range (xs[i]), ! on null, a broken invariant in the prelude (a RangeError before, such as toFixed(25) or a step of 0), a purity or borrow violation found at run time, an @for mut item that is gone, two items with one key, a size limit passed. A panic is { name, message } (name as before: RangeError, TypeError, …). It can't be handled by ordinary code: it ends the turn, which keeps the writes it made (as a JS exception does), and is reported with where it started: panic RangeError: index 5 is outside the list (length 2), then a line per Weft call, innermost first (at inner (lib/util.weft:2); at main.weft:7 for a closure or a top level). The boundaries that do see panics are:

  • markup's @try { … } @catch e { … }, which shows its @catch for a panic while rendering (e the panic);
  • the server, which answers a request whose turn panicked with a 500;
  • tests: assertPanics(f, name?) (std/testing), and a failed assertion is a panic named AssertionError.

A panic's name is the same on every backend, and so is every field of an error value (errors are ordinary values); the runtime's own message texts may differ between backends.

Stops (fuel, stack, memory, the deadline, the effect loop) stay as they are (Limits): neither errors nor panics.

Functions and methods ​

weft
fn countOpen(list: Todo[]): number { return list.count(t => !t.done) }
fn rename(mut todo: Todo, title: string) { todo.title = title }
async fn load(id: string): Todo { return (await lib.fetch(id)) as Todo }
fn pad(s: string, width: number = 2, ...rest: string[]): string { … }
fn card({ title, compact = false }: CardProps): string { … }
  • fn declares a function; arrows (t => t.done, async (a) => { … }) are the function expressions.

  • An async fn's written result is Task<R> or just R; both mean it returns Task<R>.

  • Parameters can have defaults (any expression of earlier parameters and module names), x?: T (type T?, default null) and one rest parameter. A default applies only when the argument is left out: an explicit null is null.

  • A parameter may be a destructuring pattern with its type after it: fn card({ title, compact = false }: CardProps), fn dist([x, y]: [number, number]). Defaults inside the pattern fill fields the record type marks optional (they are evaluated in the callee, after the earlier parameters, when the field is null). Such a parameter is read-only; a mut parameter can't be destructured. Other patterns take no defaults.

  • Methods: x.m(args) calls the built-in method m of x's type if there is one; otherwise a function m in scope whose first parameter takes x: xs.sum() is sum(xs), and with fn toggle(mut t: Todo), todo.toggle() is toggle(&todo). A field of that name wins over both; a module function named like a built-in method of its first parameter's type is a warning (the built-in wins).

  • Query closures: a parameter typed Query<(a: A, …) => R> receives its argument, which must be an arrow literal, as a typed expression tree as well as a function: the callee can call it (q.call(a, …)) or read its tree (q.tree, data) to translate it, as std/db translates a query's filter, sortBy, map and policies into SQL. The arrow is checked as usual; the callee's declaration may restrict what its body uses (only fields, comparisons, &&, ||, !, in, literals and its parameters, for SQL), an error at the expression otherwise. Only the standard library declares Query parameters for now.

    Settled details: Query<F> allows every node of a query tree (hir.md, Query trees); Query<F, G> only the groups G names, a union of "compare", "logic", "arith", "coalesce", "in" (list.includes(x), Weft's in), "cond" and "call" (string methods); fields, literals, parameters and values are always allowed. A sub-expression that reads no parameter (user.id) is a value, computed when the argument is evaluated. Query outside a std/… module is an error, through an alias too; QueryFn is its other name, for a module exporting a Query of its own (std/db's Query<T>, which user code may name). std/testing's queryTree (hir.md) shows a tree.

  • The prelude is the language's types and their methods; every free function is imported from a standard-library module named by purpose (std/format's plural, std/motion's slide, std/json, std/math, std/log…): std.md.

Components ​

weft
import { slide } from "std/motion"
import { plural } from "std/format"
import { uuid } from "std/random"
page({ label: "Todos" })                    // in an app, routes/todos/page.weft gives the path

type Todo = { id: string, title: string, done: boolean }
type Filter = "all" | "open" | "done"

prop initial: Todo[] = []
prop bind filter: Filter = "all"
prop onchange?: (todos: Todo[]) => void

let mut todos = initial
let mut draft = ""
derived shown = todos.filter(t => filter == "all" || t.done == (filter == "done"))
derived left { return todos.count(t => !t.done) }

fn add() {
  let title = draft.trim()
  if title == "" { return }
  todos.push(Todo { id: uuid(), title, done: false })
  draft = ""
  onchange?.(todos)
}
effect { lib.store.set("todos", todos) }
shortcut("add", { label: "Add", keys: ["ctrl+enter"] }, add)
---
<Box class="flex flex-col gap-2">
  <TextField bind:value={draft} onsubmit={add} placeholder="What next?" />
  @for mut todo of todos key todo.id {
    <Checkbox bind:checked={todo.done} label={todo.title} in={slide} />
  } @empty {
    <Text>Nothing yet</Text>
  }
  <Button onpress={filter = "open"}>Open only</Button>
  <Text>{plural(left, "item")} left</Text>
</Box>

Declarations at the top level of a component's code ​

let mut x = estate: the instance's own, reactive
let x = ea constant, computed once per instance
prop x: T = d, prop x?: Ta prop: read-only, follows the parent
prop bind x: T = da two-way prop: writing it writes the parent's bound place (bind:x={place}, or bind:x when the place is the name x), whose type must be exactly T. Passed as a plain value, or not passed, it is the instance's own state, starting from that value or d. Writing a plain prop is an error whose fix-it makes it prop bind (editors also change the parents' x={place} to bind:x={place})
derived x = e, derived x: T = e, derived x { …; return v }a derived value: pure, recomputed when what it reads changes
effect { … }, effect { …; return () => cleanup() }runs after the first paint, then after every turn that wrote what it read; the cleanup runs before the next run and on unmount
fn f(…) { … }, type T = …, import …as anywhere
query fn f(…): R { … }, mutation fn, action fnruns on the server (The server, below)
provide c = eprovides a context (below) to the instances below, live
page({…}), dialog({…}), permissions({…}), shortcut(…), gesture(…)literal arguments, a handler last (js-subset.md, Declarations); a shortcut's or gesture's when is a pure closure, when: () => !editing, whose reads are tracked like a derived value's
test "name" { … }a test (below)

Top-level statements other than declarations run once, in order, when the instance is created (they may await: the instance paints from its first values). Every let, let mut, prop, derived, effect, provide, fn and declaration call must precede the first top-level await; statements after it may only assign and call. A top-level let or let mut initialised with a Task<T> is an await value for @await. A let whose initialiser awaits (let user = await load()) is set when that await completes, after the instance first painted: what reads it (markup, derived values, effects) follows it as it follows state, and it is null until then.

Markup ​

The markup is README.md's (tags, attributes, text, {expr}, bind:, class:, motion), with control flow written like the code's, behind @:

weft
@if todos.length == 0 {
  <Text>Nothing yet</Text>
} @else if left == 0 {
  <Text>All done</Text>
} @else {
  @for (todo, i) of shown key todo.id {
    <Row {todo} index={i} />
  } @empty {
    <Text>No match</Text>
  }
}
@match shape {
  Circle { r } => <Circle {r} />,
  Rect { w, h } => <Rect {w} {h} />,
  Empty => {},
}
@await results {
  <Spinner />
} @then found {
  <List items={found} />
} @catch e {
  <Text>{e.message}</Text>
}
@key page.id { <Page {page} /> }
@try { <Chart data={rows} /> } @catch e { <Text>The chart failed: {e.message}</Text> }
@snippet row(t: Todo) { <Text>{t.title}</Text> }
@render row(todo)
@let total = rows.sum()
  • @if c { … } @else if d { … } @else { … }.
  • @for x of xs key k { … } @empty { … }: (x, i) binds the index too; key (an expression of the item) is optional; @empty shows when the list is empty. @for mut x of xs names each item as a place (Reactivity, below).
  • @match e { pattern => markup, … }: an arm's markup is one element, { … } with several, or {} for nothing; exhaustive as match is.
  • @await t { pending } @then v { … } @catch e { … }: either of the last two may be left out.
  • @key e { … } rebuilds its markup when e changes; @try { … } @catch e { … } is a panic boundary: a panic while rendering what it holds shows its @catch (e the Panic, { name, message }) and is not reported. @await t's @catch e shows the task's error (e: E of a Task<R ! E>); without one, a failure shows nothing and is reported when the queue drains; a panic there reaches the nearest @try.
  • Text follows README.md (Markup): a whitespace run containing a line break that touches a tag is dropped; any other whitespace run collapses to one space (<B>a</B> <I>b</I> keeps its space).
  • @snippet name(params) { … } declares a snippet (directly inside a tag, it is that tag's prop of that name; the rest of a tag's content is its children); @render name(args) shows one; @let x = e names a value for the rest of its block.
  • @ starts a block only when a block's word follows it directly (if for match await key try snippet render let); anywhere else it is text (mail@example.com). @@ writes a literal @ before such a word.
  • @for iterates a list, a tuple, json or a range (@for i of 0..n); @for mut only a state list.
  • Tags. A capitalised tag names, in order: a primitive imported under another name (import { Checkbox as CheckboxPrimitive } from "primitives": the built-in primitives module exports every primitive of the schema), a component in scope (imported, or by file name in an app), else a primitive of the schema. So a component shadows the primitive of its name: the registry's Checkbox component draws the Checkbox primitive it imports as CheckboxPrimitive (styles.md, Headless primitives and the registry).
  • A component's class and type. class is a reserved word, so a component takes the class its tag is given as its prop className (Svelte's class: className): <Button class="w-64"> passes className. Without a className prop, class on a component is an error as any unknown prop. type is reserved too and goes to a typeName prop the same way (<Input type="password">, platform.md, Text fields).
  • Optional props of a primitive take null as not given, so a component passes its own optional props on as they are (prop testId?: string … <Pressable {testId}>); a primitive's required and bindable props don't.
  • bind:x={place} binds a prop or bindable attribute to a place; bind:x alone binds the place named x, as {x} passes the value named x. Binding (or writing) an item of a @for without mut is an error whose fix-it makes it @for mut.
  • Event attributes take a function (onpress={add}, onpress={() => count += 1}) or, shorter, a statement: an assignment or ++/-- (onpress={count += 1}, onpress={open = !open}) is a handler that runs it. A call is an expression, so onpress={save()} passes save()'s result: an error unless that is a function ("write onpress={save} or onpress={() => save()}"). A primitive's events are its schema's (a tap is onpress, spec/gestures.md); a component's are its on… props of a function type (the registry's Button has onpress and onlongpress, shadcn's onClick in Weft's words), and they take the statement form too.

Reactivity ​

  • Paths. A read or write touches a path: a state field, prop or global, then field names, with every index or key step written [*] (todos[*].done). Two paths overlap when one is a prefix of the other, [*] matching any step.
  • Reads are known statically: for each derived value, effect, provide and markup expression, the compiler lists the paths it may read (in any branch, through every function it calls). Precisely:
    • a method call on a list, map or set reads the whole receiver path; .length and .size read path.length; xs[i] reads xs[*];
    • a callee's parameter paths are replaced by the argument paths (an argument that isn't a place contributes its own reads); a recursive function reads its arguments whole;
    • a pure closure (no writes, no effectful calls) or function name created or named in the unit contributes its body's reads, so <List pred={t => t.done == flag} /> re-sends pred when flag changes; an impure one (a handler) contributes none and isn't re-sent;
    • reads inside an impure escaping closure don't count: they happen later.
  • Writes are what ran: a turn's writes are the paths its executed writes touched (assignments, mutating methods, bind: and prop bind updates). Passing &p writes p whether or not the callee changes it. A write counts even if it stores an equal value. A prop bind write reaches the parent's place at once, within the turn.
  • A turn is one handler, shortcut, gesture, timer callback, effect run, or continuation after an await completes. After a turn:
    1. derived values whose reads overlap the turn's writes are recomputed, in dependency order; one whose new value equals its old one (structurally, numbers by SameValueZero) writes nothing further;
    2. markup expressions reading an overlapping path update. A turn's writes may span instances (callback props, context functions, prop bind), so steps 1 and 2 run over the whole tree until no derived value or prop changes; then the screen is drawn;
    3. effects whose reads overlap the writes run: within an instance in declaration order, children before parents, siblings in order. Each effect run is its own turn; the writes of one round of effects flush together, and the effects they trigger are the next round. A chain counts the first round as 1; starting round 101 is a stop instead ("effects keep changing what they read: …").
  • Derived values are always current. Read inside a turn after something it reads was written, a derived value is recomputed before the read returns. The screen and effects see only flushed values.
  • Props change when the value the parent passes differs, compared structurally (numbers by SameValueZero); a closure the parent creates again (a pure one whose reads changed) always counts as a change.
  • Scheduling. Turns run one at a time from one queue, first in first out. await always suspends, even on a finished task; its continuation is queued as a new turn when the task finishes, after the current flush. A component's top level runs to its first await (or its end), then the instance's first flush paints and runs its effects; continuations follow. Host answers (lib calls, server calls, timers) are queued in the order they arrive; test hosts make that order explicit. A rejected task that nothing awaits is reported when the queue drains. A continuation of an unmounted instance still runs, with its writes discarded; its timers (and so a pending sleep) are cancelled and never resume.
  • Derived values, provide and markup expressions are pure: they write no state, prop or global and make no effectful call (a lib function with effects, std/log, timers, dialogs, std/random, a server function). Writes are classified by the place's root: changing a local created in the unit is pure. Error otherwise, naming the write or call. They may call a function value (a prop, a context function); a write or effectful call made while a pure unit evaluates panics (TypeError) before it happens. Creating an impure closure (a handler, a function in a provided value) is not a call and is allowed; it contributes no reads, and keeps its identity until the unit evaluates again.
  • A pure unit that panics (it can't fail: a derived value, provide and markup handle their errors): a derived value keeps its previous value and the panic is reported; with no previous value (the first evaluation), or in a markup expression, the nearest @try shows its @catch (the panic is not reported), and without one the error is reported and the instance stops.
  • Async derived values: a derived whose body awaits (derived results = await search(query), or a block with awaits) is an Async<T>: { pending, value, error }. It starts when the instance mounts and again whenever something it reads (anywhere in its body) is written; starting again cancels the run in progress (its continuations never run and its result is dropped). While a run is pending, value keeps the last result (pending is true); a run that fails sets error and keeps value. Its body may pass errors on (unlike a sync derived value), and there an await of a task that can fail passes its error on by itself (derived results = await search(q) needs no try; try … else still handles one): its error type E is the union of what it passes on (a server function's NetworkError included), and the value is an Async<T, E>; a panic ends the run (reported; pending cleared, value and error kept). Markup shows one with @await results (pending, then value, then error) or reads its fields. value and error start null; a run's start keeps both; success sets value and clears error; failure sets error and keeps value; unmounting cancels the run. debounce(x, ms) and throttle(x, ms) (std/reactive) are derived values that follow x late, so derived results = await search(debounce(query, 300)) searches once the typing pauses: an async derived value depends on a helper's output, not on its input, so writes to query re-run the search only when the debounced value changes. Its body is pure apart from its awaits on server functions and the host's lib. An annotation gives the value's type: derived results: Todo[] = await search(query) is an Async<Todo[]>.
  • effect bodies can't await. Effects don't run during server rendering; async derived values do, and the server waits for them (ssr.md).
  • Markup expressions are Weft expressions. An instance's render has one fuel budget per flush (Limits). Event objects are typed by the schema.
  • @for mut item of list names each item as a place in list (which must be one): writing item (or bind:checked={item.done}) writes list[i], the item found by its key when the loop is keyed, else its index when the handler runs, at each access. A write whose key (or index) no longer exists does nothing; a read of it panics with TypeError ("the item is gone"). A key is the one the item had when it was drawn. Two items with the same key panic (TypeError) when drawn. Without mut, items are read-only. list must be state, so a derived list can't be mut: iterate the state list with an @if inside, or derive the set of shown ids.
  • Every component has children, the markup its tag was given: Snippet? (null with none; @render children?.()), Snippet in a layout. Declaring prop children: Snippet makes it required.
  • Motion attributes (in, out, animate, morph) take a description or a function making one (in={slide}).
  • Snippet parameters are annotated (@snippet row(t: Todo)), unless the snippet is passed straight to a prop whose schema type gives them.

Context and globals ​

  • Globals: a module declares export global theme: Theme = "light"; every instance that imports theme reads and writes the one shared value, reactively. Writes are global writes.
  • Context: a module declares export context theme: Theme = defaultTheme. A component provides it with provide theme = expr (a live, pure expression); instances below that import theme read the nearest provider's value, or the default. It is read-only to them; to let them change it, the provider puts functions in it (escaping closures that write the provider's state).
  • context and global belong to components; they don't exist on the server. Per-request values there (the signed-in user, a transaction) are std/http's business.

Modules ​

weft
import { plural } from "lib/text"
import type { Todo } from "./todos"
import * as dates from "std/time"

export type Todo = { id: string, title: string, done: boolean }
export let MAX = 100
export fn open(todos: Todo[]): Todo[] { return todos.filter(t => !t.done) }
export global theme: "light" | "dark" = "light"
export context density: "compact" | "normal" = "normal"
let mut hits = 0                              // process state: private, not reactive
  • A module holds import, export, type, fn, query fn, mutation fn, action fn, let, let mut, global and context, and top-level statements, which run in order with its declarations when it loads (a program's work, await serve(…)); its top level may await.
  • A module runs once per process, when it is first imported, in import order: its lets are computed then (an importer waits for a module whose top level awaits). Exported lets are what other modules use, such as a database connection (Projects, above). A let that literals alone decide is computed at compile time and is in the IR, as today (js-subset.md, Compile-time values).
  • A module let mut is process state: one value per running program (a server process, a browser tab), shared by every importer, private to the module (not exportable), and not reactive. It suits caches and counters in a backend; reactive shared state is a global. Each sandboxed tree of user code (std/sandbox) has its own.
  • import { a, b as c } from "id", import X from "id" (a component), import * as m from "id", import type { T } from "id" (importing a type with variants brings its variants). Imports are static and acyclic.

The server ​

Code runs on the server through three kinds of declaration, called from the client as a typed call:

what it doesdatabasemay callmay importruns
query fn f(…): Rreadsthe caller's handle, read-only: one snapshotquery fns, plain functionspure modules, the database, the caller's requestonce per call; live when a component awaits it
mutation fn f(…): Rwritesthe caller's handle: one serializable transactionquery and mutation fns (in its transaction), plain functionsas a query fnagain from the start on a conflict
action fn f(…): RI/Opool.as(user), or through the query and mutation fns it callsanythinganything on the serveronce
weft
import { pool } from "lib/server/db"          // a Database, with identify(pool, …) where it is made
import { fetch } from "std/http"

export query fn openTodos(): Todo[] {                  // read-only; live from a component
  return try await pool.query.todos().filter(t => !t.done).sortBy(t => t.created)
}

export mutation fn toggle(id: string): void {          // one serializable transaction, run again on conflict
  let t = try await pool.query.todos().find(t => t.id == id)
  if let t = t { try await pool.update.todos({ id }, { done: !t.done }) }
}

export action fn importFeed(url: string): number {     // I/O, then mutations
  let res = try await fetch(url)
  let items = try (try await res.json()) as Item[]
  for it of items { try await addItem(it) }            // each its own transaction
  return items.length
}
weft
// In a component: a query fn awaited in an async derived value is live, with no keyword.
derived todos = await openTodos()

What the three share.

  • Each runs on the server and is implicitly async (it may await; writing Task<R> is the same). Client code calls it as a Task<R>; the compiler generates the call. Its parameters and result are data types (no functions, handles or type parameters); the server checks them again when the call arrives, because it comes from the network. They travel in the VM's value encoding, which keeps every value exactly (-0, NaN, lone surrogates, maps and sets).
  • Its body sees its parameters, module-level types, lets and fns that use only server-safe names, and the standard library. Component state, props, global, context, timers and the client's lib are errors there.
  • Errors cross typed. action fn f(…): R ! E (any kind) is, from client code, a Task<R ! (E | NetworkError)> (NetworkError { message, status? } of std/http): its errors arrive as data, checked like its result, and a call that fails on the way (network, decoding, a panic on the server, which answers 500) fails with a NetworkError. Server code calling it directly (a server module, another of these, an endpoint, an app's app.weft, whose router runs on the server) gets Task<R ! E>.
  • A server module is a module compiled for the server; a client import of one sees only its types and these functions.
  • Server code reaches I/O through the standard library's modules (std/http, std/db, std/s3, std/live, std/process; docs/plan.md, Full stack). Nothing is ambient in sandboxed user code (std/sandbox, Projects above): it reaches only what the app gives it.
  • server fn is gone (server-fn): the error's fix-it makes it a query fn when the checker sees that it only reads, an action fn otherwise.

The kind is part of the type. query fn f(id: string): Todo has the type query (id: string) => Todo, and likewise mutation (…) => R and action (…) => R. A function of a kind fits a plain function type of its shape; only a function of that kind fits a type naming one, so a mutation where a query (…) => R is expected is a type-mismatch. The rules below hold for values too: calling one, or passing one on, counts as what its type says.

query fn runs in one read-only transaction per database it reads (a snapshot: REPEATABLE READ on Postgres and MySQL, a read transaction on SQLite), so its reads agree with each other. Awaited in a component's async derived value it is live (std/live.md, Live calls), with no keyword: its arguments are the call's reads, and the server runs it again when a committed write could change its result, sending what changed. Anywhere else it is one call.

mutation fn runs in one transaction per database, SERIALIZABLE (Postgres SSI, MySQL SERIALIZABLE, SQLite BEGIN IMMEDIATE), committed when it returns and rolled back when it fails or panics. The retry rule: when the database reports a conflict (a serialization failure or a deadlock) it is rolled back and run again from the start, up to ten runs with a short, growing, jittered wait between them; past that it fails with std/db's Failed { code: "40001" }.

A query or mutation fn called inside one runs in its transaction (a query in a mutation reads the mutation's writes).

action fn has no database rules: each query or mutation it calls is its own transaction, so what it did before a failure stays. It is where I/O goes, and it runs once.

The caller's handle. In a query or mutation fn the pool is the caller's handle: pool.query.todos(), pool.update.todos(…) and pool.sql"…" run under the policies for whoever called, as identify(pool, async () => …) says where the pool is made. caller(pool) writes the same thing out, for a plain function the query calls. pool.as(…) is for actions and scripts: in a query or mutation fn, or through a function it calls, it is db-kind, and so is a scoped handle made outside and used there (the fix-it leaves the pool). admin(pool) stays the one way around the policies, and weft audit lists it.

Determinism (db-kind). A query or mutation fn may run more than once and must give the same result, so its body, and every function it calls (in its module or imported, followed through plain functions), may:

  • import and call only pure modules (std/math, std/json, std/format, std/reflect, std/log, std/time, std/random), the database through the caller's handle, the caller's identity (request(), session(req), std/auth's principal, requireUser, requireRole), plain functions, and query fns (a mutation fn also mutation fns);
  • not do I/O: no other std/http, no std/s3, std/process, std/live channels, std/sandbox, timers, lib calls, or action fns;
  • not change a module's let mut (it would change again on every run): keep it in the database, or do it in an action fn;
  • in a query fn, not read a module's let mut either, directly, in a closure, or through a function it calls or passes on: a query depends only on its arguments and the database, and a live query runs again only when what it read from the database changes. Pass the value as an argument, or do it in an action fn. A module let is a constant and stays readable, and a mutation fn or action fn may read a let mut;
  • read the clock and randomness only through the deterministic sources it is given: now() (and std/time's) is the time the call started, and random()/uuid() draw from a generator seeded for the call, so a run again sees the same values. elapsed(), a monotonic clock, is an error there.

A query fn also doesn't write (insert, update, delete, a writing sql, transaction) or call a mutation fn. Each error is at the call, saying what it does and where (fetch, or ping, which calls fetch), with the fix: most make the function an action fn. std/db's spec says how each runs (std/db.md, Server functions).

Tests ​

weft
fn open(todos: Todo[]): Todo[] { return todos.filter(t => !t.done) }

test "open leaves out done todos" {
  let todos = [Todo { id: "a", title: "x", done: false }, Todo { id: "b", title: "y", done: true }]
  assertEq(open(todos).length, 1)
}
  • test "name" { … } declares a test at the top level of any module or component file; its body is an async block that may await. Tests are compiled only by weft test, which runs every test of the project (or the files and names given) and reports each failure with its source line; they never ship.
  • Inside tests (import { assert, assertEq, assertPanics, mount } from "std/testing"): assert(cond, message?), assertEq(actual, expected) (structural, with a diff), assertPanics(fn, name?) (fn must panic, with a panic named name when given); a failing one panics with AssertionError, which fails the test. A test's body may pass errors on (try, fail): a test that fails with an error fails, reporting it. std/testing is test-only.
  • mount(Component, props) (the props checked as a tag's) mounts a component on the deterministic test host (conformance/lang/README.md) and returns a Handle<"mounted">, whose methods all run synchronously: each performs its action as one turn, then drains every turn that is ready (continuations of finished tasks, timers already due) and flushes, before it returns. Test ids are elements' testId attributes (or id, on an element whose schema gives it one, as the corpus's fixture Button):
    • view.text(): string: the rendered text, as the corpus's text (text nodes joined in document order);
    • view.click(id): fires onclick (or onpress) on the element with that id, and does nothing on a disabled one (its disabled is true, as view.type on a disabled field); view.type(id, text): a TextField (or any element with a bind:value or oninput) gets text as its new value, one turn (bind:value written, then oninput); an unknown id panics with TestError;
    • view.advance(ms): moves the fake clock forward, firing due timers in order (each a turn, drained);
    • view.resolveTask(call, value: json) / view.rejectTask(call, message): answer the oldest pending host call named call (a lib path such as "store.get", or a server function's name), TestError when none is pending; view.pending(): string[]: the pending calls' names, oldest first;
    • view.unmount(): unmounts it (effects' cleanups run, timers are cancelled).
  • Replacing modules: weft.toml's [test.replace], "lib/server/db" = "lib/server/db.test", swaps a module by id for the whole run, so code that imports a resource stays testable without passing it in. Every importer but the replacement itself gets the replacement, which must export every name of the module it replaces with an assignable type (an error otherwise).
  • What a test loads: its own file and what that file imports, transitively, on a fresh runtime per test. The project's other modules don't run, so a page or an app.weft that needs a server stays out of a library's tests. When a module a test does import needs something the test host lacks (a server, a device), that test fails with a LoadError naming what isn't available in tests; the other tests still run.
  • std/testing is a test-only module (hir.md): weft test and the conformance harness provide it, and importing it elsewhere is an error. weft test runs the tests on the VM's deterministic test host (bytecode.md, The test host) and reports each failure with its source line; weft test --list lists them.

Limits ​

  • Fuel. One unit is spent before entering every call (a Weft function, a closure, a prelude function or method, constructions such as Map(…), Set(…) and Error(…) included; reading a field such as a range's length is no call; the entry call counts, the host's harness doesn't) and one for every loop iteration. A prelude method that calls a callback spends for each call too. Each turn starts with a full budget; await spends nothing. A turn has 50,000,000 by default (the host may set it). Running out stops the turn (neither an error nor a panic), at the same point on every backend, because the budget is checked at fixed points (deterministic blocks):
    • A call checks it every time: the call that would spend a unit with none left stops.
    • A loop checks it only before its iterations 1, 65, 129, … (every 64th, counting from 1), after the loop's condition (or its next item) and before the body. The check pays the iterations run since the last check and stops when nothing is left for the one about to start.
    • A loop that ends between checks pays the iterations it ran since its last check as it ends: when its condition (or its items) ends it, and at a jump (break, continue, return) for each loop the jump leaves, a break's own loop included, before any defer the jump runs. A panic out of a loop pays nothing for them.
    • So a stop inside a loop lands at the first check after the fuel ran out, and a call inside a loop sees the budget without that loop's unpaid iterations.
    • An instance's flush (its derived values, provides, markup expressions and the pure calls they make) has one budget of 1,000,000; past it the instance stops.
  • Deadline: 250 ms of engine time per turn on the UI (hosts may set it, and tests inject the engine clock).
  • Stack: 4,000 active Weft calls, the entry call included (prelude functions don't count); the call that would be the 4,001st stops instead. Tail calls are never elided observably. (A browser's native stack holds fewer than 10,000 small frames, so 4,000 is what every backend can promise; a server host may raise it.)
  • Memory: what a turn allocates, 32 MB per turn by default, by a logical size every backend computes the same way: 16 bytes per allocation plus 2 per string code unit, 8 per list item, record field or set item, and 16 per map entry, counted when a value is created. A copy-on-write copy is real memory and counts as the level it copies, when a write makes it (let b = a; a.push(1) pays for a copy of a's list; what lies below that level stays shared). A value whose other holder is gone may be written without a copy: the VM counts references and skips it, the JS backend marks a value shared for good and copies, so only there can such a write stop for memory. String and number literals and templates without substitutions don't count; list and record literals do (each evaluation makes a new value). A call's rest arguments are a list (16 plus 8 per item, log(a, b) and xs.push(x) included), except a lone spread (f(...xs)), which is passed as it is. Iterating a map or a set (for … of, a spread) makes nothing chargeable; each code point for … of takes from a string is a new string. A json record costs 16 plus 8 per field, and a conversion to json costs the lists and objects it makes (stringify costs only its text); closures, tasks and handles cost nothing; s += t costs what it adds (2 per code unit of t, whether or not the string is copied), so a loop of += costs what it builds; the number text a template makes costs nothing. A string method whose result is its receiver unchanged (padEnd to a shorter length, trim with nothing to cut, replace with no match) makes nothing. An error the runtime makes (ParseError, SyntaxError, CastError, HostError) costs its record as a written variant does (kind a field); what a failed parse or cast had built, and the strings the runtime writes into the error (messages, paths), cost nothing. A host's limit on live memory is its own, and not part of conformance.
  • Prelude calls: a lib call spends 1 fuel like any call; resuming after an await spends none.
  • These, fuel and the effect loop limit are stops: no code sees them. defers don't run. Every store the turn wrote (state, props bound to it, globals) returns to what was last painted; the instance that owned the turn and the instances below it stay on screen as they were and run nothing more (no handlers, effects, timers or cleanups). Their closures that another instance calls still run, with their writes discarded.
  • Strings at most 2^28 code units, lists at most 2^28 items: past them panics (RangeError).
  • String comparison and positions are by UTF-16 code units everywhere (the VM stores strings as one byte per code unit when every unit fits, else two, so positions are direct in both backends).

What the compiler produces ​

The front end turns a file into a typed HIR (weft-hir), the one input of every backend:

  • every expression with its type, every name resolved to its declaration, every literal widened or not;
  • places explicit, each call argument marked as a copy, a read-only borrow or a & borrow, and each implicit copy the exclusivity rules require;
  • closures with their captures (by copy, or in place for non-escaping ones) and whether they escape;
  • per unit (top level, function, handler, derived, effect, markup expression): the paths read and the write sites with their paths; whether it is pure; its effectful calls; its await points;
  • markup as a tree of elements, blocks and expressions referring into the HIR;
  • source spans throughout, for diagnostics, source maps and the editor.

Diagnostics have a code, a span, a message naming what was expected and found, and, where one exists, a fix-it. Habits from other languages get one guided diagnostic each, with the Weft form and a fix-it where one is clear, and recovery that reports nothing else in what they cover: JSX in markup ({c && <X/>}, {xs.map(x => <X/>)}, E0002), Svelte's blocks ({#if}, {#each}, {:else}, {/if}, E0003, the whole block rewritten), a block part without its @ (} else {, E0004), interface (E0005), export default (E0006), an arrow's return type (E0007), and a DOM event's name on an element that has another (onClick → onpress, E4008). weft codes lists every code.

Migrating from the JS subset ​

markup-kit migrate rewrites today's markup-kit files to Weft: the <script> wrapper to code above a --- line (<script module> to a module), state to let mut and constants to let, function to fn, $props() to prop, $bindable to prop bind, $derived to derived, $effect to effect, {#if}/{#each}/{#await}/{#key}/ {#snippet}/{@render}/{@const} to @ blocks, === to ==, undefined to null, coercions to templates or explicit conversions, globals()/global.x to a module of globals, setContext/getContext to context, and types where inference needs them. Errors: throw e becomes fail e where the function can fail and is reported elsewhere; try { … } finally { … } becomes the body with defer { … } first; a try { … } catch is kept as its body and reported (which calls to handle, and how, needs a hand); Math.*, JSON.*, console.* and the formatting helpers become imports from std/math, std/json, std/log and std/format. A call that can fail now (a host call, a checked as) gets a propagating try where its function may fail (the function becomes fallible); where nothing can fail (a handler, markup, an effect, a top level) it is left as it is and the file is reported as needing a hand, with the checker's unhandled-error and its fix-it. A handler running an async function that can fail keeps the task in a local (() => { let _ = save() }), so its error is reported when the queue drains, as it was. Every place where copies change behaviour (an alias written, such as const l = list; l.push(x)) is reported, and becomes a & borrow or a deliberate copy.

Weft is in development. The reference is the spec as it stands today.