Skip to content

Basics ​

Files ​

weft
/// The greeting for a name, or for a stranger.
export fn greet(name: string?): string {
  if name == null { return "Hello, stranger" }
  return `Hello, ${name}`
}

That file is a module. Weft code lives in .weft files. There are two kinds:

  • A module holds only code: types, functions, values. Other files import from it.
  • A component is code, then a line ---, then markup. It draws part of a screen. Components get their own page: Components and reactivity.

The compiler tells them apart by that line: a file with a --- line is a component, the code above it and the markup below. A component with no code starts with ---.

// starts a comment to the end of the line, and /* … */ a block comment. /// before a declaration is its doc comment.

Bindings ​

let makes a binding that never changes, and nothing inside its value changes either. let mut makes one you can change:

weft
export fn totals(prices: number[]): number[] {
  let mut sum = 0
  for p of prices {
    sum += p
  }
  let result = [sum, prices.length]
  return result
}

let is deep. Pushing to a let list is an error, and the compiler suggests let mut:

rejected by the compiler (E3001)
weft
export fn build(): number {
  let xs = [1, 2]
  xs.push(3)
  return xs.length
}

Each let and let mut binds one name or one destructuring pattern:

weft
type Size = { width: number, height: number }

export fn area(size: Size): number {
  let { width, height } = size
  return width * height
}

There is no const and no var. Writing either is an error that points to let.

Values you write directly ​

examples
numbers (64-bit floating point)1, 1.5, .5, 1e-3, 0xff, 0b1010, 1_000_000
strings"double", 'single', `template ${expr}`
booleanstrue, false
absencenull (there is no undefined)
lists and records[1, 2, 3], { title: "Docs", done: false }
ranges0..10 (10 left out), 1..=10 (10 included)

There is one number type, number. Strings are sequences of UTF-16 code units, as in JavaScript, so s.length and positions match what a browser reports.

No coercion ​

Weft never converts a value to another type behind your back. Adding a number to a string is an error:

rejected by the compiler (E2001)
weft
export fn label(count: number): string {
  return "Items: " + count
}

Write a template instead. A template shows numbers, strings and booleans, and shows null as nothing:

weft
export fn label(count: number): string {
  return `Items: ${count}`
}

Conditions must be booleans too. if xs.length { … } is an error; the compiler suggests xs.length > 0:

rejected by the compiler (E2008)
weft
export fn describe(xs: string[]): string {
  if xs.length { return "some" }
  return "none"
}

Equality ​

== and != compare values by their contents: lists item by item, records field by field. There is no ===.

weft
export fn same(): boolean {
  let a = { x: 1, tags: ["a"] }
  let b = { x: 1, tags: ["a"] }
  return a == b
}

same() returns true. Weft values have no identity, so there is nothing else == could compare. (Functions are the exception: they compare by identity.)

Semicolons and lines ​

Semicolons are optional, and the formatter writes none. A line break ends a statement when the statement is complete, except inside ( ) and [ ], and when the next line obviously continues the expression (it starts with ., ?. or a binary operator such as + or &&):

weft
type Item = { name: string, price: number }

export fn cheapNames(items: Item[]): string[] {
  return items
    .filter(i => i.price < 10)
    .map(i => i.name)
}

