# Types

| Rook              | Values                                       | In JS               |
| ----------------- | -------------------------------------------- | ------------------- |
| `number`          | numbers                                      | `number`            |
| `bigint`          | whole numbers of any size, `10n`             | `bigint`            |
| `byte`            | a number from 0 to 255                       | `number`            |
| `string`          | strings                                      | `string`            |
| `bool`            | `true`, `false`                              | `boolean`           |
| `any`             | anything, unchecked                          | —                   |
| `void`            | no value: `Promise<void>`                    | `undefined`         |
| `never`           | no value at all: a function that never ends  | —                   |
| `error`           | an error or `null`                           | `Error` or `null`   |
| `T[]`             | an array                                     | `Array`             |
| `byte[]`          | bytes                                        | `Uint8Array`        |
| `float64[]`, ...  | numbers of a fixed size                      | `Float64Array`, ... |
| `queue T`         | values in order, taken out at both ends      | `$$deque`           |
| `?T`              | a value of type `T` or `null`                | a value or `null`   |
| `func(A, B) R`    | a function                                   | a function          |
| `(a A) => R`      | the same function type, written as an arrow  | a function          |
| `comp(a A)`       | a component, which a tag takes from a value  | a function          |
| `A \| B`          | a value of type `A` or of type `B`           | a value             |
| `"all"`, `42`     | exactly that value                           | a value             |
| `{ x number }`    | an object with these fields                  | an object           |
| `{ [string]: T }` | an object used as a map: any key, values `T` | an object           |
| a class name      | an instance of the class                     | an instance         |
| an interface      | any value with the needed fields and methods | —                   |

The type goes after the name, without a colon: `x number`, `xs string[]`, `cb func(number) bool`,
`user ?User`.

Typing is **structural**, as in TypeScript: a value fits a type if it has all the needed fields and
methods of the needed types.

- **An array** is written after the type of its elements, as in TypeScript: `string[]`,
  `number[][]`, `Map<string, User>[]`. `[]` belongs to the type just before it, so a type written
  with a word or a sign before it takes `[]` inside: `?string[]` is an array or `null`,
  `func() number[]` gives an array, `queue string[]` holds arrays. An array of such a type puts it in
  parentheses: `(?string)[]` is an array of nullable strings, `(func() number)[]` an array of
  functions, `(string | number)[]` an array of both.
- **A function type as an arrow,** `(paths string[]) => Shape`, is the same as
  `func(string[]) Shape`; the names of the parameters only document them, and `=> void` means no
  result. Parentheses with one type and no arrow still group: `(string | number)[]`.
- **The parameters of a function type** may have names, which only document them; as in Go, if one
  has a name, all have, so `func(a, b number) number` takes two numbers. The rest of the arguments
  is last, `func(string, ...any[])`.
- **`void`** is the value of a Promise without one, `Promise<void>`, and of a callback whose result
  is not used. As the result of a function it is no result: `close() void` is `close()`. A function
  whose result in a `.d.ts` is `any` or `void | T` may end without `return`, and a parameter that
  takes `void` may be left out at the end, as the `resolve()` of a `Promise<void>`.
- **`never`** is the result of a function that never ends: it throws or exits, as `process.exit`.
  Its body must not reach its end, and the code after a call of it is not reached, so the call
  narrows types as `throw` does (section 12).
- **An object used as a map,** `{ [string]: number }`, has any keys with values of that type; the
  key is `string` or `number`. An object literal or another object fits it if all its fields do.
  `scores["ann"]` and `scores[name]` are a `number`, and `delete scores[name]` removes a key.
- **There is no `map[K]V` of Go:** an object with string keys is the map that JS code and JSON
  use, written as a literal, and a `Map<K, V>` of JS, typed from its lib, takes keys of any type.
  A third map with its own syntax would only have to be converted to them.

### bigint

```go
let big = 2n ** 64n           // 18446744073709551616n
let zero bigint               // 0n
const third = big / 3n        // the fraction is dropped
const n = Number(big) + 0.5   // a number again
```

`bigint` holds whole numbers of any size, as in JS. A literal ends with `n`: `10n`, `0xffn`,
`1_000n`; it has no fraction or exponent. The zero value is `0n`.

- **It does not mix with numbers** in arithmetic: `big + 1` is an error, since JS throws a
  TypeError there. One of them is converted: `big + 1n`, `BigInt(n)`, `Number(b)`.
