# The language

Declarations, types, logic, calls that can fail, files and packages. Markup
is in [markup.md](markup.md); when things run and re-run is in
[reactivity.md](reactivity.md). Back to the [map](README.md).

```mote
// docs: whole
shape Todo
  id: string
  title: string
  done: bool

state todos: Todo[] = [] persist
state draft = ""
derive left = todos.filter(t => !t.done).length

action add
  if draft.trim() == "" return
  todos.push({id: uid(), title: draft, done: false})
  draft = ""

action remove(id: string)
  todos = todos.filter(t => t.id != id)

column gap=8 padding=16
  row gap=8
    input value=draft placeholder="What next?" submit=add
    button "Add" press=add
  for t in todos key=t.id
    row gap=8 align-items=center
      input type=checkbox checked=t.done
      text t.title color=(t.done ? "dim" : "fg")
      button "×" press=remove(t.id)
  text `${left} left` color=dim
```

## Mental model

A file is an app. It holds declarations (what the page knows and can do) and
markup (what it shows), in any order; the compiler reads all declarations
first, so a name may be used above the line that declares it.

The compiler turns the file into one HTML page:

1. `lex.rs` cuts the text into tokens. Indentation is the block structure: a
   deeper line opens a block, a shallower one closes it. Spaces only; a tab
   in indentation is refused. A line end inside `( )`, `[ ]` or `{ }` is
   just a space.
2. `parse.rs` (`Parser::body`) reads each top-level line. A line that starts
   with a declaration word and a name (`state n`, `fn f`, `shape T`, …) is a
   declaration. Anything else is markup.
3. `types.rs` (`check`) checks every expression. Types are inferred, so most
   programs write few of them.
4. `emit.rs` writes the logic as JavaScript; `view.rs` writes the markup.
   State becomes a signal; what reads it re-runs when it changes
   ([reactivity.md](reactivity.md)).

Three rules shape everything else:

- **Only an `action` (or a `{…}` handler, a `task`, a timer) writes state.**
  A `fn` is pure. A binding in markup and a `derive` only read.
- **A call that can fail must be settled where it is made**, with `else` or
  `?`. Nothing fails silently and nothing is thrown past you.
- **Nothing says `async` or `await`.** A call that leaves the page (the
  network, a file, a worker, the back end) is waited for by the compiler.
  Only an action, a fn, a handler, a task or a resource can wait.

## Declarations

