Appearance
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.weftfile 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
.weftfiles whose root holdsweft.toml. A file's id is its path from the root without.weft(lib/dates,server/api).weft.tomlholds only what tools need before any code runs (weft-check'sconfig.rs); everything else about a project is Weft (its theme istheme.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:tomlmain = "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 aweft.jsongets 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/liveandstd/processas it needs, like any module. Restrictions apply to user code: code an app lets its users write (and plugins, an agent's code) runs throughstd/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 loadweft// 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 callsserve(above), and a script is code that does its work.weft runon a project runs the entry itsweft.tomlnames (main = "server/main.weft"), or, in an app (a project withroutes/), the app framework.weft devruns the same with hot swap and the development tools (editor-protocol.md). Arguments, the environment and the exit code come fromstd/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$,_) thenID_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 ("writelet", "writefn", "writefail", "usetry", "usedefer") 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(ofonly after aforpattern;whereonly after a type;itonly inside awherecondition).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 arenumber(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,breakandcontinuetake their operand on the same line (failalone is an error), and postfix++/--must be on their operand's line. These restrictions win over the continuation rules:returnfollowed by a line starting with+ 1returns nothing (and the next line is an error). The formatter writes no semicolons.- inside
Generic calls:
f<…>(is a generic call when<type arguments>parse and(follows immediately; otherwise<is a comparison. This never depends on whatfresolves 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 ofif,else,while,for,matchanddefer,{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..banda..=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:
@nameor@name(args)before a record type's field or before atypedeclaration (@primary @default(uuid) id: string).@deprecated(until: "2027-06-01", use: "heading")also goes before any other top-level declaration (a function, alet, a prop), or before a file's imports, its---or at its end (the file itself); its arguments are named, both optional,untilaYYYY-MM-DDdate (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\nending too), else a module. - A fraction needs digits after the dot (
1.5,.5):1.toFixed(2)is a method call on1, and1..3is 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.letandlet mutbind one pattern each (let a = 1, b = 2is an error). - Arrows have no return type annotation (
(a): T => …is an error): annotate what they return, or write anfn. elsegoes on the line of the}it follows (} else {); a line starting withelseis an error.- Record types separate fields with
,,;or a line break; the formatter writes,. - A tag is a name directly followed by
"or';fromnever is one, soimport { x } from"id"stays an import. if lettakes any pattern, with an optional guard before the=:if let n if n > 2 = count { … }. It is a statement only (in a value, usematch);elsegoes on the line of the}as forif. Inlet p = e else { … }theelsegoes on the line ofe.- A
matcharm's guard ends at the arm's=>, which never makes an arrow of it:n if ready => …andn 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/sandboxparses user code). whereafter 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,Thas no top-level|(|separates alternatives:n is number | s is string). - Inside any markup
{ … }, line breaks end nothing. tryis a prefix operator over a unary expression, taking a followingas Tinto its operand:try await t,try f().g(),try x as T;try f() + 1is(try f()) + 1.elsegoes on the line of its operand, and its fallback reaches as far right as an expression does (try f() else 0 + 1falls back to1);else e => exprbinds the error (the fallback is an expression, not a block).failtakes 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, bmakes both writable.R ! Eis the loosest type operator:A | B ! C | Dis(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..cis 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 elseName { … }in a type is an error. - Markup:
@render f(x)ends at the)closing its call;@let x = eat 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,@thenand@catchgo 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 (@@ifshows@if); elsewhere@@is text as written.
Types
| type | values |
|---|---|
number | IEEE-754 doubles |
string | sequences of UTF-16 code units (lone surrogates allowed) |
boolean | true, false |
null | null, 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 | U | unions; 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) => R | functions; async (a: A) => R returns Task<R> |
query (a: A) => R, mutation (a: A) => R, action (a: A) => R | a 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 |
Range | a..b (a ≤ i < b) or a..=b, of numbers; iterable, and data ({ start, end, inclusive }) |
Bytes | an immutable sequence of bytes (files, images, HTTP bodies, S3 objects); data; std.md, Bytes |
R ! E | a 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> |
Parts | a tagged string's literal parts (below) |
Query<F> | a closure received as a typed expression tree (Functions) |
json | dynamic 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 } |
void | a function returning nothing; never for one that never returns |
Data types are the types with no function or
Taskinside: they can be serialized, converted tojson, 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 withexport 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,
TtoT?) goes through lists, tuples, maps, sets and function results:1[]is anumber[]. 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
mutparameter, the place of abind:orprop bind, and the list of@for mutmust 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:
wefttype Shape = Circle { r: number } | Rect { w: number, h: number } | Emptyis the union
{ kind: "Circle", r: number } | { kind: "Rect", w: number, h: number } | { kind: "Empty" }: the same values, injsonand 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, amatch'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, writeShape.Circle(error otherwise). A variant's name can't also be a type's or a value's (type Taken = Takenis 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 ofTodomust be given (optional ones may be left out), and no other. It is a record literal checked againstTodo, with the error at the field.Validating types add a condition to a type:
wefttype 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() != "" }itis 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 (Emailis astring: it shows, compares, slices and converts tojsonas one); a base value becomes one only through a check:x as Email(fails with aCastErrornaming 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:asfromjson, 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
Emailisn't aUsername); 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 constantlet): the compiler evaluates the condition when it uses onlyit, constants, operators, the prelude's pure string, number and list methods, and module functions whose body is onereturn; otherwise, or when it fails, the literal is an error (fix-it:… as T).asnames the type and the path to the failing value in itsTypeError(value.age is not a valid Age).Attributes are data the compiler keeps on a type or a field:
@nameor@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 callsuuidwhen 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 throughfields<T>()(std.md), as forms,jsonrenaming andstd/aido.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.uuidfor 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 astringfield is an error); a reference to a function fits a parameter its result fits (the library calls it). Attributes are their own namespace:@primarynames 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 writtenfirst<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]])isMap<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,matchtype tests, showing in a template, and what needs data (json.stringify, conversion tojson, 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) allowsjson.stringifyand conversion tojson,==structurally,fields<T>(), andis/astests 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 adataparameter used as a map key is aninvalid-keyerror (bound itkey).No
any, nounknown, 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 = 1is1, andfn circle(r: number) { return { kind: "circle", r } }returns{ kind: "circle", r: number }, which fitsShape.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 suchlet mut):- only literals assigned (
filter = "done",null): it is their union with the initializer's, solet mut filter = "all"fitsFilterwhere it's passed tolabel(f: Filter), andlet mut open = falsewithopen = truesomewhere isboolean; - a use that needs an exact type (
bind:of it,&of it for amutparameter,bind:of an@for mutitem 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 thelet mutwith 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 alet mutto state it:let mut filter: Filter = "all".- only literals assigned (
An empty
[],{},Map()orSet()initialising an unannotatedlet mutgets its type the same way: from an exact use, then a type expected where it is read (an argument, areturn, a prop, an annotatedlet), then what is added to it (push,unshift,insert,xs[i] = x; a set'sadd; a map'ssetandm[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 = nullis an error asking for a type (let x = nullisnull).c ? 1 : "a"andif c { 1 } else { "a" }arenumber | string. Destructuring a list (let [a, b] = xs) givesT?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, asstd/motion'sanimate(el, (t, dt) => …)does) and props whose default decides their type (prop count = 0isnumber).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" (alet 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,matcharms,if letandlet … else(Statements);&&,||,!, earlyreturn/fail/break/continue: afterif x == null || c { break },xisn'tnull(a false||has every side false, andcis checked withxalready narrowed, also when it compares a field ofx: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 = 1leavesaunchanged. So does pushingainto 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==). letis 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 itlet mut").let mutbindings 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 avoidarrow 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
&placeargument'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]withioutside0 … length - 1or not an integer panics (RangeError); writing a map's key adds it. - Writing through a field of
nullpanics (TypeError); the type checker makes this need a!or a narrowing first.
Parameters: borrows
| Rust | Weft | at the call | in the callee |
|---|---|---|---|
&T | x: T (the default) | f(a) | read-only: can't be assigned or changed |
&mut T | mut x: T | f(&a), a a place | changes 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 amutparameter, and only there.&of something that isn't a place (alet, a prop, a temporary, a read-only parameter) is an error. Amutparameter 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: usexs.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 oldxs); 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 bindor 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
asyncfunction can't havemutparameters (a borrow can't live across anawait).
- two
- 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 andforEach'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 alibfunction. 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 changetotal; make it state, or return the value"). - A closure bound to a
letlocal (or a nestedfn) 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
asyncclosure or nested function always escapes: it runs past the call that started it. - Component state,
globals and modulelets 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
fndeclaration. - Function types carry their parameters' modes;
escapingbelongs to a parameter's type, not the function's.
Expressions
| literals | numbers, 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 |
| ranges | a..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]) |
if | if 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 |
| optional | a?.b, a?.[i], f?.(x) on T?; a! asserts non-null (panics with TypeError) |
| member | r.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? |
| calls | f(a, &b); x.f(…) (below, Methods); spreads into rest parameters f(...xs) |
| types | x 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) |
| async | await t inside async functions, handlers and the top level |
| functions | (a: A, b) => expr, async (a) => { … } |
match | an expression (below) |
| tagged strings | tag"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 (+xisx). - Conditions are booleans.
if xs.length { … }is an error with a fix-it toxs.length > 0;if x { … }on aT?is an error with a fix-it tox != null. - No coercion anywhere. Arithmetic on a
T?needs a narrowing or??. - Templates and text show
stringas is,numberby Number::toString (shortest round-trip,-0→"0"), booleans astrue/false,nullas nothing. Showing a list, record, map, function or handle is an error (joinit, orjson.stringifyit). Ajsonvalue 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.
asandistest a primitive type, a literal ornullon any value; a record type only onjson(j as Todochecks every field ofTodowith the right type and projects away the rest; a missing optional field becomesnull; nested records and lists are checked the same way, all the way down) or on a discriminated union (by its tag).x as TrequiresTto be a member ofx's type, orx: json.json:j.kandj["k"]read a key,j[i]an index, givingjson(nullwhen absent or the wrong shape). Ajsonplace can be written (j["a"] = 1;TypeErrorifjisn't a record). Every data type converts tojsonimplicitly;jsonconverts to another type only withas.- Construction:
Map<K, V>(),Map([[k, v]]),Set<T>(),Set([a, b]),Error("message"),Error({ name, message, data }). There is nonew. - 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'ssqlchecks 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), andpattern if guard. - A list or tuple pattern without
...restmatches exactly that length; with one, at least the fixed items. Every alternative ofp | qbinds 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. Amatchused 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 exitsletandlet mut, with destructuring (let { a, b: [x, y] } = r,let mut [lo, hi] = pair).if let pattern = e { … } else { … }runs its block whenematches the pattern (anymatchpattern), with the pattern's names bound there:if let Circle { r } = shape { draw(r) }. A plain name against aT?matches when the value isn'tnulland binds it asT:if let user = session.user { greet(user) }.else if letchains. 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 theelseblock, which must leave it (return,fail,break,continue):let user = await currentUser() else { return unauthorized() }. With a plain name againstT?, the binding isT.if/else if/else,while,for x of xs,for (x, i) of xs(with the index; lists, tuples, strings andjson),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;xsmust be one),break,continue(labels on loops),return,fail,defer,match, blocks, assignments, calls. There is no C-stylefor(use a range) and nodo.- A declaration's own initialiser doesn't see it: there its name means the outer one (
let now = now()calls the prelude'snow; 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
fndeclarations, 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 xsiterates a copy ofxstaken when the loop starts: changingxsin 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 itemsA | B).- In
for mut x of xs, the body can't read, write or passxsor anything overlapping it except throughx(error at the access). - Calling an
fndeclaration, or taking it as a value, before a declaration it uses in the same block is an error. const,function,switch,do,var,delete(usem.delete(k)),with,for in,newandclassare errors with a pointer to the replacement.- Errors are values (below, Errors):
fail,tryanddefer. There is nothrow,catchorfinally.
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 exitsFallible functions. A function's result type may carry an error type:
R ! E, whereEis 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 bodyfails with and what itstrys 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 eends the function with the errore, asreturnends it with a value;emust 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 perlet, so it handles an error withtry … else): never fails;erris the error ornull, andvaluethe result whenerrisnull(nullotherwise). After a check that leaves the block whenerr != null,valueis narrowed toR.try f() else fallbackgivesfallbackon error;try f() else e => exprcan use the error. Neither fails.try await tandlet v, err = try await tfor tasks.
Where a failure can go. Propagation needs a function to fail: in a handler, an effect, a component's top level or markup,
trymust take two bindings or anelse(error otherwise, with a fix-it). A module's top level may propagate: its load fails, and a program run byweft runreports the error and exits with code 1. A server function's errors reach the client typed: the client's call isR ! E | NetworkError.Errors are data: compared with
==, converted tojson, sent over the network, matched exhaustively. The standard library's modules define their errors as variants (std/json'sSyntaxError,std/http'sNetworkError…).defer s(a statement or a block) runsswhen the enclosing block exits — normally, byreturn,break,continue,fail, or atrypassing an error on — in reverse order of thedefers. It doesn't run on a panic or a stop.x as Tis fallible:T ! CastError, withCastError { path: string, expected: string }naming the failed field path (value.people[1].age) and the type expected there.x is Tstays a test.Written results. In a declaration, a result written without
!still has its error type inferred (fn f(): numbermay fail);: number ! neversays 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[] ! Efails with whatffails with, and can't fail whenfcan't (Eis inferred asnever). 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), atrypassing an error on inside is an error (propagation-forbidden). Anasyncfunction 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 (
() => Ris a() => R ! E): a success is the value itself.Two bindings:
valueisR?anderrisE?; a check thaterrisnull(thethenofif err == null, or the code afterif err != null { return … }) makesvalueanR.let value: T, err = try f()typesR.tryon 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 anasyncfallible function isn't itself fallible (it gives theTask<R ! E>); theawaitis.deferis checked where it is written and runs at its block's exit, reading variables as they are then; areturn'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'treturn,fail,await, pass an error on (handle each fallible call there), orbreak/continueout of itself;deferbelongs 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 fixedvalue:value.people[1].age) andHostError { name, message }(the host'slibcalls,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 | LoadErrormatchesNotFound,OfflineandParseError).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@catchfor a panic while rendering (ethe 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 namedAssertionError.
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 { … }fndeclares a function; arrows (t => t.done,async (a) => { … }) are the function expressions.An
async fn's written result isTask<R>or justR; both mean it returnsTask<R>.Parameters can have defaults (any expression of earlier parameters and module names),
x?: T(typeT?, defaultnull) and one rest parameter. A default applies only when the argument is left out: an explicitnullisnull.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 isnull). Such a parameter is read-only; amutparameter can't be destructured. Other patterns take no defaults.Methods:
x.m(args)calls the built-in methodmofx's type if there is one; otherwise a functionmin scope whose first parameter takesx:xs.sum()issum(xs), and withfn toggle(mut t: Todo),todo.toggle()istoggle(&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, asstd/dbtranslates a query'sfilter,sortBy,mapand 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 declaresQueryparameters for now.Settled details:
Query<F>allows every node of a query tree (hir.md, Query trees);Query<F, G>only the groupsGnames, a union of"compare","logic","arith","coalesce","in"(list.includes(x), Weft'sin),"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.Queryoutside astd/…module is an error, through an alias too;QueryFnis its other name, for a module exporting aQueryof its own (std/db'sQuery<T>, which user code may name).std/testing'squeryTree(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'splural,std/motion'sslide,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 = e | state: the instance's own, reactive |
let x = e | a constant, computed once per instance |
prop x: T = d, prop x?: T | a prop: read-only, follows the parent |
prop bind x: T = d | a 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 fn | runs on the server (The server, below) |
provide c = e | provides 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;@emptyshows when the list is empty.@for mut x of xsnames each item as a place (Reactivity, below).@match e { pattern => markup, … }: an arm's markup is one element,{ … }with several, or{}for nothing; exhaustive asmatchis.@await t { pending } @then v { … } @catch e { … }: either of the last two may be left out.@key e { … }rebuilds its markup whenechanges;@try { … } @catch e { … }is a panic boundary: a panic while rendering what it holds shows its@catch(ethePanic,{ name, message }) and is not reported.@await t's@catch eshows the task's error (e: Eof aTask<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 itschildren);@render name(args)shows one;@let x = enames 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.@foriterates a list, a tuple,jsonor a range (@for i of 0..n);@for mutonly a state list.- Tags. A capitalised tag names, in order: a primitive imported under another name (
import { Checkbox as CheckboxPrimitive } from "primitives": the built-inprimitivesmodule 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'sCheckboxcomponent draws theCheckboxprimitive it imports asCheckboxPrimitive(styles.md, Headless primitives and the registry). - A component's
classandtype.classis a reserved word, so a component takes theclassits tag is given as its propclassName(Svelte'sclass: className):<Button class="w-64">passesclassName. Without aclassNameprop,classon a component is an error as any unknown prop.typeis reserved too and goes to atypeNameprop the same way (<Input type="password">,platform.md, Text fields). - Optional props of a primitive take
nullas 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:xalone binds the place namedx, as{x}passes the value namedx. Binding (or writing) an item of a@forwithoutmutis 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, soonpress={save()}passessave()'s result: an error unless that is a function ("writeonpress={save}oronpress={() => save()}"). A primitive's events are its schema's (a tap isonpress,spec/gestures.md); a component's are itson…props of a function type (the registry'sButtonhasonpressandonlongpress, shadcn'sonClickin 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,
provideand 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;
.lengthand.sizereadpath.length;xs[i]readsxs[*]; - 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-sendspredwhenflagchanges; an impure one (a handler) contributes none and isn't re-sent; - reads inside an impure escaping closure don't count: they happen later.
- a method call on a list, map or set reads the whole receiver path;
- Writes are what ran: a turn's writes are the paths its executed writes touched (assignments, mutating methods,
bind:andprop bindupdates). Passing&pwritespwhether or not the callee changes it. A write counts even if it stores an equal value. Aprop bindwrite 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
awaitcompletes. After a turn:- 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;
- 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; - 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.
awaitalways 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 firstawait(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 pendingsleep) are cancelled and never resume. - Derived values,
provideand markup expressions are pure: they write no state, prop or global and make no effectful call (alibfunction witheffects,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,
provideand 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@tryshows its@catch(the panic is not reported), and without one the error is reported and the instance stops. - Async derived values: a
derivedwhose body awaits (derived results = await search(query), or a block withawaits) is anAsync<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,valuekeeps the last result (pendingistrue); a run that fails setserrorand keepsvalue. Its body may pass errors on (unlike a sync derived value), and there anawaitof a task that can fail passes its error on by itself (derived results = await search(q)needs notry;try … elsestill handles one): its error typeEis the union of what it passes on (a server function'sNetworkErrorincluded), and the value is anAsync<T, E>; a panic ends the run (reported;pendingcleared,valueanderrorkept). Markup shows one with@await results(pending, then value, then error) or reads its fields.valueanderrorstartnull; a run's start keeps both; success setsvalueand clearserror; failure setserrorand keepsvalue; unmounting cancels the run.debounce(x, ms)andthrottle(x, ms)(std/reactive) are derived values that followxlate, soderived 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 toqueryre-run the search only when the debounced value changes. Its body is pure apart from its awaits on server functions and the host'slib. An annotation gives the value's type:derived results: Todo[] = await search(query)is anAsync<Todo[]>. effectbodies can'tawait. 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 listnames each item as a place inlist(which must be one): writingitem(orbind:checked={item.done}) writeslist[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 withTypeError("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. Withoutmut, items are read-only.listmust be state, so a derived list can't bemut: iterate the state list with an@ifinside, or derive the set of shown ids.- Every component has
children, the markup its tag was given:Snippet?(nullwith none;@render children?.()),Snippetin a layout. Declaringprop children: Snippetmakes 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 importsthemereads and writes the one shared value, reactively. Writes are global writes. - Context: a module declares
export context theme: Theme = defaultTheme. A component provides it withprovide theme = expr(a live, pure expression); instances below that importthemeread 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). contextandglobalbelong to components; they don't exist on the server. Per-request values there (the signed-in user, a transaction) arestd/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,globalandcontext, and top-level statements, which run in order with its declarations when it loads (a program's work,await serve(…)); its top level mayawait. - 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). Exportedlets are what other modules use, such as a database connection (Projects, above). Aletthat literals alone decide is computed at compile time and is in the IR, as today (js-subset.md, Compile-time values). - A module
let mutis 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 aglobal. 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 does | database | may call | may import | runs | |
|---|---|---|---|---|---|
query fn f(…): R | reads | the caller's handle, read-only: one snapshot | query fns, plain functions | pure modules, the database, the caller's request | once per call; live when a component awaits it |
mutation fn f(…): R | writes | the caller's handle: one serializable transaction | query and mutation fns (in its transaction), plain functions | as a query fn | again from the start on a conflict |
action fn f(…): R | I/O | pool.as(user), or through the query and mutation fns it calls | anything | anything on the server | once |
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 mayawait; writingTask<R>is the same). Client code calls it as aTask<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 andfns that use only server-safe names, and the standard library. Component state, props,global,context, timers and the client'slibare errors there. - Errors cross typed.
action fn f(…): R ! E(any kind) is, from client code, aTask<R ! (E | NetworkError)>(NetworkError { message, status? }ofstd/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 aNetworkError. Server code calling it directly (a server module, another of these, an endpoint, an app'sapp.weft, whose router runs on the server) getsTask<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 fnis gone (server-fn): the error's fix-it makes it aquery fnwhen the checker sees that it only reads, anaction fnotherwise.
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'sprincipal,requireUser,requireRole), plain functions, and query fns (a mutation fn also mutation fns); - not do I/O: no other
std/http, nostd/s3,std/process,std/livechannels,std/sandbox, timers,libcalls, oraction fns; - not change a module's
let mut(it would change again on every run): keep it in the database, or do it in anaction fn; - in a query fn, not read a module's
let muteither, 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 anaction fn. A moduleletis a constant and stays readable, and a mutation fn or action fn may read alet mut; - read the clock and randomness only through the deterministic sources it is given:
now()(andstd/time's) is the time the call started, andrandom()/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 anasyncblock that mayawait. Tests are compiled only byweft 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?)(fnmust panic, with a panic namednamewhen given); a failing one panics withAssertionError, 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/testingis 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 aHandle<"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'testIdattributes (orid, on an element whose schema gives it one, as the corpus's fixtureButton):view.text(): string: the rendered text, as the corpus'stext(text nodes joined in document order);view.click(id): firesonclick(oronpress) on the element with that id, and does nothing on a disabled one (itsdisabledistrue, asview.typeon a disabled field);view.type(id, text): aTextField(or any element with abind:valueoroninput) getstextas its new value, one turn (bind:valuewritten, thenoninput); an unknown id panics withTestError;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 namedcall(alibpath such as"store.get", or a server function's name),TestErrorwhen 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.weftthat 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 aLoadErrornaming what isn't available in tests; the other tests still run. std/testingis a test-only module (hir.md):weft testand the conformance harness provide it, and importing it elsewhere is an error.weft testruns the tests on the VM's deterministic test host (bytecode.md, The test host) and reports each failure with its source line;weft test --listlists 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(…)andError(…)included; reading a field such as a range'slengthis 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;awaitspends 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, abreak's own loop included, before anydeferthe 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 ofa'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)andxs.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 pointfor … oftakes from a string is a new string. Ajsonrecord costs 16 plus 8 per field, and a conversion tojsoncosts the lists and objects it makes (stringifycosts only its text); closures, tasks and handles cost nothing;s += tcosts what it adds (2 per code unit oft, 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 (padEndto a shorter length,trimwith nothing to cut,replacewith no match) makes nothing. An error the runtime makes (ParseError,SyntaxError,CastError,HostError) costs its record as a written variant does (kinda 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
libcall spends 1 fuel like any call; resuming after anawaitspends 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
awaitpoints; - 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.