- **Comparisons:** `<`, `>`, `<=` and `>=` work between a bigint and a number, as in JS. `==`
  between them is an error: it compiles to `===`, which is always `false` for the two.
- `-b`, `~b`, `b++` and the bit operators work; `+b` and `>>>` are errors, as JS throws there.
- `typeof b` is `"bigint"` and narrows a `number | bigint`. A bigint goes into markup as text and
  to a goroutine as a copy; `JSON.stringify` cannot write one (JS throws).

### byte[]

```go
let header byte[] = [0x89, 0x50, 0x4e, 0x47]
let empty byte[]
const bytes = byte[]("rook")
const text = string(bytes)
```

```js
let header = new Uint8Array([0x89, 0x50, 0x4e, 0x47])
let empty = new Uint8Array()
const bytes = new TextEncoder().encode('rook')
const text = new TextDecoder().decode(bytes)
```

`byte[]` is a `Uint8Array`, as a byte slice in Go, and `byte` is a `number` from 0 to 255 (the
range is not checked, as for other numbers). `data[i]` reads and writes a `byte`, and the methods
are those of `Uint8Array`: `subarray`, `slice`, `set`, and no `push`, since its length is fixed.

- **A list of numbers** where a `byte[]` is expected becomes one; the zero value is an empty
  `Uint8Array`.
- **Text and bytes** convert as in Go, in UTF-8: `byte[]("text")` and `string(bytes)`. They are
  the only conversions written with a type: `string(65)` is an error (in Go it would be `"A"`), and
  other values use `String(x)` or a template string. A program that declares a type `byte` or a
  value `string` uses its own.
- A `byte[]` goes to a goroutine as a copy, or without one with `transfer(data)`.

### Typed arrays

```go
const samples = make(float32[], 4)
let weights float64[] = [0.25, 0.5, 0.25]
let ids uint32[]
const counts = make(int64[], 8)
const field = make(float64[], 1_000_000, shared)
```

```js
const samples = new Float32Array(4)
let weights = new Float64Array([0.25, 0.5, 0.25])
let ids = new Uint32Array()
const counts = new BigInt64Array(8)
const field = new Float64Array($$shared(8 * 1_000_000))
```

The typed arrays of JS are written as arrays of the number types of Go, as `byte[]` is: their lengths are fixed, and
their elements are numbers of a fixed size, stored in a buffer without boxes.

| Rook        | JS               | Elements                     |
| ----------- | ---------------- | ---------------------------- |
| `int8[]`    | `Int8Array`      | `number`, from -128 to 127   |
| `uint8[]`   | `Uint8Array`     | `number`, the same as `byte` |
| `int16[]`   | `Int16Array`     | `number`                     |
| `uint16[]`  | `Uint16Array`    | `number`                     |
| `int32[]`   | `Int32Array`     | `number`                     |
| `uint32[]`  | `Uint32Array`    | `number`                     |
| `float32[]` | `Float32Array`   | `number`                     |
| `float64[]` | `Float64Array`   | `number`                     |
| `int64[]`   | `BigInt64Array`  | `bigint`                     |
| `uint64[]`  | `BigUint64Array` | `bigint`                     |

- **The element types** are other names of `number`, and of `bigint` for `int64` and `uint64`, as
  `byte` is: `const x float64 = data[0]`. The ranges are not checked, as for other numbers; a
  value is converted to the element when it is stored, as in JS. `uint8[]` is `byte[]`.
- **The JS names are the same types:** a `Float64Array` of a library goes where a `float64[]` is
  expected. `Uint8ClampedArray`, whose values stop at 0 and 255 (the pixels of a canvas), has no
  name in Go and keeps its own.
- **`make(float64[], n)`** makes a typed array of `n` zeros, as `make` does in Go. A length is
  only for typed arrays: a list, `number[]`, starts empty and grows. `make(float64[])` is an empty
  one, as `make` of any type is its value ("make" below).
- **`make(float64[], n, shared)`** puts it on a `SharedArrayBuffer`, which the workers of
  `go for` write into without copies. A page has one only with cross-origin isolation (the
  headers `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy:
require-corp`); elsewhere `make` throws an error that says so. Node always has it.
- **A list** where a typed array is expected becomes one, as for `byte[]`; the zero value is an
  empty one. The methods are those of the typed arrays: `subarray`, `slice`, `set`, `fill`, and no
  `push`.