| Line | What it declares |
|---|---|
| `state n = 0` | A value the page shows and actions change. |
| `state todos: Todo[] = [] persist` | The same, kept in `localStorage` under its name between visits. |
| `derive left = todos.filter(t => !t.done).length` | A value worked out from state; it follows what it reads. |
| `action add` / `action set(v: string)` | Statements that may write state. |
| `fn total(xs: number[]) = xs.length` | A pure function, in one line. |
| `fn f(a: T): R` + an indented block | A pure function with a body. `: R` is optional. |
| `shape Todo` + indented `field: type` lines | A named record type. |
| `component Badge(label: string, tone: string?)` | A piece of markup with its own declarations ([markup.md](markup.md#components)). |
| `resource posts: Post[] = net.get(url) else []` | A value loaded in the background ([reactivity.md](reactivity.md#resources)). |
| `task` / `task load` | Statements that run when the page opens ([reactivity.md](reactivity.md#tasks)). |
| `every 1000` / `after 500` | Statements on a timer ([reactivity.md](reactivity.md#timers)). |
| `watch active` | Statements that run after a value changes ([reactivity.md](reactivity.md#watch)). |
| `fill "bar.tools"(row: Row)` + markup | What this file draws wherever any file wrote `slot "bar.tools" row=r` ([markup.md](markup.md#components)). |
| `use "./parts.mote"` | Another file's declarations ([below](#files-and-use)). |
| `app "Todos" accent=#0a84ff` | The page's title and settings ([below](#app)). |
| `server fn`, `server live fn`, `live`, `on name(…)` | The back end ([back-end.md](back-end.md)). |
| `model Note`, `local model Note` + its fields and rules | A schema that is also typed reads and writes ([models.md](models.md)). |
| `off fn`, `main fn` | Where a fn runs ([reactivity.md](reactivity.md#workers)). |
| `fns main`, `fns off`, `fns auto` | The same, said once for the plain fns of a file, before its first ([reactivity.md](reactivity.md#said-once-for-a-file-or-a-package)). |
| `shortcut "mod+k" find` | A chord the whole page hears ([events.md](events.md#shortcuts-for-the-whole-page)). |

A name is declared once in a program, whichever of its files declares it
(`use` makes them one program). A second one is refused (`H022`), at the
later of the two, with where the other is:

```text
extras.mote:12:1: error[H022]: `clockOf` is declared twice: a fn here, and a fn at lib.mote:31
```

`state`, `derive`, `resource`, `live`, `fn` and `action` share their names
(an action cannot be called what a state is); `shape` and `model` share
theirs; components have their own, so a model and a component (yours or the
kit's `Command`) may be called the same. A component's own declarations are
its own: two components may each have a `fn label`.

### state

```mote
// docs: whole
state n = 0
state name: string? = none
state tags: string[] = []
state theme = "light" persist

text `${n} ${name ?? "nobody"} ${tags.length} ${theme}`
```

The first value gives the type. An empty list or `none` says too little, so
those two need the type written (`H061` otherwise). `persist` keeps the value
as JSON in `localStorage` under the state's own name; the first value is used
only when nothing was kept (`runtime/page/dom.mote`, parts `PG` and `PW`).

A state's first value may read other state and call fns, but it may not wait
or write.

### Addresses

`url` takes an address apart and puts one together, in the page and on the
back end alike.

| Call | Gives |
|---|---|
| `url.encode(text)` | The text percent-encoded, to stand in a path or a query: `"a b&c"` is `"a%20b%26c"` (JavaScript's `encodeURIComponent`). |
| `url.decode(text)` | The other way. It can fail (text that is not percent-encoded: a lone `%`), so it meets `else` or `?`. |
| `url.query(text)` | A query or a form-encoded body (`"text=hello+there%21&channel=%23general"`, with or without a leading `?`) as a record of texts, `json`: `{text: "hello there!", channel: "#general"}`. A `+` is a space, as a form sends it. Of a name given twice, the last. |
| `url.form({q: "oak door", page: 2})` | The other way: `"q=oak+door&page=2"`. A field that is `none` is left out. |
| `url.parse(text)` | `{scheme, host, port, path, query, hash}`: `"https"`, `"example.com"`, the port as a number (0 when the address names none: the scheme's own), the path as the address writes it (still percent-encoded), the query as `url.query` gives it, and what follows `#`. It can fail (not an address). |
| `url.build({host, scheme?, port?, path?, query?, hash?})` | An address from its parts: `scheme` unsaid is `"https"`, `path` `"/"`; `query` is a record as `url.form` takes it. The path is written as addresses are (a space is `%20`). |

```mote
// docs: whole
state address = "https://example.com:8443/find?q=oak+door&page=2#top"

fn told(a: string): string
  let u = url.parse(a)?
  return `${u.host} port ${u.port}, looking for "${u.query.q}"`

fn next(a: string): string
  let u = url.parse(a) else none
  if u == none return a
  return url.build({...u, query: {...u.query, page: Number(u.query.page ?? 1) + 1}})

column gap=8 padding=16
  input value=address
  text (told(address) else "not an address")
  text next(address)
  text `/tag/${url.encode("c++ & more")}`
```

Source: `runtime/shared/patterns.mote` (part `UR`).

### derive

A `derive` is an expression. It runs once, then again whenever state it read
changes. It cannot be assigned (`H031`), cannot write state (`H030`) and
cannot wait (`H082`).

`derive first: string? = xs.at(0)` says its type, as a `let` may: the value is
checked against it, and it is that type to whatever reads it (a `json` the
back end gave, made a `json[]`: `derive rows: json[] = got.rows ?? []`).

```mote
// docs: whole
server fn quick(): number requires anyone
  return 1
server fn slow(): number requires anyone
  return 2

state got: json = {rows: ["a", "b"]}
state n = 0
derive rows: json[] = got.rows ?? []
derive first: string? = rows.at(0)

component Pill(label: string, loud: bool?)
  text label font-weight=(loud == true ? 700 : 400)

action pick(fast: bool)
  n = fast ? quick()? : slow()?

column gap=8
  Pill loud label=`${first ?? "none"} of ${rows.length}`
  button "Pick" press=pick(true)
  text `${n}`
```

(`Pill loud`: a lone word straight after a component's name is a `bool` prop
of that name, true, where the component has one: [kit.md](kit.md#pitfalls).)

### action

An action's body is statements. Parameters need types. An action is called
from a handler (`press=add`, `press=remove(t.id)`) or from another action.
An action that waits keeps `pending(name)` and `failure(name)` for the page
([below](#a-call-that-can-fail)). `action find(q: string) newest`: called
again while it waits, the earlier run is called off
([reactivity.md](reactivity.md#newest-a-later-run-calls-an-earlier-one-off)).

### fn

A fn is pure: it reads its parameters, other fns, and (unless it is to run in
a worker or on the back end) state. Writing state in a fn is refused
(`H030`: "make it an `action`"). Parameters need types (`H060`). The return
type is inferred; write it (`fn f(a: T): R`) when you want it checked.

A fn that loops or recurses and uses only its parameters and other such fns
runs in a worker when an action, handler, task or resource calls it. That is
decided by the compiler; `main fn` and `off fn` override it, and `fns main`
at the top of a file (or `fns = "main"` in `mote.toml`) says it for all of them
([reactivity.md](reactivity.md#workers)).

### wasm fn

**Experimental.** Ahead of JavaScript on counters, indexes and small records, level or behind elsewhere ([the measurements](../bench/README.md)).
`wasm fn` compiles a fn, and every plain fn it calls, to one WebAssembly module:

```mote
// docs: whole
shape Pt
  x: number
  y: number

fn far(p: Pt): number = Math.sqrt(p.x * p.x + p.y * p.y)

wasm fn farthest(ps: Pt[]): number
  let most = 0
  for p in ps
    most = Math.max(most, far(p))
  return most

text `${farthest([{x: 3, y: 4}, {x: 6, y: 8}])}`
```

- It gives the same answers as the same fn without the word, which is still
  compiled to JavaScript too: that runs until the module is ready (a moment
  after the page opens), in its place wherever there is no WebAssembly, and
  everywhere when the back end is started with `MOTE_WASM=off`.
- What can go: numbers, bools, shapes whose fields can go, lists of those;
  `let`, writes, `if`, `while`, `for … in`, `return`, `break`, `continue`;
  arithmetic and comparisons, `Math.*`, `.length`, `xs[i]`, `xs.push(v)` on a
  line of its own, a shape or a list written out where its type is known,
  and calls of other plain fns. Anything else is refused (`H220`), and it
  must say what it gives (`H221`).
- It reads only what it is handed, and what it is handed is a copy: a write
  to a parameter, or to part of one, is refused. Build what changes inside
  it and return it.
- A number that is only ever whole (a counter, a length, an index) is kept
  as a whole number, and a `number` parameter used as one is taken to be one.
  When that turns out wrong for a call (it was handed 2.5, a sum went past
  what a number holds exactly, an index was outside its list), the call is
  run again as JavaScript: the answer is the same either way, only slower.
  `int` in a type says a whole number outright.
- Calls between the fns of the group cost nothing extra; each call from
  outside copies its arguments in and its answer out, so a `wasm fn` should
  be the fn with the loop in it, not a small fn called in a loop.

A parameter at the end that may be none (`T?`) may be left out of a call,
and is none: so a fn, a `server fn` among them, can take one more thing
later without every call changing. Those before it are given, in order
(`H064` says how many it takes).

```mote
// docs: whole
fn greet(name: string, title: string?): string = title == none ? `Hello, ${name}` : `Hello, ${title} ${name}`

server fn visits(days: number, app: string?): number requires anyone
  return days * (app == "planner" ? 2 : 1)

text greet("Ada")
text greet("Ada", "Dr")
```

### shape

```mote
// docs: whole
shape Point
  x: number
  y: number

shape Line
  from: Point
  to: Point
  label: string?

state l: Line = {from: {x: 0, y: 0}, to: {x: 3, y: 4}}
fn length(l: Line) = Math.sqrt((l.to.x - l.from.x) * (l.to.x - l.from.x) + (l.to.y - l.from.y) * (l.to.y - l.from.y))

text `${length(l)} ${l.label ?? ""}`
```

A shape is a name for a record type. Shapes may refer to each other and to
themselves. A field typed `T?` (or `json`, which may be `none`) may be left
out of a literal.

#### A shape as a JSON Schema

`schema(Line)` is the shape's fields as a JSON Schema (and `schema([Line])`,
`schema({total: number})`, any type [`check`](data.md#check) takes), and
`schema(length)` a fn's parameters as one (an object of their names),
worked out when the program is compiled and written into it as a literal:
what a model's tool takes, or the shape its answer is to have
([ai.md](ai.md#tools-and-answers-from-the-programs-own-types)), or what
another service is told to send.

```mote
// docs: whole
// A point on the page.
shape Spot
  // Across, in pixels.
  x: number
  y: number
  label: string?

server fn spotSchema(): string requires anyone = JSON.stringify(schema(Spot))

text "schema"
```

Every object is `additionalProperties: false`; a field is in `required`
unless it is `T?` or `json`; `T?` is `anyOf: [T, null]`; `T[]` an array;
`json` is `{}` (anything); bytes a base64 `string`; a shape inside is
written out where it stands, but for a shape that holds itself, written
once under `$defs` and named by `$ref`. `{strict: true}` puts every field
in `required` (a `T?` may still be null), as model services' strict modes
ask. The comment right above the shape, a field or the fn is its
`description`. What is not a type is `H318`; a fn's type has no schema
(`H313`). `check(value, T)` holds a value to the same type as the program
runs.

### app

`app "Name"` sets the page's title. Its settings:

| Setting | Effect |
|---|---|
| `accent=#0a84ff` | The accent colour: the `accent` role, the theme colour, the made icon's ground, form controls. |
| `scheme=dark` or `scheme=light` | Fixes the colour scheme whatever the system says. |
| `lang="de"` | The language the page is written in: `<html lang="de">`, which screen readers, translators, hyphenation and a field's spell checking follow. A language tag: `"pt-BR"`, `"zh-Hant"`. Unsaid: `"en"`. One that changes while the page runs is `root lang=…` ([markup.md](markup.md#values-of-the-whole-page)). A tag of another shape is refused (`H231`). |
| `toasts="top"` | Where the notes of `toast(…)` stand: an edge (`top`, `bottom`) and a side (`left`, `center`, `right`), as `"top right"` or `"bottom left"`; an edge alone is its centre. Unsaid: `"bottom right"`. |
| `edges=cover` | The page goes to the screen's edges, under a phone's notch and home bar ([markup.md](markup.md#the-screens-edges)). |
| `agents=off` | Leaves out everything written for agents ([agents.md](agents.md)). |
| `writes=confirmed` | Every write of a model from the page waits for the back end before it shows ([models.md](models.md#a-write-shows-at-once)). Unsaid: they show at once. |
| `timeout=30000` | How long a call to the back end may take, in ms, before it counts as unanswered ([back-end.md](back-end.md#a-call-is-answered-once)). Unsaid, or `timeout=0`: no limit. |
| `policy=strict` | The page is sent with a Content-Security-Policy made from its own build, and the headers that go with it; `connect="…"`, `images="…"`, `media="…"`, `frames="…"` list the other origins it may reach ([delivery.md](delivery.md#the-strict-policy)). |
| `update=ask` | An installed app keeps its build until the page says `app.update()` ([delivery.md](delivery.md#updates-that-ask)). Unsaid, or `update=auto`: a new build takes over by itself. |

Any other setting is refused (`H047`). Without `app`, the title is the entry
file's name (or its folder's, for `app.mote` and `index.mote`), capitalised.

## Types

```text
string  number  bool  none  bytes  json
image  sheet  video  sound  font  database  element  pen  picked
T[]     T?     a shape's name     {x: number, y: number}
```

- **Inferred** everywhere except parameters, shape fields, and an empty or
  `none` first value.
- **Structural.** A literal fits a shape when its fields do. A misspelt or
  missing field is named in the message.
- **`json`** fits anything and is not checked. It is what `net.get`,
  `JSON.parse` and `db.get` give. Give it a type where it lands:
  `let xs: Post[] = net.get(url)?`.
- **No unions.** `T?` ("T or none") is the one "or".
- `int` is accepted as another word for `number`. A function type
  (`() => none`, `(a: T) => R`) may be written on a component's prop; it is
  read and not checked.
- `image` is `{width, height, data: bytes}` (with `depth`, `space` and
  `profile` if it has them); `sheet`, `video`, `sound`,
  `database` are small records with an `id` ([media.md](media.md),
  [data.md](data.md)); `font` is a font file that has been read, with its
  facts ([text.md](text.md#font)); `element` is what `ref=` fills
  ([events.md](events.md#the-element-itself)); `pen` is what a `surface`
  draws with ([drawing.md](drawing.md)).

### none and T?

`none` is the one nothing. There is no `null` and no `undefined`.

A `T?` must be settled before `.`, an index, or arithmetic (`H062`, `H065`):

```mote
// docs: whole
shape User
  name: string
  age: number

state users: User[] = [{name: "Ada", age: 36}]
state picked: User? = none

fn label(u: User?): string
  if u == none return "nobody"
  return `${u.name}, ${u.age}`

action pick(name: string)
  picked = users.find(u => u.name == name)

column
  text label(picked)
  text (picked?.name ?? "no one yet")
  if picked
    text `${picked.age + 1} next year`
  button "Ada" press=pick("Ada")
```

Ways to settle it: `x?.f` (gives `none` if `x` is), `x ?? d`, `if x …`,
`if x != none …`, `if x == none return` (the rest of the block knows it is
there; so it does after `fail("…")?`, `continue` and `break`, on the `if`'s
line or as the last line under it), and `&&`, `||`, `c ? a : b` on such tests. The narrowing holds for a
plain name, not for a field chain: bind the value with `let` first.

`find()`, `findLast()`, `pop()`, `shift()` and `at()` give `T?`. `xs[i]`
gives `T` (the checker does not know the length).

### What is refused

| You write | Message |
|---|---|
| `n == "1"` (different types) | `H066`: always false |
| `s - 1`, `s * 2` on a non-number | `H065`: convert it with `Number(…)` |
| `` `${xs}` ``, `text user` (a list or record as text) | `H069`: use `for`, `.join(", ")`, or show a field |
| `text someBytes` | `H069`: show it as `.hex()`, `.base64()` or `.text()` |
| `image p` where `p` is an `image` (pixels) | `H069`: show it as a file, `img.png(p)?.url("image/png")`, or draw it ([media.md](media.md#mental-model)) |
| `xs.length()` | `H063`: `length` is a value |
| `any`, `boolean`, `String`, `null` as a type | `H073`, with the right word (`json`, `bool`, `string`, `none`) |

## Logic

```mote
// docs: whole
state xs = [3, 1, 2]
state name = ""
state n = 0

fn size(n: number): string
  match n
    0 return "none"
    1, 2 return "few"
    else return "many"

action work
  let first = xs.at(0)
  if first == none return
  xs.push(first + 1)
  for x in xs
    if x == 1 continue
    if x > 100 break
    n += x
  let i = 0
  while i < 3
    i += 1
  if n > 10 name = "big" else name = "small"
  let copy = [...xs, 9]
  let rec = {n, name, ...{extra: true}}
  log(copy, rec, i > 1 ? "a" : "b")

text `${size(xs.length)} ${name}`
button "work" press=work
```

- `let x = e` · `let x: T = e` · `x = e`, `+=`, `-=`, `*=`, `/=`
  A `let` is seen from its line to the end of its block. A block declares a
  name once: a second `let` of it, or a `let` of one of the fn's parameters
  or of the loop's own name, is refused (`H022`; write `x = e` to change
  it). An inner block (under an `if`, a `for`, a `while`) may declare a name
  an outer one has, or a `state`'s: the outer one is back after the block.
  Its own value may not read the one it hides (`let n = n + 1`: `H022`).
  In markup the block is the `if`, `for`, route or component a `let` is in,
  whatever element it is written under.
- `if c` + block, `else if c`, `else` · `if c stmt` on one line, and
  `if c stmt else stmt` (the `else` may also go on the next line). On one
  line an `else` is always the `if`'s, never the fallback of a call that
  can fail (`if p save(p) else p` is refused, `H081`, and says so): put
  such a call, with its own `else`, on a line of its own under the `if`.
- `for x in xs` · `for x, i in xs` (`i` counts the turns from 0, as in markup) · `while c` · `return e` · `break` · `continue`
- `atomic` + a block: the model operations in it are one ([models.md](models.md#atomic))
- `x => e` · `(a, b) => e` (a lambda is one expression)
- `c ? a : b` · `a ?? b` · `a?.b` · `!a` · `-a`
- `+ - * / %` · `< <= > >=` · `==` and `!=` are strict · `&&` `||`
- `& | ^ ~ << >> >>>` on numbers, as 32-bit integers (JavaScript's). They
  bind tighter than a comparison and looser than arithmetic, `<< >> >>>`
  tightest, then `&`, `^`, `|`: `x & 1 == 0` is `(x & 1) == 0` (not
  JavaScript's reading), `c >>> 1 ^ poly` is `(c >>> 1) ^ poly`, `1 << n + 1`
  is `1 << (n + 1)`. `>>> 0` makes a result unsigned. In markup, as any
  operator, they go in parentheses: `text (flags & 4)`.
- `` `text ${e}` `` (may span lines) · `"text"` or `'text'` with `\n \t \r \\ \"`
- `r"\d+"`: a raw string, nothing in it is an escape, a backtick and a quote `'` included; it ends at the next `"` ([text.md](text.md#patterns))
- `[a, ...b]` · `{k: v, k, ...o}` · `true` `false` `none`
- Numbers: `12`, `1.5`, `2e3`, `0xff`. Colours are values too: `#0a84ff`, `#fff`.
- `// a comment` to the end of the line. The `//` lines directly above a
  declaration (or a shape's or model's field) are its documentation: an editor
  shows them where the name is hovered ([editor-plugin.md](editor-plugin.md#comments-that-document)).

### match

```text
match x                            arms indented: values (comma-separated), or else
  0 return "none"                    an arm is one statement, or a block under it
  1, 2 return "few"
  else return "many"
```

`match` compares with `==`, top to bottom. It is the same in markup, with
markup under each arm ([markup.md](markup.md#control)).

### Writes

State is written by assigning it, or by changing it in place: `push`, `pop`,
`shift`, `unshift`, `splice`, `sort`, `reverse`, `fill`, `remove(x)`, and
`t.done = true`. Writes are allowed only in an action, a `{…}` handler, a
task or a timer.

The compiler traces each write back to the state the value came from and
tells that state's readers (`emit.rs`, `Gen::write` and `Gen::srcs`). So this
works, though `t` is a local:

```mote
action finish(id: string)
  let t = todos.find(t => t.id == id)
  if t t.done = true            // tells `todos`
```

`xs.remove(x)` takes the first `x` out of a list. `xs.sort()` in a binding
or a derive is refused, because it changes the list: write `toSorted()`
(likewise `toReversed()`), or sort in an action.

### Built in

| Call | Gives |
|---|---|
| `uid()` | A new unique id (a UUID string). |
| `now()` | The moment, in milliseconds. |
| `log(x, …)` | Writes to the console. |
| `time.clock(now())` | `"2:22 PM"`, as the reader's own place writes it. In a zone, a language, 12 or 24 hours: [time](#time). |
| `time.date(now())` | `"Thu, Nov 12"`, likewise. |
| `url.encode(text)` `url.decode(text)?` `url.parse(text)?` `url.build({…})` `url.query(text)` `url.form({…})` | Addresses ([below](#addresses)). |
| `store.get(k)` `store.set(k, v)` `store.remove(k)` | `localStorage`, values as JSON. `store.get` gives `none` when there is nothing. |
| `go("/path")` `back()` `forward()` `route.path` | Addresses ([markup.md](markup.md#routes)). |
| `route.url` `route.origin` `route.link("/path")` | The page's whole address, its origin, and the whole address of one of its paths ([markup.md](markup.md#routes)). |
| `route.fragment` `route.setFragment(text)` `route.takeFragment()` | What stands after `#` where routes are paths: read, changed, or read and taken out of the address ([markup.md](markup.md#the-fragment)). |
| `net.online` | Whether the page can reach out: the browser's word (not for a page served from this machine), and the line to the back end ([back-end.md](back-end.md#is-there-a-line-netonline)). Reactive. |
| `screen.visible` `screen.focused` `screen.idle(ms)` | Whether the page is in front, has the keyboard, and has been left alone ([markup.md](markup.md#in-front-and-at-it)). |
| `toast("Saved", "A second line", "error")` | A note in the corner for four seconds; the last two are optional. Which corner: `app … toasts="top"` ([app](#app)). Three notes show at most; more wait their turn (and hurry the oldest along). A note stays while the pointer is on it, and only a note's own box takes presses: what is beside and between the notes can still be pressed. |
| `title("(3) Inbox")` `badge(3)` | The page's title, and a number on the app's icon; `title("")` and `badge(0)` put back and take away. Kept current from state by `root title=… badge=…` ([markup.md](markup.md#values-of-the-whole-page)). |
| `share()` `share({title, text, url, files})` | Opens the share sheet with the page (its title, description and address), or copies the link and says so where there is none. Gives `"shared"`, `"cancelled"`, `"copied"` or `"shown"`; never fails ([data.md](data.md#share)). |
| `copy(text)` | Puts text on the clipboard. It never waits or fails; reading the clipboard, or putting a picture on it, is `clipboard.…` ([data.md](data.md#clipboard)). |
| `close()` `close("id")` | Closes the popover or dialog the reader is in; the one with that id ([markup.md](markup.md#popover-and-tip)). |
| `focus("id")` | Puts the keyboard in the element with that id (wherever it was drawn: another component's field too); a field's caret is where it was, as with `el.focus`. `focus("id", true)` also selects a field's words, ready to be typed over. |
| `scroll("id", where)` | Scrolls that element: `"start"`, `"end"`, `"next"`, `"prev"` (a screenful), or the id of something inside it to bring into view. A third `{behavior: "instant"}` does it at once. |
| `scroll(target, {inside, block, behavior})` | Brings an element (an id, or a `ref=`'s) into view: `block` `"start"` `"center"` `"end"` `"nearest"`, `behavior` `"smooth"` `"instant"`, `inside` the one scroller to move ([events.md](events.md#the-element-itself)). |
| `fail("why")?` | Ends the fn or action with that failure ([below](#a-call-that-can-fail)). |
| `s.isEmpty()` `xs.isEmpty()` | Whether a string or a list is empty. |

JavaScript's own methods on strings, lists and numbers are there under their
own names (`trim`, `split`, `map`, `filter`, `find`, `reduce`, `toFixed`, …),
and so are `Math`, `JSON`, `Date`, `Number`, `String`, `Object`, `Array`,
`Boolean`, `parseInt`, `parseFloat`, `isNaN`, `structuredClone`,
`performance`. There is no `new`: use `Date.now()` or `now()`, not
`new Date()`. `Map` and `Set` are named but cannot be made without `new`;
use a record or a list. The checker knows the common methods' types and
suggests the right name for a habit from another language (`contains` →
`includes`, `len` → `.length`, `append` → `push`).

The namespaces (`net`, `db`, `sql`, `fs`, `img`, `re`, …) are listed in the
[map](README.md#namespaces).

### time

A moment is a number: milliseconds, as `now()` gives. `time` writes one
down, and does sums on one, in a zone and a language. None of it waits or
fails, so all of it may stand in a binding.

```mote
// docs: whole
state zone = "Asia/Tokyo"
state at = now()

fn tomorrowAtNine(from: number, z: string): number
  let p = time.parts(from, z)
  return time.of({...p, day: p.day + 1, hour: 9, minute: 0, second: 0}, z)

column gap=4
  text `${time.clock(at, {zone, hours: 24})} there, ${time.clock(at)} here (${time.zone()})`
  text time.date(at, {zone, lang: "de", style: "full"})
  text `the reminder is ${time.words(tomorrowAtNine(at, zone), {from: at})}`
  select value=zone
    for z in time.zones()
      option z value=z
```

| Call | Gives |
|---|---|
| `time.clock(at, {zone, lang, hours, seconds}?)` | `"2:22 PM"`. `hours: 12` or `24` (unsaid: as the language has it); `seconds: true` adds them. |
| `time.date(at, {zone, lang, style, year}?)` | `"Thu, Nov 12"`. `style`: `"short"` Nov 12 · `"medium"` (unsaid) · `"long"` November 12, 2026 · `"full"` Thursday, November 12, 2026 · `"numeric"` 11/12/2026 · `"month"` November 2026 · `"weekday"` Thursday · `"iso"` 2026-11-12 (the same in every language). `year: true` adds the year to the short ones. |
| `time.words(at, {from, zone, lang, style}?)` | How far `at` is from `from` (unsaid: now): `"now"`, `"in 20 minutes"`, `"3 hours ago"`, `"yesterday"`, `"tomorrow"`, `"in 3 days"`, `"last week"`, `"2 months ago"`. Within an hour, by the minute; on the same day (or under six hours), by the hour; past that by the calendar in `zone`. `style`: `"long"` (unsaid), `"short"`, `"narrow"`. |
| `time.parts(at, zone?)` | `{year, month, day, hour, minute, second, weekday, offset}`: the calendar and the clock there. `month` is 1 to 12, `weekday` 0 (Sunday) to 6, `offset` the minutes the zone is ahead of UTC at that moment (Berlin in summer: 120). |
| `time.sleep(ms)` | Waits that long and does nothing else: the pause of a poll that asks again (`replicateWait` in [replicate.md](replicate.md)). The one call of `time` that waits, so it is a statement, in a fn or an action. In a test (`mote test`) it does not wait. |
| `time.of({year, month, day, hour?, minute?, second?}, zone?)` | The moment that reads so there. A number past its end carries on (day 32 is the 1st or 2nd of the next month; hour 25 is one o'clock the day after), so `{...p, day: p.day + 1, hour: 9, minute: 0}` is tomorrow at nine whatever the clocks do in the night. |
| `time.add(at, {years, months, weeks, days, hours, minutes, seconds}, zone?)` | `at` moved on (or back, with negatives). Years to days go by the calendar there: the clock reads the same afterwards, also across a change of the clocks, and the 31st plus a month is that month's last day. Hours and less are exact. |
| `time.next({hour, minute?, weekday?}, zone?, from?)` | The first moment after `from` (unsaid: now) at which a clock there reads that hour and minute; with `weekday` (0 Sunday to 6), on that day of the week. For work that is due at a time of day ([back-end.md](back-end.md#at-a-time-of-day)). Once a day whatever the clocks do: a time they skip that day is met an hour later (02:30 on the night they go forward is 03:30), and one they repeat is its first time only. |
| `time.startOf(at, unit, {zone, lang, first}?)` `time.endOf(…)` | The first moment, and the last millisecond, of the `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"` or `"year"` that `at` is in. A week starts on `first` (0 Sunday to 6), else where `lang` starts its weeks. |
| `time.stamp(at, zone?)` | `"2026-11-12T14:22"`: what an `input type="datetime-local"` holds. `.slice(0, 10)` is what `type="date"` holds. |
| `time.read(stamp, zone?)` | The moment such a stamp (or a date alone, `"2026-11-12"`: its first moment) names there: a `number?`, `none` for anything else. |
| `time.zone()` | This device's zone: `"Europe/Berlin"`. The page's alone (`H092` on the back end). |
| `time.zones()` | Every zone there is, `"UTC"` first: about 400 names, as `Intl` lists them. |
| `time.weekStart(lang?)` | The day a week starts on there: 0 (Sunday) to 6. `"en-US"` 0, `"de"` 1, `"ar-EG"` 6. |

- A **zone** is an IANA name (`"America/New_York"`, `"UTC"`); a **language**
  is a tag (`"de"`, `"en-GB"`, `"ja"`). Left out, each is the reader's own.
  One nobody knows counts as left out: nothing here throws, so a binding
  may be given a zone a person typed. `time.zones().includes(z)` says
  whether a zone is known.
- **An hour the clocks skip** (02:30 on the night they go forward) is read
  by `time.of` as the hour after (03:30); **an hour they repeat**, as its
  first time.
- **On the back end there is no reader.** In a `server fn`, what depends on
  a zone must be given one (`H064`: `time.clock(at, {zone: m.zone})`), and
  `time.zone()` is refused: keep each person's `time.zone()` in their row,
  written by their page. A language left out there is English. (A plain
  `fn` that both sides call is checked as the page's; where it runs on the
  back end without a zone, the zone is UTC.)
- `now()` is not followed: a page that shows "in 20 minutes" keeps a state
  it sets `every 30000` and passes it as `from`.

Built on the host's `Intl` (`runtime/shared/time.mote`, part `TI`), so the
words are the browser's (or Bun's) own. Recorded in
`tests/expect/real_zone_lang_page.txt` and `tests/expect/real_server_net.txt`.

## A call that can fail

Every call that leaves the page can fail: the network, storage, a battery, a
back-end call. Its type is written `T!` in messages. It must meet one of
these at once, or it is refused (`H081`):

```text
x else fallback                  the fallback on failure
x else err => …                  the handler gets the failure's message (a string)
x?                               pass the failure on
x else err => (… ? y : err?)     settle some failures, pass the others on as they came
```

```mote
// docs: whole
shape Post
  id: number
  title: string

state report = ""

fn count(url: string): number
  let xs: Post[] = net.get(url)?
  return xs.length

action tally
  let a = count("posts.json") else -1
  let b = count("nope.json") else err => err.length
  let c = count("more.json")?
  report = `${a} ${b} ${c}`

column
  button "Tally" press=tally disabled=pending(tally)
  text report
  if failed(tally)
    text `It failed: ${failure(tally) ?? ""}` color=danger
```

A `?` right before the `:` of a `c ? a : b` is the first branch's own: `n = c
? one()? : two()?` passes either call's failure on.

What `?` does depends on where it is:

- **In a fn**, `?` makes the fn one that can fail: its callers must settle
  it in turn (`count` above).
- **In an action**, a task or a `{…}` handler, the action stops there. An
  action keeps the failure: `failure(action)` is its message (a `string?`),
  `failed(action)` whether there is one, `pending(action)` whether a run is
  in flight. So calling an action cannot fail. A fault (nobody answered, the
  back end broke, something threw) is also logged to the console; a failure
  the program made on purpose is not (below).
- **In a binding or a derive** there is nowhere for it to go: `?` is refused
  there. Use `else`.

A `?` may be followed at once by more: `Note.add(row)?.id` (the `?`, then
`.id`), `count()? == 0`, `find()? ?? []`. After a test on one line it ends
the test: `if Room.has({name})? return`. (A `?` begins `c ? a : b` only
when the `:` follows.)

`pending`, `failed` and `failure` take the name of an action or a resource
(`H083` otherwise). They are reactive: `button "Save" disabled=pending(save)`.
`pending` also takes a row of a model: `pending(m)` is true while a write
of that row, which the page has already shown, has not been answered by
the back end ([models.md](models.md#a-write-shows-at-once)).

`fail("out of stock")?` makes a failure on purpose. It works in a fn or an
action, in the page and on the back end; the caller's `else` or
`failure(action)` gets the words. Such a failure is an answer, not a
fault: an action it stops (whether or not the action waits) keeps the
words for `failure(action)` and writes nothing to the console. The same
goes for what a `server fn` said with `fail`, a model's
`check … else "why"` and a rule's refusal. So a person's mistake can be
said with `fail` and shown from `failure(action)`.

A failure is its words wherever it is put in text, and also says what kind
it is: under `else err => …`, `err.kind` (`"offline"`, `"signin"`,
`"refused"`, `"invalid"`, `"toobig"`, `"full"`, `"memory"`, `"taken"`, `"fault"`, `"said"`, or the program's
own word), `err.id`, `err.data`, `err.where` and `err.words`; of an action
or a resource, `failure(save)?.kind` and the rest. `fail("out of stock",
{kind: "stock", data: {sku}})?` gives one its kind and data. **`err?`**, in
the handler, passes the failure on as it came (its kind, data and id; a
fault stays a fault): `Note.add(row) else err => (err.kind == "taken" ?
none : err?)` settles one kind and lets the rest go to the caller, where
`fail(err)?` would make a new failure, of the kind `"said"`, from its words.
`err?` stands only in such a handler (`H080` elsewhere, as for any `?` after
a value that cannot fail). `on
failure(f)`, at the top level, hears every failure nothing else did. All of
it, with the back end's side, is in
[back-end.md](back-end.md#when-something-fails). `log.info("msg", {fields})`,
`log.warn`, `log.error` and `log.debug` are the console's in a page and
[the log's](back-end.md#logs) on the back end.

The words, shown:

```mote
// docs: whole
state when = ""
state booked = 0

action schedule
  if when.trim() == "" fail("Say when.")?
  booked += 1

column gap=8 padding=16
  input value=when placeholder="When?"
  button "Schedule" press=schedule
  if failed(schedule)
    text (failure(schedule) ?? "") color=danger
  text `${booked} scheduled` color=dim
```

`let xs: Post[] = net.get(url)?`: a `json` result takes the type its `let`
gives it. The type is trusted, not checked at run time.

Only actions, fns, handlers, tasks and resources can wait. A binding or a
`=>` cannot (`H082`): use a resource, or a `for` loop in an action instead of
`map` with a waiting call.

**A `=>` may start an action that waits.** A `=>` that is nothing but a call
of an action (`x => upload(x)`, `e => pasted(e)`) begins the action and
gives none at once; the action goes on by itself, with its own
`pending(upload)` and `failure(upload)`. That is what a callback wants: a
timer, `xs.forEach`, a handler given to something a `json` value holds.

```text
action upload(f: File)                 // waits
  f.url = files.upload(f.data)?
action sendAll
  picked.forEach(f => upload(f))       // all begun, side by side; the next line does not wait for them
  widget.on("change", e => changed(e))   // `widget: json`, what a fn of an `extern js` file gave
```

To have them one after another, and to go on only when they are done, call
the action in a `for` loop: there a call waits. A `=>` that starts an action
is for where state may change (an action, a handler, a task, a `watch`): in
a binding or a `fn` it is refused (`H030`).

**`wait(p)`** waits for a promise that a `json` value holds, and gives what
it comes to, as `json` (what is not a promise is itself). A promise that is
refused is a failure, so it meets `?` or `else` like any call that can fail:

```text
action finish(widget: json)            // what a fn of an `extern js` file gave (js.md)
  let text = wait(widget.value()) else ""   // a promise it gives, or "" if it is refused
  let done: json = wait(widget.ready)?      // what is not a promise is itself
```

Mote's own calls never need it: they wait by themselves
(`clipboard.text()`, `net.get(url)`).

How it works underneath: a waiting action compiles to
`AC(action, async () => {…})` (`runtime/page/actions.mote`, part `AC`), which
counts runs in flight in a signal, catches what is thrown, and puts the
message in another signal. `x else y` is a `try`/`catch` around the call.

## bytes

```mote
// docs: whole
state b: bytes = bytes("hi")
state shot: bytes? = none

action go
  let h = bytes.hex("6869")?
  let g = bytes.base64("aGk=") else bytes("")
  log(b.text(), b.hex(), b.base64(), b.length, b[0], b.slice(0, 1), h, g)

if shot
  image shot.url()
link "Get it" href=b.url("text/csv")
button "go" press=go
```

**Making them**

| Call | Gives |
|---|---|
| `bytes("text")` | The text's UTF-8. |
| `bytes.new(n)` | `n` zeros. |
| `bytes.of([72, 105])` | Bytes from a list of numbers. |
| `bytes.join([a, b, c])` | Them end to end, as new bytes. |
| `bytes.hex(s)` · `bytes.base64(s)` · `bytes.base64url(s)` · `bytes.base32(s)` | Text read back into bytes. Each can fail. base64url is RFC 4648's section 5 (`-` and `_`, no padding needed); base32 its section 6 (A to Z and 2 to 7, as a TOTP secret is written: case, spaces and padding are let be). |
| `bytes.find(b, what, from?)` | Where a run of bytes (or a text's UTF-8) first stands in `b`, from `from` on: a number, -1 where it does not. |
| `bytes.buffer()` | Bytes that grow as they are added to, for a message built piece by piece: `w.add(data)` (bytes, or text as UTF-8), `w.byte(n)`, `w.put("i32be", n)` (a number of a kind `b.write` takes), `w.length`, `w.bytes()` (a copy of all of it), `w.clear()`. Each but the last two gives the buffer back, so they chain: `bytes.buffer().add("Q").put("i32be", 9).bytes()`. |

**Reading them**

| Form | Gives |
|---|---|
| `b.length` · `b[i]` | How many · one byte, a number 0 to 255. |
| `b.slice(from, to)` | A copy of a part; `b.slice()` of it all. |
| `b.text()` `b.hex()` `b.base64()` `b.base64url()` `b.base32()` | Them as text (base64url with no padding, base32 with it). |
| `b.text("windows-1251")?` | Them as text in a character set, by any of its WHATWG labels (`latin1`, `iso-8859-2`, `koi8-r`, `cp1252`, `shift_jis`, …). It can fail, `"unsupported"`: a label that names no set, or a set not read where it runs. UTF-8 and UTF-16 everywhere; the 28 single-byte sets by tables of the standard's own, and the multi-byte ones (Shift_JIS, EUC-JP, ISO-2022-JP, GBK, gb18030 with its four-byte ranges, Big5 with Hong Kong's extensions, EUC-KR) by the charsets battery, the standard's own decoders and index files: the same text in a page, a worker and the back end, malformed bytes too (U+FFFD where the standard says, which a browser's own decoder does not always: [The legacy multi-byte sets](#the-legacy-multi-byte-sets)). `runtime/shared/charsets.mote` and `batteries/charsets`, made by `node tools/charset-tables.mjs` from the WHATWG Encoding Standard's files at a pinned commit. |
| `b.read(at, "u32")` | A number of several bytes, starting at `at`. |
| `a.dot(b)` | Two vectors of 32-bit floats (laid end to end, as `write(at, "f32", v)` lays them; of one length) multiplied number by number and added up: the cosine of two of length 1, all at once and fast. A vector store's search ([ai.md](ai.md#retrieval)). |
| `b.url()` | An address for them, for `image` and `link`: `image shot.url()`, `link "Get it" href=file.url("text/csv")`. |

**Writing into them**, as a list is written into:

| Form | Does |
|---|---|
| `b[i] = v` | One byte. It keeps the low eight bits of `v`. |
| `b.set(other, at)` | Lays bytes, or a list of numbers, in from `at`. They must fit. |
| `b.fill(v, from?, to?)` | That byte throughout, or over a part. |
| `b.write(at, "u32", v)` | A number of several bytes. |

```mote
// docs: whole
state said = ""

fn packed(parts: bytes[]): bytes
  let head = bytes.new(8)
  head.set(bytes("MOTE"), 0)
  head.write(4, "u16", 1)
  head.write(6, "u16be", parts.length)
  let all = [head]
  for p in parts
    let n = bytes.new(4)
    n.write(0, "u32", p.length)
    all.push(n)
    all.push(p)
  return bytes.join(all)

action build
  let file = packed([bytes("one"), bytes.of([1, 2, 3])])
  let b = file.slice(0, 8)
  b[0] = 104
  b.fill(0, 4)
  said = `${file.length} bytes, version ${file.read(4, "u16")}, ${file.read(6, "u16be")} parts, ${b.hex()}`

button "Build" press=build
text said
```

- **The kinds** `read` and `write` know: `i8` `u16` `i16` `u32` `i32` `f32`
  `f64`, little-endian; `u16be`, `u32be` and the like for big-endian. A
  single unsigned byte is `b[i]`. Another word is refused (`H064`).
- **Who may write.** Writing into bytes is a write like any other: into
  state, only in an action. A `fn` writes only into bytes it made itself
  (`bytes.new`, `b.slice()`), never into a parameter (`H030`): take a copy
  with `.slice()`, write into that and return it.
- **A slice is a copy.** Writing into it leaves what it was cut from alone.
- Bytes made in a worker fn come back moved, not copied; bytes the page
  made itself may be written into and still be moved to a worker
  ([reactivity.md](reactivity.md#what-is-copied-and-what-is-moved)).
- A page cannot show bytes: pick a form (`.hex()`, `.text()`, `.url()`).
- The address `b.url()` gives is given up when the bytes are
  (`runtime/page/batteries.mote`, part `BU`).
- All of it works in a worker fn and in a `server fn` too.

Bytes are a `Uint8Array` underneath (`runtime/shared/bytes.mote`: parts
`BY`, `BYJ`, `BYN`). Compressing them is `zip` ([data.md](data.md#zip)).

### The legacy multi-byte sets

`b.text(label)` reads the seven multi-byte encodings of the WHATWG Encoding
Standard (Shift_JIS, EUC-JP, ISO-2022-JP, GBK, gb18030, Big5, EUC-KR, by
any of their labels: `sjis`, `ms932`, `gb2312`, `big5-hkscs`, `ks_c_5601-1987`,
…) with the **charsets battery** (`batteries/charsets`): the standard's own
decoders, step for step, over tables made from its index files at a pinned
commit, with its error handling (a malformed sequence is U+FFFD where the
standard says one, and a byte the standard reads again is read again). It is
the same wasm in a page, in a worker and in a `server fn`, so a text reads
the same everywhere, byte for byte, whatever the host's own decoder does:

```mote
// docs: whole
state said = ""

fn greeting(b: bytes, label: string): string = b.text(label) else "?"

server fn greetingThere(b: bytes, label: string): string requires anyone
  return greeting(b, label)

action read
  let sjis = bytes.of([130, 177, 130, 241, 130, 201, 130, 191, 130, 205])
  let big5 = bytes.of([167, 65, 166, 110, 129, 128])
  said = `${greeting(sjis, "shift_jis")} ${greeting(big5, "big5")} / ${greetingThere(big5, "big5")?}`

button "Read" press=read
text said
```

- **Why not the browser's own.** A browser's `TextDecoder` reads every
  valid sequence of these as the standard does, but Chrome (149) parts from
  it on some malformed ones: in Big5 a lead byte followed by a byte from
  0x80 that names nothing is two U+FFFD in Chrome and one in the standard;
  in ISO-2022-JP an escape that is not one, followed by 0x0E, 0x0F or a byte
  from 0x80, loses an error. A message read on the page would then differ
  from the same message read on the back end. (Bun 1.4 reads these sets
  too, and as the standard does; the battery makes the answer not depend on
  which Bun.) `tests/all.sh real_charsets` holds the battery to every
  pointer of every index and to the browser, record by record, and says
  where the browser parts.
- **Fetched only where it can be used.** The compiler gives the battery to
  a program only where a `b.text` can be given one of these labels: a label
  that is not written out (it is known when it runs), or one written out
  that names one of the seven. `b.text("latin1")` and `b.text("utf-8")` bring
  nothing. Where it is given: on the back end it is inside `server/main.js`
  (about 90 KB deflated), made when such a text is first read; on a page of
  `mote build` it is a file of the build (`assets/charsets.<hash>.wasm`,
  178 KB, 88 KB gzipped), brought before the code that can read one runs, as
  `re`'s engine is ([internals.md](internals.md#batteries)): the page waits
  for it at its start where its own lines can read one (its head asks for the
  file as the page arrives), else a component that can is drawn once it is
  here; an `off fn` that can read one asks for it before it runs, in its
  worker. In a page that is one file (`--single`) it is inside the page.
- If the file cannot be fetched, the read fails with kind `offline`.


## Files and `use`

```mote
use "./parts.mote"
```

`use` brings in that file's declarations: its states, fns, actions, shapes,
components, resources. Of what the file would show, only its tasks and
timers are kept: a named task in a used file starts with the page. Paths are
relative to the file that says `use`. A file reached twice (by two spellings
or from two files) is read once.

All files share one set of names. There are no modules and no exports.

Two folders beside the entry file ship with the page:

- `public/`: every file ships as it is, under its own name
  (`net.get("posts.json")`).
- `assets/`: only the files a page names ship, checked at build time
  ([markup.md](markup.md#pictures-and-assets)).

## Packages

Another project's files:

```mote
use "pkg:shop/engine/resolve.mote"
```

with a `mote.toml` beside the entry (or in a folder above it) that says
where the package is:

```toml
[packages]
shop = "../libs/shop"
```

Local folders only; nothing is fetched. A `use "pkg:name/…"` is looked up
in the `[packages]` of the program's own `mote.toml` (the nearest at or
above its entry) first, wherever the line is written: so a package's file
may take another package for the program (`use "pkg:usage/usage.mote"` in
the admin extension's `usage.mote`), the program saying where both are. A
name the program's `mote.toml` does not have is looked up as before, from
the nearest `mote.toml` at or above the file that says `use`. A missing
file or package is `H091`.

### What a package wants of its taker

A package says, at the top of a file, the fns it calls and the program is
to write:

```mote
// docs: whole
// (In a package: what it wants of the program that takes it.)
wants fn shopMay(): bool
wants fn shopGreeting(name: string): string = `Welcome, ${name}`

// (In the program: its own `shopMay`; `shopGreeting` is left to the package's default.)
fn shopMay(): bool = true

state said = ""

action hello
  said = shopMay() ? shopGreeting("Ada") : ""

button "Hello" press=hello
text said
```

- **`wants fn name(params): type`**, required: the program declares a fn
  of that name, or the build says, at the program's entry, what to write:
  `the program must declare fn usageMay(): bool for pkg:usage` (`H166`,
  with the fix and where the package wants it).
- **`wants fn name(params): type = expr`** (or a block under it): optional.
  What follows `=` is the fn where the program declares none; the program's
  own declaration takes its place where it does.
- **The program's declaration is checked against what is wanted**: the same
  parameters, the same types, the same type given back (`H166`, with the
  line to write). It may be in any file of the program, or in another
  package (the admin extension's `usage.mote` declares the usage
  extension's `usageMay`). Two packages that want a fn of one name want it
  alike. A name is still declared once: a second `fn usageMay` is `H022`.
- **Whether it can fail is the taker's to say**: in a package's file `else`
  and `?` after a call of a wanted fn are right either way (no `H080`), the
  program's fn or the default being whichever it is. A package may also
  call a fn it does not declare at all, as before; `wants` is what says so
  where the build can check it.

## Refused, with the fix in the message

Every diagnostic has a stable id (`H0xx`), a position, one line of what is
wrong, and where possible the text to write instead. `mote check --json`
gives them as data ([cli.md](cli.md#mote-check)).

| You write | Write instead |
|---|---|
| `null`, `undefined` | `none` |
| `xs.sort()` in a binding or derive | `toSorted()`, or sort in an action |
| `xs.contains(x)` `s.len()` `xs.append(x)` | `includes` · `.length` · `push` |
| `any` `boolean` `String` | `json` · `bool` · `string` |
| `fn f(a)` | `fn f(a: string)`: a parameter needs a type |
| `state xs = []`, `state x = none` | `state xs: string[] = []`, `state x: string? = none` |
| a write in a `fn` | make it an `action` |
| `net.get(url)` with nothing after it | `else fallback`, or `?` |
| `{a: 1}` as an attribute's value | `({a: 1})`: a bare `{…}` there is a handler |
| a tab in indentation | spaces |
| `x.constructor`, `x.prototype`, `x.__proto__`, `Object.getPrototypeOf`, `Object.defineProperty`; `eval`, `Function`, `globalThis`, `self`, `import(…)` (`H246`) | what it is for, in Mote's own words: a copy of a record is `{...x}`, its keys `Object.keys(x)`; for what the browser has and Mote does not, as a last resort, [`extern js`](js.md) |
| `window`, `document`, `navigator`, `this` | these are not names in Mote (`H020`) |

A program cannot reach the host's means of running text as code: the
names above are refused, and a key worked out while it runs (`o[k]`, with
`k` the word `"constructor"`) finds there only a stand-in that refuses
(`TypeError: Mote does not run text as code`), on the page, in its workers
and in the back end alike.

Markup's refusals (`className`, `onClick`, `text Hello`, …) are in
[markup.md](markup.md#refused).

## Pitfalls

- **A one-line `if` holds one statement each side.** `if c a = 1 else
  a = 2` is fine; for more than one statement, use a block.
- **A lambda is one expression.** For several statements, write a `for`
  loop or a fn.
- **`let` with `none` has no type.** `let x = none` is `json`; write
  `let x: T? = none` if it matters.
- **Narrowing needs a name.** `if a.b != none` does not narrow `a.b`;
  `let b = a.b` then `if b`.
- **`persist` uses the state's name as its key.** Renaming the state loses
  what was kept. Two apps on one origin share `localStorage`.
- **A fn that is to run in a worker cannot read state.** Pass what it needs
  ([reactivity.md](reactivity.md#workers)).
- **No `new`, no classes, no `try`.** Failure is `else` and `?`.
- **Numbers are plain decimals.** `0xff`, `1_000` and `.5` are not read;
  write `255`, `1000`, `0.5`.

## In the source

| What | Where |
|---|---|
| Tokens, strings, indentation | `compiler/src/lex.rs`, `lex` |
| Declarations, statements, expressions | `compiler/src/parse.rs`: `Parser::body`, `stmt`, `expr`, `ty` |
| The tree | `compiler/src/ast.rs` |
| Types, narrowing, the standard library's signatures | `compiler/src/types.rs`: `check`, `Checker::call`, `narrow`, `fit` |
| Logic to JavaScript, tracing writes | `compiler/src/emit.rs`: `Gen::expr`, `Gen::call`, `Gen::write`, `Gen::items` |
| Reading files, `use`, packages | `compiler/src/build.rs`: `load`, `package` |
| Diagnostics | `compiler/src/diag.rs` |
| Recorded behaviour | `compiler/src/tests.rs`; `tests/pages/*/app.mote` |