Unlike JavaScript, a line that starts with ( or [ always starts a new statement.

Control flow ​

if, while and for take no parentheses around their head, and their bodies always have braces. else goes on the line of the } before it: } else {.

weft
export fn firstLong(words: string[], min: number): string? {
  for w of words {
    if w.length >= min { return w }
  }
  return null
}

export fn countdown(from: number): number[] {
  let mut out: number[] = []
  let mut n = from
  while n > 0 {
    out.push(n)
    n -= 1
  }
  return out
}

export fn grade(score: number): string {
  if score >= 90 {
    return "A"
  } else if score >= 75 {
    return "B"
  } else {
    return "C"
  }
}

for x of xs walks a copy of the list taken when the loop starts, so changing the list in the body doesn't change the loop. for (x, i) of xs gives the index too, and for [k, v] of m walks a map's entries. break and continue work as in JavaScript; a label on a loop lets them leave an outer one:

weft
export fn findZero(grid: number[][]): [number, number]? {
  outer: for (row, r) of grid {
    for (cell, c) of row {
      if cell == 0 { return [r, c] }
      if cell < 0 { break outer }
    }
  }
  return null
}

A head ends at the { that opens its body, so a record literal at the top level of a head needs parentheses: if p == ({ x: 0, y: 0 }) { … }.

There is no C-style for (init; cond; update), no do … while and no switch. Count with a range, and choose with match.

Ranges ​

a..b is the numbers from a up to, but not including, b. a..=b includes b. A range is a value of type Range; a loop over one counts up by 1:

weft
export fn squares(n: number): number[] {
  let mut out: number[] = []
  for i of 0..n {
    out.push(i * i)
  }
  return out
}

export fn middle(xs: number[]): number[] {
  return xs[1..xs.length - 1]
}

export fn rest(s: string): string {
  return s[2..]
}

In a slice, either end may be left out: xs[..3] is the first three items, s[2..] all but the first two code units. A slice works exactly like slice(a, b).

if as a value ​

if is also an expression. Each branch is one expression, and else is required:

weft
export fn describe(n: number): string {
  let word = if n < 0 { "negative" } else if n == 0 { "zero" } else { "positive" }
  return word
}

c ? a : b works too.

match ​

match tests a value against patterns, top to bottom, and gives the first arm's result. On a union it must cover every case; the compiler names the one you missed.

weft
import { PI } from "std/math"

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

export fn area(shape: Shape): number {
  return match shape {
    Circle { r } => PI * r * r,
    Rect { w, h } => w * h,
    Empty => 0,
  }
}

export fn keyName(key: string): string {
  return match key {
    "Enter" | "Return" => "submit",
    k if k.length == 1 => "character",
    _ => "other",
  }
}

export fn size(n: number): string {
  return match n {
    0 => "none",
    1..10 => "a few",
    10..=99 => "many",
    _ => "lots",
  }
}

Shape is a type with variants (Types). Patterns can be literals, null, _, a name, alternatives (p | q), variants (Circle { r }), record patterns ({ kind: "rect", w }), list patterns ([first, ...rest]), ranges of numbers (1..10), type tests (n is number) and guards (k if k.length == 1).

if let and let … else ​

if let runs a block when a value matches a pattern, with the pattern's names bound inside. Against a T?, a plain name matches when the value isn't null, and is a T there. let … else binds for the rest of the block, or runs its else, which must leave (return, fail, break or continue).

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

export fn radius(shape: Shape): number {
  if let Circle { r } = shape { return r } else if let Rect { w } = shape { return w / 2 }
  return 0
}

export fn greet(name: string?): string {
  let n = name else { return "Hello, stranger" }
  if let first if first.length > 1 = n { return `Hello, ${first}` }
  return "Hello"
}

The guard (if first.length > 1) goes before the =. In markup, @if let does the same: @if let Circle { r } = shape { <Text>{r}</Text> } @else { … }.

Errors ​

A function that can fail says so in its type: number ! PortError is a number or a PortError. fail gives the caller an error, and the caller must handle it: try passes it on, let v, err = try … checks it, and try … else gives a fallback.

weft
import { parseNumber } from "std/math"

type PortError = NotANumber { text: string } | OutOfRange { port: number }

export fn parsePort(text: string): number ! PortError {
  let n = try parseNumber(text) else fail NotANumber { text }
  if !n.isInteger() || n < 1 || n > 65535 { fail OutOfRange { port: n } }
  return n
}

export fn portOr(text: string, fallback: number): number {
  return try parsePort(text) else fallback
}

There is no throw and no catch. A bug, such as an index out of range, is a panic, which ends the turn and is reported. Running out of time or memory is a stop (Limits). Errors has the whole story.

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