- A program that declares a type `float64` or another of these names uses its own: `float64[]`
  is then an array of it.

### Queues

> **Experimental:** may change between releases; see the status at the top.

```go
const jobs = queue<string>(["build", "test"])
jobs.push("deploy")              // at the end
jobs.unshift("lint")             // at the start
const next = jobs.shift()        // ?string, "lint"
const last = jobs.pop()          // ?string, "deploy"
console.log(jobs.length, jobs.at(0), jobs.at(-1))
for job in jobs {
    console.log(job)
}
let waiting queue number         // an empty queue
```

```js
const jobs = new $$deque(['build', 'test'])
jobs.push('deploy')
jobs.unshift('lint')
const next = jobs.shift()
const last = jobs.pop()
// ...
let waiting = new $$deque()
```

`queue T` keeps values of type `T` in order, and they go in and out at both ends. It has the
methods of an array that a queue needs, but `shift()` and `unshift()` do not move the other values,
as they do in an array, so taking the first of 100 000 values costs as much as taking the first of
ten. `queue<T>()` makes an empty queue, and `queue<T>(items)` one with the values of an array or of
another iterable, which it copies.

- **The methods:** `push(...items)` and `unshift(...items)` add values at the end and at the start
  and give the new length; `shift()` and `pop()` take one out at the start and at the end;
  `at(i)` gives the value at a position, from the end if it is negative, `at(-1)` is the last;
  `length` is the number of values and `clear()` removes them all. `shift()`, `pop()` and `at(i)`
  give a `?T`: `null` for an empty queue or a position outside it, where an array gives
  `undefined`. There is no `q[i]`, nor `map` or `filter`: `[...q]` makes an array of the values.
- **`for v in q`** goes over the values from the start, without taking them out. A queue has no
  keys, so `for i, v in q` is an error.
- **Only a queue is a queue:** a `T[]` is not a `queue T`, nor the other way round. A
  `queue number` goes where a `queue ?number` is expected, as an array does, and a queue goes
  where an interface with its members is expected, `{ length number }`.
- **`queue` is a name elsewhere:** it is a type only before the type of its values, `queue number`,
  and makes a queue only before `<T>(`. So a variable may be called `queue`, and `queue < n`
  compares it. `queue<number>` as a type is an error that says to write `queue number`.
- **The zero value** is an empty queue, a new one for each variable and field, as `[]` is for an
  array; a closed `chan queue T` gives an empty queue too.
- **In JS** a queue is an instance of the class `$$deque`, which the module gets when its code
  uses queues: the values are a ring in an array, copied into one twice as large when it is full
  and into one half as large when it is mostly empty. Its fields are data, so a queue goes to
  another thread as a copy, if its values can be copied, and is a queue there too. TypeScript code
  sees its members in the `.d.ts`. The values of a channel and the goroutines that wait for it are
  kept in such queues as well.

### Type declarations

```go
type ID string
type Handler func(string) bool
type Pair { first, second number }
```

`type` gives a type another name: `ID` and `string` are interchangeable (in Go they would be
different types). The shape of objects is usually described with interfaces (section 9).

### Union and literal types

```go
type Filter "all" | "active" | "done"

func show(value string | number) string {
    if typeof value == "string" {
        return value.toUpperCase()
    }
    return value.toFixed(2)         // here value is already a number
}
```

- **`A | B`** is a value of one of the types. Parentheses group: `(string | number)[]`,
  `?(A | B)`. `?` applies to the nearest type, and `func() A | B` is a function that returns a
  union.
- **A literal type** `"all"`, `42` or `true` allows only that value. A union of literals catches
  typos: `filter = "activ"` and `filter == "activ"` are errors.
- **A member of a union** can be used if every type has it: `string | number` has `toString()` but
  not `length`. To get to the rest, the type is narrowed (section 12).
- A literal in code gets a literal type only where one is expected: `let f = "all"` is a `string`,
  and `let f Filter = "all"` is `"all"`.
- Branches of `?:`, array items and the different `return`s of a function without a declared
  result give a union when their types differ: `[1, "a"]` is `(number | string)[]`.
- Unions and literal types have no zero value: `let f Filter` must be initialized.
- **A field by a key whose value is known:** `point["x"]`, or `point[axis]` with
  `axis "x" | "y"`, is the field (or the union of the fields) of the object. A key that is not a
  field is an error.

### Tagged unions

> **Experimental:** may change between releases; see the status at the top.

```go
interface Pickup  { kind "pickup";  shop string }
interface Courier { kind "courier"; address string; floor ?number }
type Delivery Pickup | Courier

interface Order { id number; delivery Delivery }

func where(order Order) string {
    if order.delivery.kind == "courier" {
        return order.delivery.address     // here order.delivery is a Courier
    }
    return order.delivery.shop            // and here a Pickup
}

where({ id: 1, delivery: { kind: "pickup", shop: "Main st." } })
```

- **A tag** is a field that every member of a union has, with a literal type: a string, a number
  or a union of literals (`state "new" | "edited"`). A union may have several tags. Interfaces and
  classes with such a field work the same way.
- **Comparing a tag narrows the value it belongs to:** in `if d.kind == "courier"` the value `d`
  is a `Courier`, and in `else` the other members. `!=`, `!`, `&&`, `||`, a branch that returns,
  `switch d.kind` with its `case` and `default`, and `{if}` and `{switch}` of markup narrow as in
  section 12.
- **An object literal** where a union is expected is checked as the member that its tag chooses:
  `{ kind: "pickup", shop: "..." }` is a `Pickup`, with the usual check of its fields. A tag of no
  member is an error: `"plane" is not a kind of Delivery: write "pickup" or "courier"`.
- `decode<Delivery>(text)` checks such a union when the program runs (section 7), and its result
  narrows too.
- There is no check that a `switch` covers every kind: a `switch` without `default` that leaves a
  kind out is neither an error nor a warning.
- Nothing changes in JS: a tag is an ordinary field, and its comparison an ordinary `===`.

### Generics

Type parameters go in angle brackets after the name, as in TypeScript, and a constraint follows
its parameter, as in Go:

```go
func first<T any>(xs T[]) ?T {
    return xs.length > 0 ? xs[0] : null
}

interface Box<T> {
    value T
}

type Pair<A, B any> { first A; second B }

class Stack<T> {
    private items T[]
    push(item T) { this.items.push(item) }
    pop() ?T { return this.items.pop() ?? null }
}

const n = first([1, 2, 3])              // ?number
let b Box<string> = { value: "a" }
let s Stack<number> = new Stack()
```

- **A constraint** goes after the name: `<T Named>` means `T` must fit `Named`, and values of type
  `T` have the members of `Named`. `any` means no constraint, and then `T` has no members. Several
  names in a row share one constraint: `<K, V any>`. Interfaces, classes and `type` may leave the
  constraint out: `interface Box<T>`.
- **Type arguments** of a type are written after it: `Box<number>`, `Pair<string, ?number>`. In
  calls they are inferred from the arguments, and failing that, from the expected type:
  `let xs number[] = empty()`. A call may also give them, `empty<number>()`, `first<string>(xs)`:
  types in `<>` right before `(` are type arguments, and anything else is a comparison, so
  `a < b && c > (d)` stays two of them. `new` takes none: `new Stack<number>()` is an error, and
  the variable gets the type, `let s Stack<number> = new Stack()`. If there is nothing to infer
  from, it is an error: `let s = new Stack()`.
- Inside a function, `T` is a type of its own: `return 1` in a function with the result `T` is an
  error. `T` has no zero value, but `make(T)` gives the value of the type of each call ("make"
  below).
- A type can refer to itself: `interface Tree<T> { value T; children Tree<T>[] }`.
- `Box<number>` and `Box<string>` are different types, and so are `Stack<number>` and
  `Stack<string>`.
- A generic class cannot be extended yet: the base after `extends` is a value, as in JS, so
  `extends Stack<number>` cannot be written. Methods with type parameters of their own
  (`map<U any>(...)`) are not supported yet either.
- In JS, generics are erased, as in TypeScript.

### make

`make(T)` is the value of a type, which the compiler computes, so that no type is left in the JS:

```go
interface File {
    name string
    size number
    type ?string
}

type MyNumber number

const a = make(File)                    // { name: "", size: 0 }
const b = make(File[])                  // []
const c = make(number)                  // 0
const d = make(MyNumber)                // 0
```

```js
const a = { name: '', size: 0 }
const b = []
const c = 0
const d = 0
```

- **The value** of a type with a zero value is that zero value: `0`, `0n`, `""`, `false`, `[]`, an
  empty typed array or queue, a closed channel, `null` of `?T` and `any`. An interface or an object
  type is an object of its fields, each with its own value; a field that may be missing, `?T` or
  `any`, is left out. A literal type is its literal: `make(Circle)` with `kind "circle"` gives
  `{ kind: "circle", r: 0 }`. `Map` and `Set` are empty, `new Map()`. A class of Rook whose
  constructor takes nothing is `new Cart()`.
- **No value:** a union, a function, an interface with methods, a type that has itself as a field
  (`next Node`; `next ?Node` is fine), a class whose constructor takes arguments and a class of a
  library (`new Date()` would be the time) are errors that say why.
- Each `make` is a new value: two `make(File)` are two objects.
- `make` is a word here, as in Go: a program that declares a value `make` gets an error at
  `make(...)` that asks to rename it. `make(x, 1)`, which is no type, is a call.

**In a generic function**, `make(T)` is the value of the type that each call gives T, and so is the
type that `decode<T>(x)` checks against (section 7). The compiler finds the types of the calls in
the module:

```go
func create<T>() T {
    return make(T)
}

const num = create<number>()
const str = create<string>()
```

```js
function create($$Tmake) {
  return $$Tmake()
}

const num = create(() => 0)
const str = create(() => '')
```

- **Called with one type**, the function gets the value in its body: `create<number>()` alone
  makes `function create() { return 0; }`, and the call passes nothing.
- **Called with several, or exported,** it takes what its type parameters give before its own
  parameters: for `make(T)` a function that makes the value, `$$Tmake`, and for `decode<T>` the type,
  `$$Ttype`. A function, not a value, so that each `make(T)` is a new object, as it is without
  generics. Other modules see these parameters too, and so does the `.d.ts`:
  `create<T>($$Tmake: () => T): T`.
- **Never called**, it is left out of the JS with a warning: nothing says what T is.
- A function that passes T on needs it too: `func pair<T>() T[] { return [create<T>(), create<T>()] }`
  passes its `$$Tmake` to `create`, or its one type.
- A function whose body has no `make(T)` or `decode<T>` is as before: its types are erased, and
  nothing is passed.
- Such a function cannot be a value, `const f = create`, since a value has no T: it is called,
  `() => create<number>()`. T must come from the call, `create<number>()`, or from the arguments
  and the expected type.
- Only the type parameters of `func` give values: `make(T)` with T of a class or a method is an
  error.
- With `rook build --no-check`, without the types, `make` writes only what the type as written
  shows (`0`, `""`, `[]`); others are `undefined`.

### null and null safety

The language has one "empty" value, `null`; Rook has no `undefined`. An ordinary `==`
compiles to `===`, but a comparison with `null` stays loose: `x == null` → `x == null`. So it also
catches `undefined` coming from JS code.

`null` can be assigned only to `?T`, `error` and `any`. To use a field or a method of a value of
type `?T`, the type must first be narrowed:

```go
func findUser(id number) ?User { ... }

const u = findUser(1)
console.log(u.name)                  // error: u may be null
console.log(u?.name)                 // fine: the type is ?string
console.log(u?.name ?? "anonymous")  // fine: the type is string

if u != null {
    console.log(u.name)              // here u is a User
}

if u == null {
    return
}
console.log(u.name)                  // and here: on null the function has returned
```

- Narrowing works for local variables, parameters and paths of fields from them: in
  `if user.boss != null` the value `user.boss.name` can be read (section 12). A field of `this`
  (`this.user`) is first put into a `const`.
- `error` always allows `null`; there is no need to write `?error`. A function that gets an error
  already checked takes `Error`, which does not: `func describe(err Error) string`.
- `x!` takes a value not to be `null`, as in TypeScript: `env.PORT!` is a `string`. Nothing is
  checked at runtime, so a wrong `!` fails where the value is used; a check or `??` is safer. The
  `!` is right after the value, so `!x` before one stays a negation.
- `xs[i]` has the type `T`, not `?T`: the compiler does not catch indexes out of bounds (nor does
  TypeScript by default).
- Values of type `any`, including everything imported from JS modules without types, are not
  checked.

