# Type system

Two principles explain most of the rules on this page. First, the checker prefers skipping a check
to giving a wrong answer: a construct it cannot describe becomes `Unknown`, which is compatible with
everything, so a gap means a skipped check rather than a false error, and [strict mode](#strict-mode)
shows where the gaps are. Second, every rule must be cheap enough to check on every keystroke, which
is why inference is Hindley–Milner, why your own functions cannot be overloaded, and why there is no
subtyping between nominal types. The [guide](/guide.md#step-2-type-your-code) introduces the same ideas
through examples.

`ry check` reports the type errors on this page only when typing is on, through `[check] typing = true`
in `ry.toml` or a `# typing: on` comment at the top of the file (see
[configuration](/reference/configuration.md)). Every output block here was produced that way. With
typing off, the checker still reports unresolved names, such as a misspelled column in a data.table
query's `i`, but no type errors.

## Typing comment syntax

Annotations are written in two ways that share one type grammar: in `#:` comments, described here,
and [inline](#inline-annotation-syntax), in the code itself. An example that has both spellings shows
them in tabs, and the tab you choose is remembered on every page of this site. A form that exists in
only one spelling shows a single block and says so. A `#:` comment sits directly above the
binding or expression it describes. Consecutive `#:` lines with no blank line between them form one
*annotation block*. Each annotation takes one of these forms:

- `#: TYPE` is a [checked annotation](#checked-annotations).
- `#: @trust TYPE` is a [trusted coercion](#trusted-coercions).
- `#: @if-unknown TYPE` is an [unknown-only coercion](#unknown-only-coercions).
- `#: @new NOMINAL_TYPE` is a [nominal introduction](#nominal-introduction).

After an annotation, a `#` starts a plain comment, so `#: double # amount in euros` is the type
`double` with a note. A second `#:` on the same line is an error, because it would otherwise be
read as that note and its type dropped: write each annotation on its own line.

A block is one of three kinds, which cannot be mixed: a single line in one of those forms, an
[expanded function annotation](#expanded-function-annotations) written as `@param` and `@return`
lines, or a definition block of `@type` and `@alias` lines.

### Inline

```r
value: integer <- 1L

double_count <- function(count: integer) -> integer count + count
```

### Comments

```r
#: integer
value <- 1L

#: fn(count: integer) -> integer
double_count <- function(count) count + count
```

A block can attach at any statement depth. Inside a function body it annotates the assignment or the
block-final expression that follows it, which is how a function that builds a value of a named type
is written:

### Inline

```r
type Person = list{name: character}

make_person <- function(name: character) -> Person {
  @Person(list(name = name))
}
```

### Comments

```r
#: @type Person {list{name: character}}

#: fn(name: character) -> Person
make_person <- function(name) {
  #: @new Person
  list(name = name)
}
```

### Attachment

A block attaches to the expression that starts on the line directly after it. A braceless function
body, a braceless `if` branch, and a parenthesised expression are valid targets. When a block needs a
target and has none, it is an error and the annotation does not apply. That happens when:

- a blank line separates the block from the expression;
- a plain `#` comment separates them, or no expression follows at all;
- the block has no content beyond the `#:` marker;
- the block sits inside a call's argument list, for example beside a lambda passed to `lapply`,
  because an argument is not a statement. Give the value its own binding and annotate that instead.

A definition block, one that contains only `@type` and `@alias` lines, attaches to nothing, and
neither does a `@strict` toggle, so the adjacency rules do not apply to them.

### Refused blocks

A block is refused as a whole when it mixes forms, orders its directives wrongly, declares a
duplicate or unknown type parameter, or gives `@new` a payload that is not nominal. A refused block
reports its error and carries no typing payload, so a broken annotation does not cause follow-on
findings. Two known exceptions still do: a `[]` vector whose element type is not atomic or is not
declared (`Rec[]`), and a bare optional positional parameter (`fn(integer, [character])`). A block
the annotation grammar could not read at all is refused silently, because the parse error has
already said what was wrong.

## Inline annotation syntax

An inline annotation writes a type into the code instead of a comment above it:

### Inline

```r
count: integer <- 0L

add <- function(x: integer, y: integer = 1L) -> integer {
  x + y
}

first <- function<T>(items: list[T]) -> T items[[1L]]
```

### Comments

```r
#: integer
count <- 0L

#: fn(x: integer, [y]: integer) -> integer
add <- function(x, y = 1L) {
  x + y
}

#: <T> fn(items: list[T]) -> T
first <- function(items) items[[1L]]
```

- `name: TYPE <- value` declares a binding's type. The `=` spelling, `name: TYPE = value`, works too.
- `name: TYPE` in a parameter list declares a parameter's type, before its default if it has one.
  `...: TYPE` declares the rest parameter.
- `-> TYPE` between the parameter list and the body declares a function's return type.
- `<T, U: numeric>` directly after `function` or `\` declares the function's type parameters, with
  the same names and constraints as the compact `<...>` binder.
- `type Name<T> = TYPE` and `alias Name<T> = TYPE` at the top level of a file define a
  [named type](#named-types-and-generic-application), like `#: @type Name<T> {TYPE}` and
  `#: @alias Name<T> {TYPE}`.
- `name: @trust TYPE <- value`, `name: @if-unknown TYPE <- value` and `name: @new Name <- value`
  write a binding's [coercion](#unknown-only-coercions) inline.
- `@Name(value)` and `@Name<ARGS>(value)` introduce a nominal type on a value, like `#: @new Name`
  on that value. The `(` must follow the type directly, and `value` may be any expression, including
  a record or tuple: `@Point((x = 1, y = 2))`.
- `name <- @pure function(...)` and `name <- @pure \(x) ...` declare the function pure, like a
  `#: @pure` line above the binding (see [purity](#purity)). Followed by `(`, `@pure(...)` is a
  nominal introduction instead.

Every `TYPE` is the type grammar of `#:` comments, so anything a `#:` type can say an inline type can
say, and a type reads the same written either way.

### Meaning

An inline annotation means exactly what the equivalent `#:` block means, because both lower to the
same annotation:

- A binding's type is a [checked annotation](#checked-annotations): `count: integer <- 0L` is
  `#: integer` above `count <- 0L`.
- A function's inline types form a [compact annotation](#compact-function-annotations) naming the
  annotated parameters, so `function(x: integer, y)` is `#: fn(x: integer)` over `function(x, y)`.
  [The formal list](#annotations-and-the-formal-list) rules apply unchanged, and an unannotated
  parameter keeps its inferred type.
- A parameter with a default is optional, so the inline form never needs `[name]`.
- `type` and `alias` definitions are the `@type` and `@alias` definitions of the same name, in the
  same project-global namespace.
- A binding's directive, as in `x: @trust integer <- v`, is the same directive in a `#:` block above
  the binding. `@Name(value)` is `(value)` with `#: @new Name` on it.
- A function without `-> TYPE` infers its return type from its body, as an
  [elided return](#elided-return-types) on a definition does. A function type inside an inline
  annotation, such as `f: fn(integer)` or `callback: fn(integer)`, follows the `#:` rule for that
  position: `NULL` when nested, and inferred from the body when it is a binding's whole type over a
  function literal.

Because the signature sits on the function itself, a function that is not a statement can be
annotated too. `lapply(ids, function(id: integer) -> character format(id))` checks the lambda's
body against its signature and the call against its parameter, where a `#:` comment could not reach
it. When a binding's type and its function's own signature are both written, as in
`step: fn(x: integer) -> integer <- function(x: integer) -> integer x + 1L`, the signature types the
function and the binding's type is then checked against it like any other value.

### Where inline annotations parse

A parameter's type and a function's return type and type parameters can be written on any function
literal. A binding's type is recognized only where a statement starts, at the top level of a file or
directly inside `{ }`. Elsewhere, such as in a braceless `if` branch, `y: integer <- 1L` is R's
reading of `y:integer` as an assignment target, which is reported as a syntax error. A binding's type
continues onto the next line inside an open bracket, after a `|`, and onto a line that starts with
`|`.

`type` and `alias` start a definition only at the start of a statement and only when a name follows
them on the same line, so `type <- "x"`, `alias(y)` and every other use of them as ordinary names
keep their R meaning. A definition inside a function body or any other block parses, but is an
`annotation` error: definitions belong at the top level of a file. A definition ends at the end of
its line, and nothing but a comment may follow it there, so `type Id = integer; x <- 1` is a syntax
error. Its type continues onto the next line after `=`, after a `|`, inside an open bracket, and
onto a line that starts with `|`. No R statement starts with `|`, so a union may line
up its members:

```r
alias Shape =
  | :Circle(radius: double)
  | :Rect(width: double, height: double)
```

A leading `|` is allowed in any union, in a `#:` comment too.

A return type is read as far as the type grammar reaches, and the body starts after it. A list or
function type must hug its bracket, as the formatter writes it: `-> list{name: character}` is a
record type, while in `-> list {` and `-> fn (` the bracket starts the body.

A mistake in an inline type's grammar is a `syntax-error`, because the statement cannot be read
until it is fixed. A type that parses but means nothing, such as an unknown type name or a record
that mixes named and positional items, is an `annotation` error, as it is in a comment.

### Erasure to plain R

R's own parser rejects every inline annotation except a binding's, which R reads as an assignment to
`name:TYPE` through a `` `:<-` `` replacement function that base R does not define. So no working R
program contains one, and existing R code parses and behaves exactly as before.

`type` and `alias` definitions and `@Name(value)` are not R either: a definition is two names in a
row, and `@` cannot start an R expression. At the start of a line, `@Name` reads as a constructor
only when `(` or `<` follows the name, so a slot access broken across lines, `obj` then `@slot`,
keeps R's own syntax error.

Removing each inline annotation turns an annotated program into the plain R program it means:
delete a binding's or parameter's `: TYPE` (with its directive), a function's `<...>`, its
`-> TYPE`, and the `@Name` of `@Name(value)`. A type definition becomes its `#:` comment, line for
line, so the erased program still declares the type, and a definition paired with a `#:` block
directly above it is removed, because that block already declares it. Comments and `#:` blocks
stay. `count: integer <- 0L`
erases to `count <- 0L`, `function<T>(x: T) -> T x` to `function(x) x`, `@UserId(5L)` to `(5L)`,
and `type UserId = integer` to `#: @type UserId {integer}`.

### Inline and comment annotations together

A statement can carry both a `#:` block and inline annotations. They combine one *slot* at a time,
where a slot is the binding's value, one parameter, the rest parameter, or the return:

- A slot only one of them types takes that type.
- A slot both type takes the inline type.
- A coercion (`@trust`, `@if-unknown`, `@new`) says how the value gets its type, so it governs the
  value wherever it is written, and the other side's type is only compared against it. When both
  sides are coercions, the inline one governs.

A slot typed both ways with different types is reported as `annotation-mismatch`, a warning at the
inline type that points at the comment's type, so the reader always learns which one ry uses.
Types are compared as types: an alias agrees with its expansion, and `integer | character` agrees
with `character | integer`. Type parameters pair by position, so `<T>` in the comment and `<U>` in
the code agree, and a binder whose constraint differs is reported the same way, with the inline
constraint winning. A positional parameter type in a compact `#:` annotation is compared with
the formal it pairs with.

A type definition pairs the same way. A `#:` definition directly above an inline definition of the
same name, with nothing but a line break between them, is one definition written twice. It counts
once, so it is not a duplicate, and the inline definition is the one that applies. When the two
differ in kind (`@type` against `alias`), in the number of type parameters, in a constraint, or in
the type itself, ry reports `annotation-mismatch` at the inline definition, pointing at the comment.
Type parameters pair by position, so `#: @alias Pair<T> {Tuple{T, T}}` and
`alias Pair<U> = Tuple{U, U}` agree. A `#:` definition anywhere else in the project with the same
name is a duplicate, as two `#:` definitions are.

This example deliberately uses both spellings on one function:

```r
#: fn(price: double, rate: double) -> double
apply_discount <- function(price: integer, rate) price * (1 - rate)
```

```text
! the inline annotation gives parameter `price` the type `integer`, but the `#:` comment gives it
  `double`. ry uses the inline type; make the two agree, or delete one
```

### Turning inline annotations off

`[check] inline-annotations = false` in `ry.toml` turns inline annotations off, for code that must
also run under R. An annotation that is off types nothing, and each one is reported once as an
`inline-annotation` warning, because R cannot run that code. ry also warns once per run, and the
language server once per load, for as long as the setting stays off. A `#:` block on the same
statement then applies alone, and so does a paired `#:` definition. An inline type definition with
no `#:` partner still declares its name, so uses of it are not also reported as unknown types. A
`type` stays nominal, so a plain value is still not accepted where it is expected, but its
representation is `Unknown`. The setting also governs running code: `ry run` and `ry R` run
annotated code either way, and ry's runtime takes a function's signature from its `#:` block alone.

### Annotations at run time

`ry run` runs annotated code on ry's runtime and `ry R` on GNU R, which reads the erasure. ry's runtime
reads the annotations themselves and checks a function's parameter and return types at its
boundary, so a function called with the wrong kind of value fails where it was called instead of
somewhere inside it:

```r
scale <- function(values: double, by: double) -> double values * by
scale("a", 1)
```

```text
Error in scale("a", 1) :
  argument `values` must be `double`, not `character`
```

**A signature counts the same wherever it is written.** The runtime resolves a function's
signature by the rules the checker uses ([together](#inline-and-comment-annotations-together)): a
type written on the function wins, then the function type on the name it is assigned to, then the
`#:` block [attached](#attachment) to its statement. The two functions below are checked exactly
like `scale` above, and a signature written entirely in ry types
[compiles to native code](#native-functions) in any of the three forms.

```r
#: fn(values: double, by: double) -> double
scale <- function(values, by) values * by

halve: fn(value: double) -> double <- function(value) value / 2

halve("a")
```

```text
Error in halve("a") : argument `value` must be `double`, not `character`
```

GNU R reads a `#:` block as a comment, so a file annotated only in `#:` blocks runs under
`Rscript` without checks.

Three kinds of signature are not checked at run time:

- **A coercion.** `@trust`, `@if-unknown` and `@new` say how the value gets its type instead of
  declaring one to check, and a coercion governs the value wherever it is written. A function under
  one has no run-time checks, whatever types its literal writes, and it is not compiled.
- **The name of a type alias**, as in `#: Scaler` with
  `#: @alias Scaler {fn(values: double, by: double) -> double}`. The runtime reads the types where
  they are written, and resolving an alias takes the checker.
- **A block the checker rejects.** A `#:` line that does not parse is a comment, and a block whose
  directives are out of order declares nothing. A block with an error that only the checker can
  see, such as an unknown type name, declares nothing to the checker, and the runtime checks the
  types it recognizes in it.

The console attaches a `#:` block the same way. A command that ends in a `#:` block is unfinished,
so the console reads the next line into the same command, and a blank line ends the wait and leaves
the block attached to nothing.

A check never changes what code that satisfies its annotations does, which the oracle pins by
comparing annotated cases on ry's runtime against GNU R running their erasure. The checks follow
these rules:

- **Parameters are checked when their value is computed.** An argument from R code stays a promise
  and is checked when it is forced, so laziness, `missing()`, and `substitute()` behave as in R, and
  an argument that is never used is never checked. An argument that is already a value, such as a
  constant, is checked when the function is entered.
- **Every `...` argument is checked against the rest parameter's type**, under the same rule. An
  argument forwarded through `...` to another typed function is checked against both functions'
  types when it is forced.
- **The return value is checked when the function returns**, including through `return()`, and
  before `on.exit` code runs.
- **Bindings are not checked.** `x: integer <- value` types `x` for the checker and is erased at
  run time. A literal in the bound value still runs as the number type the checker gave it (see
  [number literals](#number-literals)).
- **Type definitions and `@Name(value)` do nothing at run time.** A definition is skipped, and
  `@Name(value)` runs as `(value)`.
- **A check tests the value's storage type only.** `logical`, `integer`, `double`, `complex`,
  `character`, `raw`, and `NULL` admit values of that type, and each numeric type also admits the
  types below it in the promotion order, as the checker does. A parameter whose type admits
  `integer` also admits a `double` scalar holding a whole number, because the checker accepts a
  whole-number literal there (`f(10)` for `n: integer`) and storage cannot tell a literal from a
  computed value; a return value gets no such allowance. A list type admits any R list, a
  `Record{...}` or `Tuple{...}` type any ry record or tuple, a function type any function, and a
  union any of its members. Vector shape, element types, and
  attributes are not checked, and a type the storage type cannot decide (a class, a type
  parameter, `Any`, `data.frame`) is not checked at all. Under `ry run`, the console and an
  installed package, an alias is checked as the type it stands for, because ry's runtime reads
  each one-line annotation there with its aliases expanded. A check therefore fails only on a value that really does not
  have the annotated type.
- **An installed typed package's signatures name the types, not their aliases.** `ry install` and
  `ry build` on ry's runtime write each one-line parameter and return annotation of a typed package
  as the type it stands for ([CLI reference](/reference/cli.md#build-and-install)), so an installed
  function with a parameter `p: Point`, where `alias Point = Record{x: F64, y: F64}`, checks `p` as
  a record. A type with no such spelling, such as the open record `Record{a: I64, ..}`, and an
  annotation that spans lines stay as written.
- **A function with no parameters whose body is a constant or a bare name is not checked**, because
  it has no language object to carry its signature.

Typed ry is strict, so a call from one typed function to another computes every argument the
caller wrote, left to right, before the callee runs, even an argument the callee never uses. This
is the one place where ry's runtime and GNU R running the erasure differ: GNU R computes such an
argument only when the callee uses it. An argument written in R code, including one that reaches a
typed function through `...`, stays lazy.

```r
first <- function(a: double, b: double) -> double a
typed_caller <- function(x: double) -> double first(x, { cat("computed b\n"); 2 })
r_caller <- function(x) first(x, { cat("computed b\n"); 2 })
typed_caller(1)
r_caller(1)
```

```text
computed b
[1] 1
[1] 1
```

A failed check is an ordinary R error, so `tryCatch()` and `try()` handle it. A parameter whose
check failed stays unevaluated, as it would after an error while computing it, so code that catches
the error and uses the parameter again computes it again and checks it again.

The checks belong to the function definition that carried the annotations. A closure built from
another function's `formals()` with a body of its own, as `rlang::new_function()` builds one, is a
new definition and is not checked.

Before running anything, `ry run` and `ry R` check the script and their console checks each command, with the
project's `ry.toml`. They print every `annotation-mismatch` and `inline-annotation` warning. In
[strict mode](/guide.md#strict-mode) they also print every error and refuse to run code that
has one: a script exits with status 1, and the console drops the command. A paste from a terminal
with bracketed paste is one command, so an error anywhere in it drops all of it. Other findings are left
to `ry check`, so they never change whether R code runs.

Each console command is checked against the commands that ran before it. It sees the names they
bound, the types they defined and the last `# typing:` directive among them, so a directive governs
the commands after it. A function body reads a global when the function is called, so it sees the
latest binding of the name. In strict mode, a command that rebinds a name in a way that breaks a
function an earlier command defined is refused, with the error shown in that function's command:

```r
> x: integer <- 1L
> f <- function() x + 1L
> x <- "a"
type-mismatch

  x `+` is not defined on `Str`. It takes a number
   --[<console>:1:17]
 1 | f <- function() x + 1L
   |                 ^^^^^^

  x strict mode found 1 error, so this code does not run
```

Line numbers in a console finding count from the start of its command. Ctrl-C while a paste runs
cancels the rest of the paste, and the cancelled lines are checked as if they were never typed.

## Types

### Atomic names

Types use R's own names: `logical`, `integer`, `double`, `complex`, `character`, `raw`, and `NULL`.
The names from other languages, such as `bool`, `int`, `float`, and `string`, are not accepted.

### Reserved constants

- `TRUE` and `FALSE` are `logical`.
- `NA` is `logical`, while `NA_integer_`, `NA_real_`, `NA_complex_`, and `NA_character_` are
  `integer`, `double`, `complex`, and `character`.
- `Inf` and `NaN` are `double`.
- An imaginary literal such as `1i` is `complex`.
- `NULL` is `NULL`.

### Vector shapes

Every atomic vector type comes in three shapes, written with a suffix on the atomic name:

```r
1L                  # integer: scalar-like, a vector of length one
c(1L, 2L)           # integer[]: array-like, a vector of unknown length
c(a = 1L, b = 2L)   # integer[named]: map-like, keyed by names
```

#### Vector coercions

- A scalar-like `T` coerces to an array-like `T[]`.
- A map-like `T[named]` coerces to an array-like `T[]`.
- An atomic type coerces up R's promotion order, `logical` < `integer` < `double` < `complex`, in
  every shape. That covers `logical` to `integer`, `integer[]` to `double[]`, `double[named]` to
  `complex[named]`, and compositions such as a scalar `integer` to `double[]`. The reverse never
  holds. `character` and `raw` are not part of the order, because R reaches `character` only through
  an explicit conversion.
- No other coercion between vector types is allowed unless a rule elsewhere on this page states it
  explicitly.

### List shapes

R has one list type, but programs use it in four roles, and the type system gives each role its own
type, because each role allows different checks:

- **tuple-like**, `list{T1, T2, ...}`: no names, a fixed number of positions, each with its own type.
- **list-like**, `list[T]`: no names, any length, one element type.
- **record-like**, `list{name: T, ...}`: named fields, a fixed set of them, each with its own type.
- **dict-like**, `list[named: T]`: names, any length, one element type.

The tuple-like and record-like shapes have a *fixed shape*: their positions or field names are part
of the type. The list-like and dict-like shapes are homogeneous collections, so no particular
position or name is part of the type. They mostly come from annotations and from coercing a
fixed-shape list.

A `list(...)` expression infers a fixed shape whenever its elements allow one:

- When all elements are unnamed, it is tuple-like, even when they share a type: `list()` is
  `list{}`, `list(1L, 2L, 3L)` is `list{integer, integer, integer}`, and `list(1L, "foo")` is
  `list{integer, character}`.
- When all elements are named and the names are known statically, it is record-like:
  `list(foo = 1L, bar = "foo")` is `list{foo: integer, bar: character}`.
- When named and unnamed elements are mixed, the names are dropped and it is list-like, so
  `list(1L, bar = "foo")` is `list[integer | character]`.
- When an argument is the enclosing function's `...`, the number and names of the elements are not
  known, so `list(...)` is `list[named: Unknown]`. Any field may be present, so reading or writing
  `dots$environment` is not reported. A list whose elements are not known at all, such as
  `as.list(environment())`, likewise says nothing about its names: `$` on a `list[Any]` or
  `list[Unknown]` reads `Any` or `Unknown` without an error.

R lets a list name be any string. A field name that is not a syntactic R name is written, and
rendered, in backticks, so `list(\`max size\` = 10L)` has the type `` list{`max size`: integer} ``.

#### List coercions

- Any list coerces to a list-like `list[T]` when every element is compatible with `T`.
- A record-like or dict-like list coerces to a dict-like `list[named: T]` when every value is
  compatible with `T`. So does a `list[Any]` or `list[Unknown]`, whose names are not known, such
  as `as.list(x)` on an untyped `x`.
- When `T` is still open, it becomes the union of the element types, so `lapply(list(1L, "a"), f)`
  passes `integer | character`.
- Otherwise the reverse is not allowed: a `list[T]` does not coerce back into a tuple-like, record-like, or
  dict-like list, and a `list[named: T]` does not coerce back into a record-like one.

Two records are compatible when they declare the same field names and each field's type is
compatible with the field of the same name on the other side. Fields pair by name, so their order
does not matter: `list(label = "a", id = 1L)` satisfies `list{id: integer, label: character}`.

When a record is rejected, the finding names the one field that failed rather than printing both
whole types: a field both sides declare whose types do not fit, a field the expected type declares
that the value lacks, or a field the value has that the expected type does not declare. For a nested
record, the finding names the path, outermost field first, as in `retry.count`.

#### The empty list

`list()` is the empty tuple `list{}`. It has no element whose type or name could conflict, so it is
compatible with `list[T]` and `list[named: T]` alike, which makes `function(options = list())` a
usable default for a `list[named: T]` parameter. A record type with required fields still rejects
it, because those fields really are missing.

Code starts from `list()` and fills it later far more often than it reads from a list it knows is
empty, so any element read from `list{}` is `Unknown`: `out <- list(); out[[1]]` and
`opts <- list(); opts$force` are not reported. Inside a union, an empty-list member contributes
`NULL` to a field read instead, as [`$` on a union](#indexing) describes.

### `NULL`

The literal `NULL` has the type `NULL`, which is the unit type of this type system and is
incompatible with every other type. An empty block is also `NULL`.

A variable whose every visible write is `NULL` is a placeholder for a value written where the
checker cannot see, such as lifecycle's `msg <- NULL # trick R CMD check` before `msg %<~% ...`,
or a top-level flag that `assign()` fills in later. Passing such a variable as an argument, or
testing it as a condition, is not reported. A parameter whose type is `NULL` and the literal
`NULL` stay checked, so `report(NULL)` against a `character[]` parameter is an error.

A local whose every visible write is a bare `NA`, and that a closure fills with `<<-`, is the same
placeholder spelled as a missing value, as in knitr's `pattern.end <- NA` before a nested function
assigns the pattern. Its reads are not checked either.

### `Any` and `Unknown`

`Any` and `Unknown` are both compatible with every type, in both directions. They differ in where
they come from, and therefore in what they mean.

`Any` is an explicit opt-out from type checking. It comes from an annotation you wrote or from a
standard-library declaration. The shipped declarations use it where any precise type would reject
calls R accepts, so seeing `Any` in a hover is not by itself a sign of a problem.

`Unknown` means the checker could not work out a more specific type, because of an unsupported or
partly supported construct, an unresolved name, or too little information. It is not an opt-out: it
records a gap in the checker's knowledge, and a value of that type flows into a `double` parameter
without complaint.

The difference in intent shows in two places. [`@if-unknown`](#unknown-only-coercions) supplies a
type where one is missing, so it applies to an `Unknown` and is refused on an `Any`, which already
says not to check the value. [Strict mode](#strict-mode) reports where an `Unknown` arose, and treats
an `Any` as an intentional opt-out.

### Type parameters, aliases, and nominal types

A type expression can bind type parameters with a leading binder, written `<T> TYPE` or
`<T, U> TYPE`:

- `<T> list[T]`
- `<T> list{ value: T }`
- `<T, U> fn(T) -> U`
- `<T> fn(T) -> T | NULL`

A type parameter may appear inside a structural type, a function type, and the vector suffix forms:
`list[T]`, `list{ value: T }`, `fn(T) -> T`, `T | NULL`, `T[]`, and `T[named]`.

Binders are rank-1: a binder is allowed only at the outermost level of a type expression, never
nested inside another type, and never inside parentheses. A directive's `{...}` payload does not
count as the outermost level, so the expanded form declares its type parameters with `@forall`, and
a named type declares them on its name, as in `@type Pair<T>`. All three of these are refused:

- `fn(f: <T> fn(T) -> T) -> integer`
- `list{ value: <T> list[T] }`
- `@param f {<T> fn(T) -> T}`

A refused binder is reported once. The type is then read as though the binder had not been written,
and the block carries no typing payload.

#### Constraints

A binder name may carry a constraint, written `NAME: CONSTRAINT`, as in
`<T: numeric> fn(values: T) -> T`. These are the constraints:

- `numeric` admits `integer` and `double`, scalar or vector, and any class that declares an
  arithmetic [operator method](#operator-methods-on-a-class).
- `atomic` admits one of the six atomic scalar types: `logical`, `integer`, `double`, `complex`,
  `character`, and `raw`.
- `key` admits a scalar `logical`, `integer`, `double` or `character`, the types a dictionary key
  or set element may have. `complex` and `raw` are left out.
- `scalar numeric` admits a scalar `integer` or `double`, which is both bounds at once. It is what an
  endpoint of `:` infers, so `function(n) 1:n` is `<T: scalar numeric> fn(n: T) -> double[]`.
- `item` admits what a [`List`](#lists) can hold: a number, a `Bool`, a `Str`, or another ry value.
  `List.from_r` uses it to type a `list[T]` argument.

Any other constraint name is an annotation error, and the error lists the ones that exist. An
argument whose type violates a constraint is a type error at the call. A union satisfies a
constraint when every member does, so `double | integer` satisfies `numeric`. A vector `U[]`
satisfies `numeric` when its element is a number, and an undetermined element becomes a
`scalar numeric` one. A constrained value that meets a union takes the union whole when the
constraint admits every member, so a number meeting `integer | double` stays `integer | double`.
Otherwise it takes the first member it fits, so
`function(n) if (length(n) == 1L) half(n) else lapply(n, half)`, where `half` needs a number, gives
`n` the type `T[]` from `lapply`'s `list[T] | T[] | NULL`, with `T: scalar numeric`.

A constraint limits what a caller may instantiate `T` with, and the annotated body may rely on it.
Under `<T: numeric> fn(x: T) -> T` the body may use `x` as a number. A body under a plain `<T>` that
does arithmetic is a type error, and `atomic` does not imply `numeric`.

Using a type parameter as a vector element, `T[]`, imposes the `atomic` bound, because a vector holds
only atomic elements. This is what makes element-preserving signatures possible. With
`keep : <T> fn(x: T[]) -> T[]`, `keep(c("b", "a"))` is `character[]` and `keep(c(1L))` is
`integer[]`, while a list argument cannot bind `T` at all. Several rules follow from the bound:

- A scalar argument coerces into a generic vector parameter and binds the element, so
  `<T> fn(x: T[])` called with `2.5` binds `T := double`.
- `[[` on a generic vector `T[]` extracts `T`.
- An arithmetic operator on a `T[]` operand also requires the element to be numeric, so the variable
  then holds both bounds. The result keeps the element, so `keep(x) + 1L` is still `T[]`, unless a
  `double` operand promotes the result to `double[]`.
- A comparison on a `T[]` operand yields `logical[]` and constrains nothing beyond the bound.

A bound that can no longer be satisfied is a type error at the expression that imposed it, whether
that means binding an element variable to a type that is not atomic or requiring a `character`
element to be numeric.

Writing `X[]` is an error when `X` is neither an atomic type nor a type parameter. Records,
functions, and nominal types are all such an `X`, and `list[X]` is how to write a list of them. An
alias expands first, so `Id[]` with `@alias Id {integer}` is fine, while an alias of a record is
refused.

#### Named types and generic application

Named types are declared with `@type` and `@alias`, and either may take parameters, as in
`NAME<T, U>`:

- `type NAME = TYPE`, or `#: @type NAME {TYPE}`, declares a *nominal type* whose representation is
  `TYPE`.
- `alias NAME = TYPE`, or `#: @alias NAME {TYPE}`, declares a *structural alias* for `TYPE`.

The two forms share one namespace, so reusing a name under either form is an error, except for a
`#:` definition paired with the inline one directly below it
([inline and comment annotations together](#inline-and-comment-annotations-together)). A definition
is allowed only at the top level of a file. Definitions are project-global, so a reference need
not come after the declaration; [type names](#type-names) has the scoping rules.

The declared type parameters are in scope only within `TYPE`, where they shadow any project-global
type of the same name. A type parameter is not itself a generic, so applying type arguments to one,
as in `Wrap<integer>` where `Wrap` is a parameter, is an annotation error rather than a reference to
the shadowed global.

A named generic is applied with angle brackets, as in `Box<integer>`, and the application must match
the declaration's arity:

- Applying the wrong number of type arguments is an error at the applied name. For `Pair<T, U>`,
  `Pair<integer, character>` is valid, while `Pair<integer>` and `Pair<integer, character, double>`
  are errors.
- Applying type arguments to a declaration that is not generic, such as `Meters<integer>`, is an
  error.
- A bare reference to a generic, such as `Box` without arguments, is an error everywhere except after
  [`@new`](#nominal-introduction).
- A wrongly applied name then compares like `Unknown`, so the one arity error never cascades into
  mismatches between values.

#### Type aliases

An alias is purely structural: writing its name is the same as writing the type it stands for. It
creates no new identity, and may appear anywhere a type may, including inside a larger type. An
alias whose expansion reaches itself, directly or through other aliases, is an error reported at
each declaration on the cycle, whether or not an annotation uses it. An annotation that uses such an
alias checks nothing.

##### Inline

```r
alias Box<T> = list{ value: T }

value: Box<integer> <- list(value = 1L)
```

##### Comments

```r
#: @alias Box<T> {list{ value: T }}

#: Box<integer>
value <- list(value = 1L)
```

#### Nominal types

A nominal type creates a fresh type identity, even when another nominal type has exactly the same
representation. Its name may appear anywhere a type expression may.

- A nominal type is compatible with itself.
- Two different nominal types are not compatible with each other, even when their representations
  are identical.
- A structural value is not compatible with a nominal type unless [`@new`](#nominal-introduction)
  introduces it.
- A value of a nominal type *is* compatible with its representation type, so it can be passed to any
  function written for the representation, while `@new` stays the only place the type's invariant is
  established.
- When an operator, an indexing form, or a loop needs a structural shape, a nominal value projects to
  its representation type. The result of the projection is structural, not nominal.

In this example, `Person` and `Pet` are distinct and incompatible. The annotation on `shape` is valid
because a nominal value satisfies its representation, and the final call is an error because a
structural value does not satisfy the nominal type:

##### Inline

```r
type Person = list{ name: character, age: double }
type Pet = list{ name: character, age: double }

person <- @Person(list(name = "bob", age = 20))

shape: list{ name: character, age: double } <- person

get_name <- function(value: Person) -> character value$name

get_name(list(name = "bob", age = 20))
```

##### Comments

```r
#: @type Person {list{ name: character, age: double }}
#: @type Pet {list{ name: character, age: double }}

#: @new Person
person <- list(name = "bob", age = 20)

#: list{ name: character, age: double }
shape <- person

#: fn(value: Person) -> character
get_name <- function(value) value$name

get_name(list(name = "bob", age = 20))
```

Projection is what makes field access and arithmetic work on a nominal value. In `get_name`,
`value$name` is `character` because `$` sees the representation. With `@type Meters {double}`,
`height + height` is `double`: arithmetic projects `Meters` to `double`, and the result does not keep
the nominal identity.

##### Opaque nominal types

An *opaque* nominal type has no representation to project. The standard-library stubs declare
`factor`, `connection`, `Date`, and other types the grammar cannot describe structurally as a bare
`@type NAME` (see [stubs](/development/authoring-stubs.md)). For these types:

- `$`, `[`, and `[[` are accepted and give `Unknown`, because the R objects behind these classes
  commonly support access that depends on values.
- The access is not checked further: there is no field-existence, index-count, or index-type check.
- Every such access is an unsupported construct under [strict mode](#strict-mode).
- Arithmetic and every other structural requirement remain type errors, unless the class declares
  the matching [operator method](#operator-methods-on-a-class). The nominal identity itself checks
  like any other nominal type.

`data.frame` is not opaque: the stubs declare it as `@type data.frame {list[named: Unknown]}`, the
named list of untyped columns it is at run time. A data frame is therefore accepted wherever a
named list is, as in `lapply(frame, f)` and `vapply(frame, is.numeric, logical(1))`. A column read
such as `frame$amount` or `frame[["amount"]]` is `Unknown`, and strict mode reports it where it is
read. The stubs also declare its methods, so `frame[rows, cols]` is `Any`
(R keeps the frame or drops it to a column depending on the indices), arithmetic such as
`frame / 100` keeps the `data.frame`, and a comparison such as `frame > 0.5` is a `matrix`.

#### Type-argument variance

Two applications of the same generic nominal type, such as `Box<integer>` and `Box<integer | NULL>`,
are compared one type argument at a time. Each parameter's *variance* follows from where it occurs
in the representation:

- **Covariant** positions keep the checking direction. They are a function's return, a direct
  occurrence, and an element of a container or structural type (a `list` item, a `list{...}` field,
  a tuple item, a vector element, or a union member). So `Box<integer>` is accepted where
  `Box<integer | NULL>` is expected.
- A function **parameter** position is contravariant and flips the direction. Given
  `@type Handler<T> {fn(value: T) -> NULL}`, a `Handler<integer | NULL>` is accepted where a
  `Handler<integer>` is expected, but not the other way around, because then a `NULL` could reach a
  function that only accepts `integer`.
- A parameter that occurs in both kinds of position is **invariant**, and its arguments must match
  exactly. Given `@type Cell<T> {list{ get: T, set: fn(value: T) -> NULL }}`, `Cell<integer>` and
  `Cell<integer | NULL>` are incompatible in both directions.
- A parameter that does not occur at all constrains nothing, and accepts any argument.

A type parameter inside a nested generic application, such as the `T` of `Sink<T>` within
`@type Outer<T> {Sink<T>}`, is invariant: the inner type's own variance does not compose with the
outer direction. When a generic nominal has no visible definition, every argument is checked
invariantly, which errs toward rejecting rather than toward accepting an unsound widening.

R's lists and vectors are mutable, yet their element positions are treated as covariant. A sound
mutable container would have to be invariant, which would break structural coercions such as scalar
to vector and `T` into `T | NULL`.

### Union types

A union type `A | B | ...` describes a value that has one of the member types. It may have any number
of members, any type may be a member, and it can be written anywhere a type can. `T | NULL` is the
nullable form of `T`. A union records the shapes a value can take without merging or coercing its
members:

- `integer | character`
- `character[] | NULL`
- `fn(count: integer | NULL) -> character | logical | NULL`
- `(fn() -> integer) | NULL`, a function returning `integer`, or `NULL`

A type may be parenthesized for grouping, where `(TYPE)` means exactly `TYPE`. In
`fn() -> integer | NULL` the `->` extends over the whole union, so an optional callback has to be
written `(fn() -> integer) | NULL`, which is also how it renders.

#### Union normalization

Unions are kept in one normal form, so equivalent spellings mean the same type and render the same
way. Every union, written or inferred, is normalized:

- A member that is itself a union is flattened, so `(A | B) | C` becomes `A | B | C`.
- Repeated members collapse, keeping the first, so `integer | character | integer` becomes
  `integer | character`.
- Member order does not affect meaning. Rendering keeps first-occurrence order, except that `NULL`
  always renders last.
- A union whose members collapse to one type is that type, so `integer | integer` is `integer`.
- A union with an `Any` member is `Any`, because every value already satisfies `Any`. So an `if`
  whose branch is `Any` is `Any` (`if (is.null(f)) order else f` with `f <- attr(x, "f")`), and
  not the other branch's type. A variable that two paths write is different: it keeps the typed
  path's type, so a later use of it is still checked.
- Otherwise, a union with an `Unknown` member is `Unknown`.

A call's result drops a union member that is a type parameter of the called function when the
callee's parameters mention it only as what a callback returns and the call left it unconstrained,
because the callback then never produces such a value. `Result.and_then` returns
`Result<B, E | F>`, where `F` is the error type of the step, so a step that never fails leaves `F`
unconstrained and the result keeps the error `E` alone:

```r
a <- Result.and_then(Str.to_integer("1"), function(n) :Ok(n))
# :Ok(integer) | :Err(:InvalidNumStr)
b <- Result.and_then(Str.to_integer("1"), function(n) if (n > 0L) :Ok(n) else :Err(:NotPositive))
# :Ok(integer) | :Err(:InvalidNumStr | :NotPositive)
```

A union made only of such parameters stays as it is. A type parameter that an argument fills
directly, or that appears only in the result (`<T> fn(name: character) -> T | NULL`), is kept,
because there an open `T` means any value. So is one that code outside the call still reaches,
such as an unannotated parameter passed as the callback:
`function(r, step) Result.and_then(r, step)` returns `:Ok(V) | :Err(U | W)`.

### Union compatibility

A value fits an expected union when it fits any one member, with the usual coercions applied per
member. So `integer` fits `integer | character | NULL`, and `NULL` fits any union that contains
`NULL`. Members are tried in order, and a failed attempt leaks no bindings into the next one.

A union *value* has to be acceptable in every shape it can take, so it fits an expected type only
when every one of its members does. A union therefore fits any wider union (`integer | NULL` fits
`integer | character | NULL`), but not a single member type: `integer | character` does not fit
`integer`, and `T | NULL` does not fit plain `T`.

An unannotated value checked against an expected union binds to the whole union at its first use.
Uses commit in program order, so a later use that needs a different type is reported at that later
site. When two union-typed contracts share only some members, such as `integer | character` at one
call and `logical | character` at the next, the checker does not compute their intersection; annotate
the value with the member type you intend.

## Records, tuples and tags

Records, tuples and tags are ry's own values, not R lists. The user guide is
[Records and tags](/guide.md#records-tags-and-match); this section is their typing contract. They are
inline syntax, so with `[check] inline-annotations = false` each literal, tag or `match` is reported
as a `ry-syntax` warning. Literals are still typed then, but a `match` gets no coverage check. Their types may be written in `#:` comments
either way.

### Record and tuple types

| Literal | Type |
| --- | --- |
| `(x = 1, y = 2)` | `Record{x: double, y: double}` |
| `(1L, "a")` | `Tuple{integer, character}` |
| `(x = 1,)` | `Record{x: double}` |
| `(1L,)` | `Tuple{integer}` |
| `()` | `Tuple{}` |

A one-field record and a one-item tuple need the trailing comma, because `(x = 1)` and `(x)` keep
their R meaning. A literal is all fields or all items, and a repeated field name is an error.

- A record's fields are all required. Field order is part of neither its identity nor its type, so
  `Record{x: double, y: double}` and `Record{y: double, x: double}` are the same type.
- A record and a list are different types: `Record{x: double}` does not fit `list{x: double}`, and
  the reverse does not fit either.
- `point$x` and `point[["x"]]` type as the field's type, and a field the record lacks is a
  `type-mismatch`. `pair[[1L]]` with a literal index types as that item, and an index past the end
  is a `type-mismatch`. On a record, a position counts the fields in their sorted order. A computed
  index types as the union of the item or field types.
- `point$x <- value` and `point[["x"]] <- value` rebind `point` to a copy with that field replaced,
  and the record keeps its type. The value must be compatible with the field's type, and a field the
  record lacks is a `type-mismatch`, because a record's fields are fixed.

### Tag types

A tag's type is written the way its value is, with types in place of values: `:None` has type
`:None`, `:Some(5L)` has type `:Some(integer)`, and `:Rect(width = 2, height = 3)` has type
`:Rect(width: double, height: double)`. Tags are structural and need no declaration.

A *tag union* is an ordinary [union](#union-types), so the union rules apply unchanged: a tag value
fits a union that lists a tag of the same name with a compatible payload, and an `if` whose branches
build different tags types as their union. Normalization merges two members with the same tag name
and payload shape into one member whose payloads are joined position by position, so joining
`:Some(1L)` with `:Some("a")` gives `:Some(integer | character)`. Two members with the same name and
a different payload shape are a `type-mismatch` where they meet.

A union that lists `..` as a member is *open*: it also holds every tag it does not list.

- A tag value fits an open union when the union lists its name with a compatible payload, or does
  not list its name at all.
- A closed union fits an open one when each of its members does.
- An open union never fits a closed union. It fits another open union only when every tag the
  target lists is also listed by the source, with a compatible payload.

There are no row variables, so a function cannot pass the unlisted tags of an open union through
with their types. Generic tag unions come from aliases, such as
`#: @alias Option<T> {:Some(T) | :None}`. One is built in: the
[standard library](/reference/standard-library.md) defines `Result<T, E>` as `{:Ok(T) | :Err(E)}`, and a
project's own `Result` alias shadows it.

### Nominal records, tuples and tags

A record, tuple or tag union may be the representation of a [nominal type](#nominal-types), as in
`type Shape = :Circle(radius: double) | :Square(side: double)`. The nominal rules apply unchanged, so
a structural value with the right shape, such as a bare `:Circle(radius = 1)`, does not fit `Shape`,
and only [`@Shape(...)`](#nominal-introduction) or `#: @new Shape` creates one. Wherever a rule of
this section needs the value's shape, the nominal value projects to its representation:

- `$`, `[[` and field writes follow the record and tuple rules above. A field write keeps the
  nominal type, its value must fit the field's type, and a field the representation lacks is a
  `type-mismatch`.
- A `match` checks its patterns and its [coverage](#exhaustiveness) against the representation, so a
  nominal tag union, including a recursive generic one such as
  `type Tree<T> = :Leaf | :Node(left: Tree<T>, value: T, right: Tree<T>)`, must be matched
  exhaustively.
- A binding pattern binds the value with its nominal type, and a payload binding has the payload's
  declared type, so `:Node(left = l, ..)` on a `Tree<integer>` binds `l` as a `Tree<integer>`.
- A nominal value whose representation is a record, tuple or tag is still a ry value when it
  [crosses into R](#crossing-into-r).

### Record update

`(..point, y = 3.5)` is a copy of the record `point` with the field `y` replaced. It has `point`'s
type, so every replaced field must exist and keep its type:

```r
p <- (x = 1, y = 2)
q <- (..p, z = 3)
```

```text
type-mismatch

  x field `z` does not exist in `Record{x: double, y: double}`
```

Only a record can be updated this way, and `$<-` is the statement form of the same change.

### `match`

`match (EXPR) { ARMS }` is a `match` expression only when the `{` is on the line of the closing `)`,
so every R use of `base::match` keeps its meaning. An arm is `PATTERN => EXPR` or
`PATTERN if (CONDITION) => EXPR`, separated by newlines, `;` or `,`.

| Pattern | Matches |
| --- | --- |
| `_` | anything, binding nothing |
| `name` | anything, binding it to `name` |
| `1L`, `"a"`, `TRUE`, `NA`, `NULL`, `-1` | a length-one value equal to the literal |
| `:Tag`, `:Tag(p1, p2)`, `:Tag(field = p)` | a tag with that name whose payload matches |
| `(p1, p2)`, `(p,)` | a tuple of that length whose items match |
| `(name = p, ..)`, `(name = p,)` | a record with those fields; without `..`, exactly those fields |
| `p1 \| p2` | either pattern; both sides must bind the same names |

The type of a `match` is the join of its arm types, as for `if`. A pattern that cannot match the
scrutinee's type, such as a tag a closed union does not list or a field the record lacks, is a
`type-mismatch` at the pattern. A scrutinee whose type is not yet known takes its shape from the
patterns: the arms' tags form a closed union. A catch-all arm accepts a value of any type, so with
one the scrutinee is not shaped by the patterns. Pattern
names are bound in the current environment, so after the `match` a name that only some arms bind
types like a variable assigned in only some branches of an `if`.

### Exhaustiveness

When the scrutinee's type is known, the arms must cover every value of it. Coverage is computed over
the cases the type has:

- a closed tag union has one case per tag, and an open union adds an "other tags" case that only a
  catch-all arm covers;
- a tuple or a record is one case, with its items or fields checked in turn;
- a scalar `logical` has three cases, `TRUE`, `FALSE` and `NA`. Coverage trusts the scalar claim,
  so a value typed scalar that holds several elements, such as `v[-1L]` (see
  [`[` on vectors](#-on-vectors-1)), matches no literal arm and stops with an error when the code
  runs;
- `NULL` is one case, and a union has the cases of each member;
- a nominal type has the cases of its representation;
- every other type has unboundedly many values, so only a binding or `_` covers it.

A guarded arm never counts toward coverage, because its guard can be false. A `match` that misses a
case is a `non-exhaustive-match` error naming up to three missing cases as patterns, and an arm that
the arms above it already cover is an `unreachable-pattern` warning.

### List and `as` patterns

`match` takes two more pattern forms. A list pattern matches a `List` by its length and items:
`[]` matches the empty list, `[a, b]` a list of exactly two items, and `[first, ..rest]` a list of at
least one item, binding the remaining items to `rest` as a list. `[.., last]` matches from the end.
`p as name` matches what `p` matches and binds the whole value to `name`:

```r
describe <- function(xs: List<I64>) -> Str match (xs) {
  [] => "empty",
  [only] => f"just {only}",
  [first, ..rest] as all => f"{List.len(all)} items, starting with {first}"
}
describe([])
#> [1] "empty"
describe([1i64, 2i64, 3i64])
#> [1] "3 items, starting with 1"
```

### Propagating an error with `try`

`try f(x)`, where `f(x)` returns a result such as `:Ok(value) | :Err(error)`, is the `value` of an
`:Ok`. On an `:Err` the enclosing function returns that `:Err` at once, and the function's result
type gains its error:

```r
parse_both <- function(a: Str, b: Str) {
  x <- try Str.to_i64(a)
  y <- try Str.to_i64(b)
  :Ok(x + y)
}
```

`parse_both` types as `fn(a: Str, b: Str) -> :Err(:InvalidNumStr) | :Ok(I64)`. `try` applies to a
name or call written directly after it. `try (expr)` and `try` before anything else keep R's
meaning, a call of R's `try()`, so no R code changes meaning. A `try` outside a function, or on a
value that is not a result, is a `type-mismatch`.

### Crossing into R

R functions and C code do not know these values. `as.list()` converts a record, tuple or tag to a
list, and `as.record()`, `as.tuple()` and `as.tag()` convert back.

Passing one to an R function that is not the project's own is a `type-mismatch` at the argument. The
exceptions are the functions the runtime lets them through: those that understand them (`format`,
`print`, `identical`, `length`, `[[`, the conversions), those that only ask what a value is
(`is.null`, `class`, `inherits`), and those that store a value without looking inside it (`list`,
`lapply`, `do.call`). A value whose type only sometimes is a record, tuple or tag, such as
`Record{x: double} | NULL`, is not reported, because it may be R data when the code runs.

### Records from R

R data enters a typed function only through its parameters, one vector or scalar each, converted
where the call is written (see [Lists and R vectors](#lists-and-r-vectors)). An R list is never a
record, tuple or tag, so passing one where a record is expected is a `type-mismatch`:

```r
alias Trial = Record{time: List<I64>, treated: List<Bool>}
trial_size <- function(trial: Trial) -> I64 List.len(trial$time)
trial <- list(time = c(5L, 3L), treated = c(TRUE, FALSE))
trial_size(trial)
```

```text
type-mismatch

  x expected `Record{time: List<I64>, treated: List<Bool>}`, found `list{time: integer[], treated: logical[]}`
   --[main.R:4:12]
 3 | trial <- list(time = c(5L, 3L), treated = c(TRUE, FALSE))
 4 | trial_size(trial)
   |            ^^^^^

  x strict mode found 1 error, so this code does not run
```

Pass the fields as parameters instead, and build any record inside the typed function:

```r
trial_size <- function(time: List<I64>, treated: List<Bool>) -> I64 List.len(time)
time <- List.from_r(c(5L, 3L))
treated <- List.from_r(c(TRUE, FALSE))
trial_size(time, treated)
#> 2i64
```

A record that R code converts with `as.record()` passes the type check, but compiled typed code
takes records only from typed code, so a call that passes one runs in the interpreter.

## Numbers, `Bool` and `Str`

ry has its own scalar types, none of which holds `NA`. They are the types typed ry is written in,
and an R value reaches them only through an explicit conversion (see
[Crossing between R and ry scalars](#crossing-between-r-and-ry-scalars)).

### Number types

| Type | Values |
| --- | --- |
| `I64` | a 64-bit signed integer, every bit pattern a value |
| `F64` | an IEEE 754 double, including `NaN` and the infinities |

An `F64` is stored as R's `double`, so an `F64` fits `double` and is passed to R code as is. An
`I64` does not share R's `integer`, because R reads one 32-bit pattern as `NA` and overflows to `NA`
with a warning: `-2147483648i64` is an ordinary `I64`, and overflow is an error.

The constraint `number` admits both types.

### Number literals

A suffix names a literal's type exactly: `5i64` or `1.5f64`. A hex literal takes only the `i64`
suffix (`0xFFi64`), because `f` is a hex digit. A `-` written directly before a literal is part of
it, so `-9223372036854775808i64` is an `I64`. Any other suffix is a syntax error.

An unsuffixed literal, such as `5`, `5L` or `1.5`, has R's type unless a ry number type asks for it.
A ry type asks in three places:

- **An expected type.** A typed parameter, an annotated variable, a function's declared result, a
  list item or a record field whose type is known.
- **The other operand.** In arithmetic or a comparison with an operand of a ry number type, the
  literal takes that type, so `n + 1` with `n: I64` is an `I64`.
- **A later use.** `total <- 0` gives `total` a literal type that its first use in the same
  function decides: an operand beside a ry number, an argument to a typed parameter, an annotated
  binding, or a value written into a `List`'s item (`lookup[[i]] <- j` with `lookup: List<I64>`)
  or a record's field (`r$x <- j` with `x: I64`). In `for (x in xs) total <- total + x` with
  `xs: List<F64>`, `total` is an `F64`, and
  `rate <- 2.0; half(rate)` with `half(x: F64)` makes `rate` an `F64`. Any other read gives the
  variable R's type, as does a function that never decides it. A literal written as a tuple item
  or a record field is decided the same way: in `pair <- ("a", 1)`, the read
  `Str.concat(s, pair[[1]])` makes `"a"` a `Str`, and with no such use `pair` is a
  `Tuple{character, double}`.
- **A top-level binding in a typed file.** In a strict file, or a file written with ry syntax (an
  inline annotation, a record, tuple, tag, `List` or `match`), a literal bound outside any function
  is a ry value: `count <- 3` is an `I64`, `rate <- 2.0` an `F64`, `name <- "ry"` a `Str` and
  `flag <- TRUE` a `Bool`. A literal written with a decimal point or an exponent (but not `1e3L`),
  or a whole number past the range of `I64`, is an `F64`, and arithmetic on literals alone is one
  literal, so `step <- 1 / 4` is an `F64`. Each top-level
  statement is checked on its own, so nothing later in the file decides the type. In any other file
  a top-level literal has R's type.

A value written with literals alone is decided as one literal, wherever a lone literal would be:

- Arithmetic (`+`, `-`, `*`, `%%` and `/`), so `2 * 3.14159 * r` with `r: F64` is an `F64`, and `/`
  asks for `F64`.
- Logic and comparisons (`!`, `&&`, `||`, and a comparison of number literals), so
  `ok: Bool <- 1.5 < 2` holds, and a literal beside a `Bool` takes that type: `TRUE && done` with
  `done: Bool` is a `Bool`.
- An `if` whose branches are such values, and a `{}` holding one, so `x: F64 <- if (c) 0.1 else 3`
  holds and `if (c) 1 else 2.5` at a top-level binding is an `F64`.

A string or `TRUE`/`FALSE` bound to a variable is decided the same way, as `Str` or `character`
and `Bool` or `logical`. A ry number that a call leaves open is decided by an annotation as well,
so `total: F64 <- List.sum([3])` sums a `List<F64>`.

A literal the type cannot hold exactly, such as `2.5` as an `I64`, is a
`type-mismatch` at the literal:

```r
m <- 5i64
m * 2.5
```

```text
type-mismatch

  x this literal does not fit `I64`, which cannot hold its value exactly
```

A literal runs as the type the checker gave it. Before `ry run` or the console runs code on ry's
runtime, every unsuffixed literal the checker typed as `I64` is spelled with its suffix, so the arm
`:Err(_) => 0` in a function declared `-> I64` returns `0i64`, and `xs <- [1, 2]` is a `List<I64>`.
An empty list keeps its item type the same way: `[]` and a `List.map` whose items come from its
callback carry the item type the checker gave them, so `List.map(List.range(3, 1), \(v) v * 2)` is
an empty `List<I64>` and its `List.sum` is `0i64`.
A file with no ry syntax and no strict mode is not analyzed, and its literals keep R's types. Code
that `ry load` or `source()` runs is not elaborated this way: there an operator converts a literal
operand, and an annotated binding such as `n: I64 <- 5` converts its literal. An `I64` parameter and an `-> I64` result
convert the same way, so `f(3)` passes `3i64` to `f <- function(n: I64) ...`. A conversion that
cannot be exact is an error, never a rounded value.

### Number arithmetic

Both operands of an arithmetic operator or comparison have the same number type, and the two types
are never converted into each other: `1i64 + 1.5f64` is a `type-mismatch` that tells you to convert
one side.

| Operator | `I64` | `F64` |
| --- | --- | --- |
| `+ - *`, unary `-` | the same type; overflow is an error | the same type |
| `/` | a `type-mismatch` that suggests `%/%` or `Num.to_f64()` | the same type |
| `%/%`, `%%` | floored division and modulo, as in R | as in R |
| `^` | the same type | the same type |
| `== != < > <= >=` | `Bool` | `Bool` |

Integer division by zero is an error. `Num.div_trunc` and `Num.rem` give truncating division, and
`Num.add_checked`, `Num.add_wrap` and `Num.add_saturated` (with their `sub` and `mul` siblings) give
the other overflow behaviors. `Num.to_i64` and `Num.to_f64` convert between the two types.
`Num.to_i64` is an error when the value is not whole or does not fit, and `Num.to_i64_checked`
returns `:Err(:OutOfBounds)` instead.

### `Bool` and `Str`

`Bool` is `TRUE` or `FALSE`, never `NA`. A comparison of ry numbers or strings is a `Bool`, as is
`!`, `&&`, `||`, `&` or `|` on `Bool` operands. `if` and `while` take a `Bool` or an R `logical`.

`Str` is an immutable UTF-8 string, never `NA`. A string literal becomes a `Str` where one is
expected, and the `Str` module holds the functions that work on strings. A `Bool` is stored as R's
`logical` and a `Str` as R's `character`, so both pass to R code as they are.

`f"..."` builds a `Str` from text and interpolated expressions, each written in braces:

```r
name <- "ry"
n <- 5i64
f"hello {name}, {n + 1i64}"
#> [1] "hello ry, 6"
```

Doubled braces, `{{` and `}}`, stand for literal braces. R reads `f"..."` as a syntax error, so no R
code changes meaning.

### Crossing between R and ry scalars

`Num.from_r` turns an R `double` into an `F64` and an R `integer` into an `I64`, and `Str.from_r`
turns a `character` into a `Str`. Each stops with an error on `NA`, on a length other than one, and
on attributes. `Num.to_r` goes the other way: an `I64` becomes R's `integer` when it fits in 32
bits and a `double` otherwise.

No R type represents an `I64`, or a `List` whose items are not `F64`, `Bool` or `Str`, so passing
one to an R function is a `type-mismatch` that names the conversion. When such code runs anyway, the
R function stops with the same advice:

```r
n <- 4
inc <- function(x: I64) -> I64 x + 1
sqrt(n)
```

```text
type-mismatch

  x `sqrt` is an R function, and this value is a ry `I64`, not an R object. Convert it with `Num.to_r()` first
```

An `F64`, `Bool` or `Str`, and a `List` of one of them, shares the representation of R's `double`,
`logical` or `character` (vector), so it passes to R code unconverted: `sqrt(2.0)` and
`mean([1.5, 2.5])` need no conversion.

## Lists

A `List` is ry's typed sequence, and this section
is its typing contract. The `[...]` literal is inline syntax, so with
`[check] inline-annotations = false` each literal is a `ry-syntax` warning, and it is still typed.
The type `List<T>` may be written in `#:` comments either way.

### List literals

`[a, b, c]` types as `List<T>`, where `T` is the type of the first item. Every other item must have
exactly that type: items are never converted into each other, so `[1, "a"]` is a `type-mismatch` at
`"a"`. An unsuffixed number literal is decided by the list it is in, as described under
[number literals](#number-literals): `[1, 2]` is a `List<I64>`, `[1.5, 2]` is a `List<F64>`, and
`[1i64, 2]` is a `List<I64>`. A literal the item type cannot hold exactly, such as `2.5` in
`[1, 2.5]`, is a `type-mismatch`. Tags are the one exception to exact item types: their types join
into a tag union, so `[:Ok(1), :Err("no")]` is a list of `:Ok(double) | :Err(character)`.

An item is a number, a `Bool`, a `Str`, or another ry value: a record, tuple, tag, `Dict`, `Set` or
list. Any other item type is a `type-mismatch`, and so is the literal `NA`. A type does not say
whether a value is missing, so an item computed by R code may still be `NA`, and the constructor
stops with an error on it when the code runs. In an annotation, `List<T>` with any other `T`, such
as `List<double[]>`, is an `annotation` error.

The empty literal `[]` takes its item type from an annotation, as in `#: List<Str>`, or from a use
such as `List.append(xs, 1)`.

### Lists and R vectors

- `List<F64>`, `List<Bool>` and `List<Str>` are stored as R `double`, `logical` and `character`
  vectors, and they fit `double[]`, `logical[]` and `character[]`. A list of ry values fits
  `list[T]`. Other lists, such as `List<I64>`, cross to R only through `List.to_r()`.
- A plain R vector never fits `List<T>`. `List.from_r(x)` converts one: a `double[]` gives
  `List<F64>`, a `character[]` gives `List<Str>`, and a `list[T]` gives `List<T>` when `T` is a ry
  value (the `item` constraint).
- At run time `List.from_r()` stops with an error on an `NA` or an attribute such as a class, and it
  drops names. Setting an attribute on a list, or assigning `NA` into it from R code, turns it into a
  plain R vector.
- At run time `List.from_r(x)` gives a list of the item type the checker gave it, which comes from
  R's vector types. A vector R types as `double` holds integers when R computed it from integers,
  as `abs(-3:3)` does, so where the checked type is `List<F64>` an `integer` or `logical` vector
  converts to `F64` items, and where it is `List<I64>` a `logical` vector converts to `I64` items.
  An empty vector gives an empty list of the checked type:

  ```r
  whole <- function() abs(-3:3)
  total <- function(extra: F64) -> F64 {
    List.sum(List.from_r(whole())) + extra
  }
  total(0.5)
  #> [1] 12.5
  ```

  A vector of any other type stops the conversion with an error. That happens when R code gives a
  value its types do not describe, for example after it binds a function to something else:

  ```r
  prices <- function() c(1.5, 2.5)
  count <- function(extra: F64) -> F64 {
    listed <- List.from_r(prices())
    Num.to_f64(List.len(listed)) + extra
  }
  assign("prices", function() c("1.5", "2.5"))
  count(3)
  ```

  ```text
  Error: `List.from_r(prices())` gave a `List<Str>` where the type checker expects a `List<F64>`, the type of the R code it read: convert the vector to that type in R first, for example with `as.numeric()`
  ```

### List operators

An elementwise operator takes two lists with the same item type, or a list and a single value of the
item type. Number types never mix, and an R vector operand is a `type-mismatch` whose message
suggests `List.from_r()`.

| Operator | Items | Result |
| --- | --- | --- |
| `+ - * %% %/% ^`, unary `-` | numbers | `List<T>` |
| `/` | `F64` | `List<T>` |
| `== != < > <= >=` | numbers and `Str` for ordering, any item for equality | `List<Bool>` |
| `& \| !` | `Bool` | `List<Bool>` |

Strings order as R orders `character` values in the session's collation locale, both as items and
as single `Str` values: in the `C` locale that is code point order, so `"B" < "a"` is `TRUE`.

`/` on `I64` items is a `type-mismatch`, as it is on a single `I64`, and it decides undecided
literal items as `F64`, so `[1, 2] / 2` is a `List<F64>`. When the code runs, two lists of different
lengths are an error rather than recycled.

### List indexing

- `xs[[i]]` takes one position and types as `T`.
- `xs[i]` takes positions, a `Bool` mask, or no index, and types as `List<T>`.
- A `character` index, or more than one index, is a `type-mismatch`, because a list has one
  dimension and no names.
- When the code runs, a negative position leaves an item out and a zero selects nothing, as in R. A
  position past the end, an `NA` position, or a mask of a different length is an error, never `NA`.
- A replacement through `[<-` or `[[<-` must be an item of the item type, or for `[<-` a list of
  them with one item per position, which is never recycled.

`for (x in xs)` binds `x` as `T`. The `List` module of the [standard library](/reference/std/list.md)
holds the functions that work on lists.

## Function types

A function can be annotated in one of two styles, but not both at once:

- the **expanded** style, with an optional `@forall`, then `@param` lines, then `@return` or
  `@returns`;
- the **compact** style, a single `fn(...)` type with an optional `-> RETURN_TYPE`.

Either way, consecutive `#:` lines form one annotation block for the function.

### Expanded function annotations

The expanded form puts one directive on each line: `@forall` to declare type parameters,
`@param name {TYPE}` for each parameter (or `@param [name] {TYPE}` for an optional one), and
`@return {TYPE}` or `@returns {TYPE}` for the result. A constrained binder is written
`@forall T: numeric`, with the same meaning as the compact `<T: numeric>`.

#### Inline

```r
double_count <- function(count: integer, label: character | NULL = NULL) -> integer {
  count + count
}

then_some <- function<T>(condition: logical, value: T) -> T | NULL {
  if (condition) value
}
```

#### Comments

```r
#: @param count {integer}
#: @param [label] {character | NULL}
#: @return {integer}
double_count <- function(count, label = NULL) { count + count }

#: @forall T
#: @param condition {logical}
#: @param value {T}
#: @return {T | NULL}
then_some <- function(condition, value) {
  if (condition) value
}
```

- Directives come in order: every `@forall` before any `@param`, and every `@param` before `@return`
  or `@returns`.
- Repeated `@forall` lines accumulate in source order, and a duplicate type parameter name is an
  error.
- At most one `@return` or `@returns` may appear. Without one, the return type is
  [elided](#elided-return-types).

### Compact function annotations

A compact annotation is a single function type, in one of these forms:

- `fn(name: TYPE) -> RETURN_TYPE`
- `fn(TYPE) -> RETURN_TYPE`
- `fn(name: TYPE, [optional_name]: TYPE) -> RETURN_TYPE`
- `<T> fn(name: TYPE) -> RETURN_TYPE`
- `<T, U, ...> fn(TYPE) -> RETURN_TYPE`

A leading `<...>` binder introduces [rank-1](#type-parameters-aliases-and-nominal-types) type
parameters for the whole function type. The binder always comes first: `fn<T>(...)` is not the
syntax. An optional parameter must be named, as in `[name]: TYPE`; a bare optional positional form
such as `fn(integer, [character])` is not supported. Omitting the return type
[elides](#elided-return-types) it.

A function may declare one rest parameter to accept a variable number of arguments. It is written
`...: TYPE`, and `fn(...)` is shorthand for `...: Any`. It has no name, because rest arguments are
matched by position, so `...items: TYPE` does not match the function's `...` and is reported, twice
at the same range: as a signature mismatch and as a parameter the function does not define. It can
come after the fixed parameters, as in `fn(prefix: TYPE, ...: TYPE) -> RETURN_TYPE`, or before named
ones, as in `fn(...: TYPE, [option]: TYPE) -> RETURN_TYPE`:

#### Inline

```r
join <- function(...: character) -> character paste0(...)

wrap <- function(x: character, ...: character) -> character {
  paste0(x, ": ", paste(...))
}
```

#### Comments

```r
#: fn(...: character) -> character
join <- function(...) paste0(...)

#: fn(x: character, ...: character) -> character
wrap <- function(x, ...) paste0(x, ": ", paste(...))
```

The position of the rest parameter, counted as the number of parameters declared before it, is part
of the signature. It must match the position of `...` in the function's formals, and it decides which
parameters a positional argument can fill (see [function calls](#function-calls) and
[function type compatibility](#function-type-compatibility)).

### Annotations and the formal list

An annotation declares the *types* of a definition's parameters, not the parameter *list*. R matches
a call's arguments against the formals in the `function(...)` header, so those formals are the call
interface: their names, their order, their defaults, and where `...` sits. An annotation cannot add,
remove, or reorder them. A parameter the annotation does not mention keeps its inferred type, which
makes annotating just one of several parameters a supported partial form.

When the declared shape disagrees with the definition, the definition wins at every call site, and
the disagreement is reported once, at the definition, so a call is never blamed for a mistake in an
annotation. The possible disagreements are:

- a declared parameter name that is not one of the formals (an annotation may not rename a
  parameter, so `fn(count: integer) -> integer` over `function(n) n` is an error);
- more declared parameter types than there are formals left to receive them;
- a declared optional `[name]` over a formal that callers may not omit (one with no default that
  the body [may force](#lazy-arguments-and-required-formals)), because declaring a parameter
  optional tells callers they may omit it;
- a parameter declared as required over a formal that has a default, because R lets callers omit it,
  so the annotation must say `[name]`;
- a rest parameter at a different position in the annotation than in the formals, or present on only
  one side, so a fixed annotation on a variadic function and a variadic annotation on a fixed
  function are both rejected.

The first case and a required declaration over a defaulted formal name the parameter. The others are
reported as a mismatch of the whole signature. In every case, the body is still checked under the
parameter types the annotation does pin down, so hover and navigation keep their facts.

### Elided return types

Both styles allow the return type to be left out: an expanded block without `@return` or `@returns`,
or a compact `fn(...)` without `-> RETURN_TYPE`. An elided return is not the same as a written
`NULL`, and what it means depends on whether there is a function body to infer from:

- On a checked annotation of a `function(...)` literal, the return type is inferred from the body,
  exactly as if there were no annotation, so annotating only the parameters never pins the return.
  `@param u {integer}` on `add_one <- function(u) u + 1L` infers `fn(u: integer) -> integer`. Writing
  the return as `Unknown` has the same effect, because `Unknown` never overrides what the body shows.
- In a nested function type, such as a callback parameter written `@param cb {fn(integer)}`, the
  elided return means `NULL`, which matches R functions called for their side effects.
- In a [trusted coercion](#trusted-coercions), and in an annotation on a value that is not a function
  literal, such as `#: fn(integer)` on `g <- f`, the elided return is `Unknown`, so a call's result
  goes unchecked even when `f`'s return type is known. This is a known gap.

A function that really does return `NULL` can say so with `@returns {NULL}` or `-> NULL`. The
explicit form is enforced, so a body that returns anything else is then a type error.

### Inferred function types

An unannotated `function(...)` expression gets its type from the definition itself:

- Every parameter appears as a named parameter under its name in the definition, because R matches
  parameters both by name and by position.
- A parameter with a default is optional at call sites, and so is one the body never forces, as
  [lazy arguments](#lazy-arguments-and-required-formals) describes.
- A default runs lazily in the function's own frame, so it sees the variables the body assigns.
  In `function(n, ma, innov = rnorm(n + q)) { q <- length(ma); innov }`, the `q` in the default is
  the body's local, not base R's `q()`. A name the body never assigns resolves outside the function
  as usual. Such a read is not yet typed against the body's writes, so it reads as `Unknown`.
- A `...` formal becomes a rest parameter with element type `Any`, at the position it holds among the
  formals, so `function(x, ...) …` is `fn(x: T, ...: Any) -> …`. The values that reach `...` are not
  tracked into the body, so forwarding `...` to another call gives `Unknown`.
- Parameter and return types are inferred, and a parameter nothing constrains generalizes when the
  function is bound to a name, so `function(x) x` is `<T> fn(x: T) -> T`.
- A requirement inference could not discharge survives into the exported type: a parameter used as a
  number exports as `<T: numeric>`, so calls from other files keep being checked.

`function(count, label = NULL) count` may therefore be called as `f(1L)`, `f(count = 1L)`, or
`f(1L, "x")`.

#### A return chosen by a flag

A body that ends in `if (flag) a else b`, where `flag` is a formal with a literal `TRUE` or `FALSE`
default that the body never reassigns, returns the union of both branches, as any `if` does. A
branch may also end in `return(value)`, and the flag may instead guard an earlier
`if (flag) return(value)` with no `else`, whose return is then the true branch and the rest of the
body the false one, provided those `return()` calls are the body's only early returns. A call that leaves the flag out, or passes a literal, selects one branch,
so it returns that branch's type alone:

```r
p_dist <- function(q, valueOnly = TRUE) {
  prob <- q * 2
  if (valueOnly) prob else list(value = prob, error = prob)
}
# p_dist: <T: numeric, U> fn(q: T, [valueOnly]: U) -> double | list{value: double, error: double}
gap <- function(x, p) p_dist(x) - p
# gap: <T: numeric, U: numeric> fn(x: T, p: U) -> double
full <- function(x) p_dist(x, valueOnly = FALSE)$error
# full: <T: numeric> fn(x: T) -> double
```

Any other flag argument, such as a variable, returns the union. A call that forwards `...` selects
by its visible arguments, so a flag passed through `...` is not seen: in
`wrapper <- function(x, ...) p_dist(x, ...)`, the wrapper returns `double` even when its caller
passes `valueOnly = FALSE`. This is a deliberate limit, because treating every forwarding call as
unselected reports ordinary wrappers that never pass the flag. An annotation has no syntax for
the selection, so a declared signature always returns its declared type.

#### Defaults

Defaults are type-checked, and they interact with the parameter's type in four ways:

- An error inside a default is reported, and the default of an annotated parameter must be
  compatible with the declared type.
- A `NULL` default is checked like any other. `function(title = NULL)` is R's usual way to write an
  optional argument, but when the caller omits it, `title` is `NULL` inside the body, so declaring it
  `character` is a promise the function does not keep. Declare `character | NULL` and narrow with
  `if (is.null(title))`. Marking the parameter `[title]` relaxes only the call.
- An unannotated parameter takes its type from its uses, not from its default, so
  `function(x = 1) x` is `<T> fn([x]: T) -> T`, and passing a character is not a finding.
- A call that omits the argument gets the default's type, because that is the value R puts in the
  frame: with `f <- function(x = 1) x`, `f()` is a `double` and `f("a")` is a `character`. A default
  is therefore checked against an *instantiation* of the declared type rather than against the
  binder, so `#: <T> fn([x]: T) -> T` over `function(x = 1) x` is accepted. A concrete declared type
  is unaffected: `fn(title: character)` still refuses a `NULL` default.
- An inferred parameter type always admits the default's type, because a call that passes the
  default's own value is always fine. When the body settles an unannotated parameter on a type the
  default does not have, the exported type is widened by the default's: with `up` declared
  `fn(x: character) -> character`, `function(s = NULL) up(s)` is
  `fn([s]: character | NULL) -> character`.

An `if` without `else` that writes a formal under a test reading that same formal *normalizes* the
input, as in `if (is.logical(type)) type <- if (type) "q" else "m"` or
`if (is.null(sep)) sep <- ","`. The write does not constrain the formal's own type, so callers may
still pass anything, and after the `if` the body sees the written type rather than a union with the
formal's type:

```r
to_double <- function(x = 1) {
  if (is.character(x)) x <- as.numeric(x)
  x
}
# to_double: <T> fn([x]: T) -> double
```

This is a deliberate approximation. A union with the open formal type would make every later use of
the value accept anything, while the normalized type is what the code after such a test assumes. A
`NULL` write is not a normalization and joins as an ordinary branch write.

### Function literals in call arguments

A function literal passed as a call argument takes its parameter types from the function type the
callee expects at that position. The other arguments are checked first, so the callee's type
parameters are already bound when the literal's body is inferred:

```r
xs <- [1, 2]
pairs <- List.map(xs, \(x) c(x, x))
# error: this function must return a list item (...), but it returns `double[]`
```

`List.map` expects `fn(T) -> U` with `T` bound to `double` by `xs`, so `x` is `double` inside the
body, `c(x, x)` is `double[]`, and the `item` constraint on `U` refuses it. Without the expected
type, `x` would be an open variable and `c(x, x)` could not be typed. The rule has these limits:

- It applies only to a literal written directly as the argument, with no `#:` or inline annotation
  on any of its formals. An annotated formal keeps its annotation, which is then checked against the
  expected type.
- Every formal without a default must receive a type, or none does. In
  `Reduce(function(a, b) a + b, xs)` the accumulator's type is still open when the literal is
  checked, so both formals stay open and are inferred from the body, as for any unannotated
  function. A formal with a default is always left to inference.
- With an overloaded callee, a formal takes a type only when every candidate that accepts the other
  arguments expects the same one. The overload is then chosen as usual, with the literal's inferred
  type among the arguments.
- A formal is an accumulator when its expected type shares a type variable with the expected
  result type, and another argument of the call has exactly that variable as its type: `seen` is
  one in `List.walk(xs, state: S, f: fn(S, T) -> S)`. The result widens the variable, so the type
  the initial state gives it (such as an empty `list()`) is no context, and by the rule above the
  literal takes no types. A variable fixed by a collection is not widened, so in
  `List.update(xs, i, f: fn(T) -> T)` the literal's formal still takes the item type.
- A literal with a formal after `...` takes no types, because R binds positional arguments to
  `...` before any later formal.
- A parameter type that is `Any`, `Unknown` or still contains an open type variable gives no
  context.

When the body uses a parameter that took its type this way as an operand its type does not allow,
the finding is reported on that use and names the parameter. Other misuses, such as passing the
parameter to a function that expects another type, keep their usual wording:

```r
words <- ["a", "b"]
bad <- List.map(words, \(w) w * 2)
# error: `w` is used as a numeric value (`integer` or `double`) here, but the call passes this
# function `character` for it
```

### Named and positional parameters

Parameter names in a function type are part of the call interface. A named parameter may be passed
as a named argument, while an unnamed parameter is positional only. So `fn(count: integer) -> integer`
allows a call with `count = 1L`, while `fn(integer) -> integer` makes a named argument a type error,
but only when no definition stands behind the type. When the annotation sits on a `function(count)`
definition, the formals supply the name, and `f(count = 1L)` stays legal. An optional parameter
follows the same rule, and must be named.

Parameter, field, and type names may contain `.`, matching R's convention for names such as
`na.rm` and `length.out`: `fn(x: double, na.rm: logical) -> double`, `list{na.rm: logical}`, and
`@type My.Type {integer}` are all valid.

### Function type compatibility

A function value is compatible with an expected function type when its parameters accept every call
the expected type may make, and its return type satisfies the expected return type.

Parameters pair by name where the expected type names them, because R matches arguments against the
definition's formal names. So `fn(a: integer, b: character)` accepts a function defined as
`function(b, a)`. An unnamed parameter type pairs with the remaining parameters from left to right,
so `fn(count: integer) -> NULL` and `fn(integer) -> NULL` are compatible with each other.

Arity is a range, not a fixed count. The function may declare more parameters than the interface
passes, as long as the extra ones have defaults. It may not require more than the interface supplies,
and it may not refuse an argument the interface may send. An optional parameter in the expected type
promises callers they can omit it, so the function's formal must have a default.

Parameters are contravariant and the return type is covariant: each expected parameter type must be
compatible with the function's parameter type, and the function's return type must be compatible
with the expected one.

- `fn(integer | NULL) -> integer` is accepted where `fn(integer) -> integer` is expected.
- `fn(integer) -> integer` is rejected where `fn(integer | NULL) -> integer` is expected, because the
  interface may pass `NULL`.
- `fn(a: integer, [b]: integer) -> integer` is accepted where `fn(integer) -> integer` is expected,
  because `b` has a default. This is what lets a standard-library function serve as a callback:
  `lapply(list(mean, sd), function(g) g(1:3))` is `list[double]`, even though `mean` and `sd` declare
  optional formals the callback never passes.
- `fn(a: integer, b: integer) -> integer` is rejected there, because the interface never supplies `b`,
  and `fn() -> integer` is rejected because it cannot receive the argument the interface sends.
- `fn(count: integer, [label]: character) -> integer` does not accept `function(count, label) count`
  in a checked annotation, because `label` has no default. At an argument position this is not yet
  checked, which is a known gap.

A variadic function serves a fixed-arity interface, because its rest parameter requires no
arguments: `mean`, declared as `fn(x: Any, ...: Any)`, is accepted where `fn(integer[]) -> double`
is expected. The other direction is rejected, because a variadic interface may send any number of
arguments and a fixed-arity function cannot receive them. Between two variadic types, the rest
element types are contravariant like any parameter, and both sides must declare the same number of
parameters before `...`. This rejects some safe pairings, but never admits an unsound one.

The base functions that take a function argument and resolve it with `match.fun` (`lapply`,
`sapply`, `vapply`, `mapply`, `Map`, `Filter`, `Find`, `Position`, `Reduce`, `do.call`, `outer`,
`apply`, `tapply`, `sweep`, `rapply`, `eapply`, `Vectorize`, `Negate`, `aggregate`, and `match.fun`
itself) also accept the function's name as a string. A string literal that names a known function
checks as that function, so `vapply(words, "toupper", numeric(1))` is an error because `toupper`
returns `character`. Any other string, such as `"[["` or a computed name, is `Unknown` and
unchecked. A string reaches a function-typed parameter only at these callees: a project function
that calls its `callback` parameter does not accept `"toupper"`.

When a function value is rejected at a parameter, the finding names the one position that failed
rather than printing both whole signatures: either the parameter to which the interface passes a
value the function will not take, or the function's return, which the interface will not take. An
arity mismatch still shows both signatures.

#### Callback forwarding at variadic call sites

R's apply family calls its callback as `FUN(element, ...)`, forwarding the caller's extra arguments,
so a callback with more formals than the interface declares is still correct when the call forwards
the difference. At a call to a variadic function, a function-typed argument that fails the plain
interface check is therefore checked again, as that forwarded call:

- Forwarded named arguments fill the callback's formals of the same name first, each checked against
  its formal's type exactly as a direct call checks it. So a `logical[]` forwarded to a formal whose
  inferred type is `logical` is accepted, as `show(tab, fade = fade)` would be.
- The interface's own parameter types then fill the remaining formals in order, followed by the
  forwarded positional arguments.
- Any formal left unfilled must have a default.
- The callback's return type must satisfy the interface's return type.
- If the second check fails, it binds nothing, and the reported error is the plain interface
  mismatch.

`lapply(words, gsub, pattern = "a", replacement = "o")` is therefore checked as
`gsub(word, pattern = "a", replacement = "o")` and is `list[character]`, and `lapply(words, nchar)`
accepts `nchar`'s optional formals. A forwarded argument of the wrong type fails the check, and the
call is an error.

Inside a wrapper, a call that forwards its own `...` to a function parameter, as in
`function(func, x, ...) func(unique(x), ...)`, demands only the parameters its other arguments fill,
because the forwarded `...` may be empty. So `dedup(basename, paths)` is accepted even though
`basename` takes a single argument. A call that passes nothing but the forwarded `...`, as in
`function(callback) function(...) callback(...)`, gives the parameter the type `fn(...: Any) -> T`,
which any function satisfies, including one with required parameters such as
`function(path) paste0(path, "/cache")` or `function(endpoint, ...) paste(endpoint, ...)`. An annotation `fn(...: Any) -> T` means the same. R
expands an argument whose value is `...` whatever its name, so `func(x, ... = ...)` forwards the
dots exactly as `func(x, ...)` does.

### Higher-order function types

A function type may appear inside another function type, as in
`fn(transform: fn(integer) -> character) -> character`, and as an expanded `@param` type such as
`@param render_count {fn(integer) -> character}`. A nested function type cannot carry its own
binder, because binders are rank-1.

## Type annotations and assertions

### Checked annotations

`#: TYPE` is a checked annotation: the annotated value must be *compatible* with `TYPE`, so the check
allows widening wherever the rules on this page define it. When the check succeeds, the value is
accepted (through a coercion if one is needed), and the annotated binding or expression has the type
`TYPE` from then on.

#### Inline

```r
value: list[integer] <- list(1L, 2L, 3L)
```

#### Comments

```r
#: list[integer]
value <- list(1L, 2L, 3L)
```

This is valid, because `list{integer, integer, integer}` is compatible with `list[integer]`.

A checked annotation with a nominal type asserts that the value *already* has that type; it does not
create one. `#: Person` on a structural value is a type error, even when the value matches the
representation. Use [`@new`](#nominal-introduction) instead.

### Unknown-only coercions

`#: @if-unknown TYPE` fills a gap in inference. It is allowed only when the inferred type is
`Unknown`, and it then gives the annotated binding or expression the type `TYPE`. When the checker
already knows the type, `@if-unknown` is an error, even if the requested type matches the known one,
so it can never override information the checker has.

Inline, the directive goes between the binding's `:` and its type:

#### Inline

```r
frame <- data.frame(a = 1)

gap: @if-unknown integer <- frame$a   # valid: `frame$a` is `Unknown`

value: @if-unknown integer <- 1L      # an error: the type is already known
```

#### Comments

```r
frame <- data.frame(a = 1)

#: @if-unknown integer
gap <- frame$a   # valid: `frame$a` is `Unknown`

#: @if-unknown integer
value <- 1L      # an error: the type is already known
```

### Trusted coercions

`#: @trust TYPE` is the unchecked override: it treats the annotated value as `TYPE` without requiring
the usual compatibility at that site. It has the same effect as coercing the value to `Any` and then
to `TYPE`, and exists as a shorter way to write that.

#### Inline

```r
callback <- function(x) x

render_count: @trust fn(count: integer) -> character <- callback
```

#### Comments

```r
callback <- function(x) x

#: @trust fn(count: integer) -> character
render_count <- callback
```

A trusted coercion silences a real error as readily as a false one, so use it only when you know
more than the checker does.

### Nominal introduction

`#: @new NOMINAL_TYPE` is the one way to create a value of a nominal type. The annotated value must
be compatible with the nominal type's representation, and when it is, the annotated binding or
expression has the nominal type from then on.

- `NOMINAL_TYPE` must refer to a nominal type declared with `@type`, either by its bare name, such as
  `Person`, or as a generic application, such as `Person<integer>`. An alias, a structural type, a
  union, a function type, or any other type form is not allowed after `@new`.
- A generic nominal may be written unapplied. `@new Person` on a `Person<T>` infers the type
  arguments from the representation check, so a value `list(value = 1L)` becomes a
  `Person<integer>`.
- When the value already has the nominal type, `@new` is allowed and does nothing further.
- The parentheses of `@Name(...)` are the value's own, so they follow the record and tuple literal
  rules: `@Point(x = 1, y = 2)` is a record, `@Pair(1L, "a")` a tuple, and `@UserId(id = 1L,)` a
  one-field record. `@UserId(id = 1L)` is an R assignment wrapped in the constructor, and when the
  representation is a one-field record with that field, the `type-mismatch` suggests the trailing
  comma.
- `@new` is an annotation form, not a type expression, so it cannot appear inside a compact type or
  an expanded function annotation.

Inline, `@Person(value)` introduces the nominal type on any expression, and `x: @new Person <- value`
on a binding:

#### Inline

```r
type Person<T> = list{ value: T }

value <- @Person<integer>(list(value = 1L))
```

#### Comments

```r
#: @type Person<T> {list{ value: T }}

#: @new Person<integer>
value <- list(value = 1L)
```

## Operators

### Operators over union operands

Control-flow joins and mixed containers produce union-typed operands, so every operator below accepts
a union member by member. A union operand is accepted when every member is accepted; one unacceptable
member rejects the whole operand, and the diagnostic shows the full union. The result is the join of
the per-member results, which for a binary operator means the join over every pair of left and right
members.

- `(integer | double) + integer` is `integer | double`.
- `(integer | double) > 0L` is `logical`.
- `(integer | character) + 1L` is a type error, because the `character` member is not numeric.

- `(integer | NULL) + 1L` is `integer`. R's arithmetic and comparison give an empty vector for a
  `NULL` operand rather than failing, so a `NULL` member is accepted and contributes nothing to the
  result, and `(character | NULL) == "a"` is `logical`. A class member dispatches its declared
  operator method the same way, so `(factor | NULL) == "a"` goes through `==.factor`. An operand that is only `NULL`, as in
  `NULL + 1L` or `NULL == 1L`, gives `Unknown`.
- `rec$a` on `list{a: integer} | list{a: character}` is `integer | character`. A member that lacks
  the field changes the result, as [indexing](#indexing) describes.
- A `for` loop over `integer[] | character[]` binds its variable as `integer | character`.

Two arithmetic exceptions keep correlated paths from being reported. A list-shaped member (a list,
record, or tuple without an arithmetic method) beside a numeric member is skipped, because a test
elsewhere in the body usually rules that path out, as in mgcv's `offset` that is a number or a
`list` of terms. A list or `NULL` operand beside an `Unknown` or `Any` operand is not reported
either, because the other operand may be a class whose method accepts it, as ggplot2's `+` does.

#### Conditions

`if`, `while`, and the operands of `&&` and `||` all take a *scalar condition*, and R decides what a
scalar condition admits:

- `logical` is the ordinary case.
- `integer` and `double` are accepted, and coerce as R coerces them: zero is false, and anything else
  is true. That makes `if (length(x))`, `if (nrow(df))`, and `while (n)` ordinary R.
- `complex` and `raw` are type errors, as R refuses them outright.
- A `character` condition of `if` or `while` is accepted unless it is a string literal. R reads it
  with `as.logical`, which accepts the spellings of `TRUE` and `FALSE` (such as `"T"` or `"true"`),
  and the value of `Sys.getenv("FLAG", unset = "TRUE")` presumably is one. Only a literal shows its
  text, so `if ("yes")` is reported and `if ("TRUE")` is not. The same holds for a `character`
  member of a union condition, such as `character | logical`. An operand of `&&` or `||` that is
  `character` is a type error, because R rejects any string there.
- A vector is accepted, because a vector type carries no length, and the vector a test produces,
  such as `x >= 1` on a `double[]`, has length one at run time far more often than not. Only a
  `c()` call with two or more arguments is known to be longer than one, so `if (c(TRUE, FALSE))` is
  a type error, as it is in R.
- A condition whose type is still undetermined becomes `logical`, so `function(flag) if (flag) 1L`
  infers `flag: logical`. A value already required to be numeric keeps that requirement, so
  `function(n) if (n %% 2L) "odd" else "even"` is `<T: numeric> fn(n: T) -> character`. An
  unannotated formal with a default is the exception: an option flag such
  as `function(x, which = FALSE) if (which) ...` is called with `1` as often as with `TRUE`, so the
  condition leaves its type to its other uses. The same holds for `!` on such a formal.
- A union is accepted when every member other than `NULL` is. The `NULL` member is the "not
  supplied" path of an optional value, which code tests only once it holds one, so
  `if (config_flag(pkg))` on a `logical | NULL` is not reported. An undetermined member, such as a
  parameter rebound on one path (`T | logical`), becomes `logical` as a lone one would. A bare `NULL`
  condition is still a type error, as `if (NULL)` is in R.

### Indexing

`[[` extracts a single element, and `[` is R's general subsetting operator. `[` with an out-of-range
position or a missing name gives `NA` at run time, which is a property of the value, not of its type.
`[[` with a missing name gives `NULL` on a list, which the rules below record as `| NULL`; they
record the same for a named vector, where R instead fails at run time.

`$name` behaves like `[["name"]]` on lists, on records, and on opaque nominals, and a backtick-quoted
name follows the same rule. `$` does not work on atomic vectors, because R rejects it on every atomic
vector, named ones included: `c(foo = 1L)$foo` is a type error, while `c(foo = 1L)[["foo"]]` is
`integer`: R stops with "subscript out of bounds" when the name is absent from an atomic vector,
where a list would give `NULL`.

On a nominal whose class declares a `$` method, in a stub or in the project (`$.request` for
`@type request`), `x$name` types as that method's result instead, because R dispatches the read to
the method before it looks at the representation. The same holds for `[.class` and `[[.class`.

When the package's `R/` files, or the file being checked, define any `$` method at all, `$` on an
atomic vector is `Unknown` rather than an error, because a classed atomic vector (an igraph vertex sequence, say) can carry that method under
a class the checker does not track.

Every element of `NULL` is `NULL` in R, so `NULL$name`, `NULL[["name"]]`, and `NULL[1]` are `NULL`.
A list that may be absent is therefore read directly: on `list{retries: integer} | NULL`,
`config$retries` is `integer | NULL`.

On a union, a field may be missing from some of the members. When the members that lack it are
empty lists, the read is that field's type unioned with `NULL`, which is what R answers for the
empty list. Code that builds a list field by field therefore checks:

```r
args <- list()
if (escape) args$escape <- TRUE
args$escape        # logical | NULL
```

When a non-empty member lacks the field, the read is `Unknown`, for the reason a single record-like
list reads a missing name as `Unknown`. A field that *no* member has is still an error when it is a
near miss of a field some member has, and the "did you mean" suggestion draws on every member's
fields.

#### `[[` on vectors

- A scalar-like `T` returns `T`.
- An array-like `T[]` returns `T`.
- A map-like `T[named]` returns `T` for a name index too, because R stops with "subscript out of
  bounds" on an absent name rather than returning `NULL`.

#### `[[` on lists

- A list-like `list[T]` returns `T`. `$name` on it returns `T | NULL`, because such a list may still
  carry names at run time, and R answers `NULL` for a name it lacks.
- A dict-like `list[named: T]` returns `T | NULL` for a name index, and `T` for a positional or
  computed one.
- A tuple-like list returns the element at a literal position. A position that does not exist is an
  error, and a computed position returns the union of the item types.
- A record-like list returns the field at a literal name or literal position, and a computed index
  returns the union of the field types, which is how a call to a function looked up in a list gets
  its type. A position that does not exist is an error.
- A literal name a record-like list lacks reads as `Unknown`, because R lists are open: a list
  literal is often only the start of a value other code adds fields to. A name that is a near miss
  of a field, such as `opts$verbsoe` for `verbose`, is still an error with a "did you mean"
  suggestion. `$` also matches a unique prefix of a field name, as R does, so `opts$verb` reads
  `verbose`.

#### `[` on vectors

The result of `[` on a vector depends on the shape of the index:

- A scalar-like `integer`, `double`, or `character` index gives the scalar element type. That is not
  always exact, since `x[-1]` drops one element and returns the rest, but a scalar coerces into every
  vector position, so the claim can never cause a false error later.
- An array-like or map-like numeric or character index, such as `x[c(1L, 3L)]`, keeps the subject's
  shape.
- A `logical` index of any shape is a mask, as in `x[x > 0]`, and keeps the subject's shape.
- `NULL` selects nothing and gives the array-like vector of the element type.
- An index whose shape is undetermined, such as an unannotated parameter or an `Unknown`, counts as
  scalar-like and is left unconstrained.
- A `complex` or `raw` index is a type error, as is a list, a function, or any other index that is not
  a vector.

Keeping the subject's shape means `E[]` on a scalar-like `E` or an array-like `E[]`, and `E[named]` on
`E[named]`, because `[` keeps names. A character index is allowed on every vector shape, not only a
map-like one, because R returns `NA` rather than failing when the subject has no names, and most
operations erase names.

- `c(1L, 2L, 3L)[2L]` is `integer`.
- `c(1L, 2L, 3L)[c(1L, 3L)]` is `integer[]`.
- `c(a = 1L, b = 2L)[c("a", "b")]` is `integer[named]`.
- `x[list(1)]` is a type error.

#### `[` on lists

`[` slices a list, so a fixed shape does not survive into the result:

- A list-like `list[T]` returns `list[T]`.
- A dict-like `list[named: T]` returns `list[named: T]`.
- A tuple-like list returns `list[T]`, where `T` is the union of the item types, so
  `list(1L, "foo")[1L]` is `list[integer | character]`.
- A record-like list returns `list[named: T]`, where `T` is the union of the field types.
- Slicing the empty list gives `list[NULL]`.

#### Indexing a value whose shape is unknown

`$`, `[[`, and `[` on a value whose shape the checker has not determined, such as an unannotated
parameter, give `Unknown` and leave the value unconstrained. So `function(node) node$value`,
`function(x) x[[1L]]`, and `function(x) x[1L]` report nothing, and neither does indexing with several
indices, as in `function(m, i, j) m[i, j]`. Ordinary R reads fields and slices off values whose shape
nobody wrote down, so refusing here would report correct code. Like access on an opaque nominal, such
an access is an unsupported construct under [strict mode](#strict-mode).

Indexing a `matrix` follows R's `drop` rule. A matrix does not record its element type, so the
elements are `Any`. When both indices are empty or vectors, as in `m[1:2, 1:2]` or `m[, ]`, the result
is a `matrix`; a scalar index drops that dimension, so `m[i, j]` and `m[i, ]` are `Any`; and
`drop = FALSE` keeps the `matrix` whatever the indices are. A single index, `m[i]`, reads elements and
is `Any`.

Any other indexing with several indices, which is data frame selection, or with a named argument, is
not modelled. It gives `Unknown` without a report, so `c(1L, 2L)[1L, 2L]` passes, and strict mode
reports it as an undetermined type. An empty index is
the subject itself, so `x[]` on `list{integer, integer}` is `list{integer, integer}`.

### Arithmetic operators

The arithmetic operators are defined for numeric operands:

- `integer` and `double`;
- `logical`, which R promotes to `integer` before arithmetic, so `TRUE + TRUE` is `2L`;
- `complex`, which makes the result `complex`, so `1i + 2` and `1i / 2L` are `complex`;
- an unannotated value, which is then required to be numeric (see below);
- a class that declares an [operator method](#operator-methods-on-a-class).

The result is scalar-like when both operands are scalar-like, and array-like otherwise, so a map-like
operand gives an array-like result. Unary `-` keeps a scalar-like or array-like operand's shape. The
result's atomic type depends on the operator:

- `+`, `-`, `*`, `%%`, and `%/%` give `integer` when both operands are `integer` (or `logical`), and
  `double` otherwise.
- `/`, `^`, and `**` (R's parser alias for `^`) always give `double`.
- Unary `-` keeps its operand's atomic type. A class with arithmetic methods negates to itself,
  because R dispatches unary `-` through the same methods, so `-(m %*% m)` is a `matrix`.
- R rejects `-NULL`, and so does the checker. A value the body computes that may be `NULL` negates
  as its other members, because code like `if (length(k)) res <- res[-k]` negates only once the
  value exists. A parameter or an annotated variable keeps its `NULL`, so `-x` on a declared
  `x: double | NULL` is reported.

For example, `double * integer[]` is `double[]`, `integer[named] + integer` is `integer[]`,
`2L ^ 3L` is `double`, and `-c(foo = 1L, bar = 2L)` is `integer[]`. Every `%op%` operator other than
`%%` and `%/%` is covered under [operator methods on a class](#operator-methods-on-a-class).

#### Unannotated values in arithmetic

An unannotated value used as an arithmetic operand is *required to be numeric* rather than rejected:
it must end up as `integer` or `double`, in any vector shape, or as a class that declares an
arithmetic operator method.

- `function(x) x + 1L` is `<T: numeric> fn(x: T) -> T`, and calling it with `"oops"` is a type error.
- `function(x) x / 2` is `<T: numeric> fn(x: T) -> double`.
- `function(a, b) a + b` is `<T: numeric> fn(a: T, b: T) -> T`.

When the other operand is a vector, the unannotated operand stays open and the result is a `double`
vector, so `f <- function(x) x + c(1L, 2L)` is `<T: numeric> fn(x: T) -> double[]` and accepts
`f(TRUE)` and `f(c(1, 2))` alike. When the other operand is a union, the unannotated operand is pinned
to a scalar `double`, which matches how R treats bare numbers. An operand whose shape is still unknown
counts as scalar-like here and in comparisons, by the same claim that
[`[` on vectors](#-on-vectors-1) makes. A generic vector written `T[]` is the exception, and its
operator results really are vectors.

A union operand is checked member by member. A union of numeric types, such as `double | integer`,
follows the rules above. A union that also holds an unannotated value or a class with arithmetic
methods, such as `double | matrix` from `if (is.null(previous)) 1 else x %*% x`, requires its
unannotated members to be numeric, and the result is `Unknown`, because R picks the result type per
member at run time. A member that is neither, such as the `character` in `double | character`, is a
type error.

A `logical` argument satisfies the numeric requirement, because R promotes it, so
`cost <- function(price, rate) price * rate` accepts `cost(TRUE, 0.5)` and `cost(1L, 0.5)`. Mixed
arguments widen in R's order, `logical` to `integer` to `double`, so both calls are `double`. A
union of numbers widens to its widest member, so `cost(1L, if (fine) 0.5 else 1L)` is `double` too.
A `matrix` absorbs any number, logical or numeric vector the same way, because R's arithmetic gives a
matrix: with `weigh <- function(a, H) a * H`, both `weigh(2, m)` and `weigh(m, 2)` are `matrix`. A
matrix's element type is not tracked, so a character matrix is absorbed too.

An argument that is itself still generic, such as the parameter `H` in
`outer <- function(H) weigh(2, H)`, is constrained to be numeric rather than pinned to the literal's
`double`, so `outer` is `<T: numeric> fn(H: T) -> double` and accepts a vector or a matrix. The result
keeps the literal's `double`, which is exact for a scalar argument and approximate for a vector or
matrix one. A declared numeric type parameter is accepted the same way.

### Operator methods on a class

When an operand of an operator is a nominal type, the operator first dispatches to the class's
declared operator method, before any numeric rule applies, just as R dispatches `d + 30L` on a `Date`
through `+.Date`.

The lookup follows R's order: first the operator-specific method, such as `+.Date`; then the
operator's S3 group generic, `Arith.Date` for arithmetic and `Compare.Date` for comparison; and
finally `Ops.Date`. Either operand's class may supply the method, the left one first, so `30L + d`
behaves like `d + 30L`. The method name's suffix is the nominal type's name, not R's full class
vector, so a class declared as `@type ggplot` takes `+.ggplot`, even though R registers the method
as `+.gg`.

A method is declared under the name R gives it, in a stub or an annotation, so the result stays
precise for each pairing of operands: subtracting two `Date` values gives a `difftime`, and offsetting
one by a count gives a `Date`. A class that declares an operator but has no candidate that accepts
the operands at hand is a `type-mismatch` error rather than a fall-through to the numeric rules, just
as in R. A class that declares nothing does fall through to the numeric rules, so arithmetic on an
opaque nominal is still a type error. An unannotated operand beside a class operand does not take
the class from the first candidate, because R accepts a plain vector there too. It is only required
to be numeric, so in `function(omega, v) omega + v %*% t(v)`, `omega` is a `T: numeric`, and a call
with two plain vectors is accepted.

A union operand beside a class dispatches member by member, and the result is the union of the
members' results. So the accumulator `total <- if (first) 0 else m %*% m; total + m %*% m` takes
`Arith.matrix` for both `double` and `matrix` and is a `matrix`, while a `character` member is
reported as `` `+` is not defined between `character` and `matrix` ``. A member with no class takes
the ordinary operator rules, so `x >= 0` on `matrix | double` is `logical`. When some member is
rejected that way, or no member is a class, the union is checked by the ordinary operator rules as a
whole.

Your own classes count. A method declared anywhere the global scope reaches, which includes a
package's `R/` sources and a script's own top level, makes its class support that operator exactly as
a shipped stub does. That is also how the class satisfies the numeric requirement: passing a `Money`
to `function(x) x + 1L` is accepted when the project defines `+.Money`, and refused when it defines
no arithmetic method.

R also dispatches on a class that `class(x) <- "string"` sets on a plain list, and no type tracks
that attribute. So when the project defines an arithmetic or `Ops` method for a class that no type
declares, arithmetic with a list operand is left to that method: `result + "text"` on such a list,
and the rest of a chain `result + a + b`, give `Unknown` and report nothing. Without such a method,
`list(a = 1) + 1` is a type error, as it is in R.

`c()` dispatches the same way. A class that declares a `c.Class` method keeps its class through
concatenation, so `c(d1, d2)` on two `Date` values is a `Date`. A nominal with no such method loses
its class but keeps its data, as R's default `c()` does, so two values of `@type Money {double}`
combine to `double[]`. An opaque nominal has no representation, so combining it gives `Unknown`.

`a %op% b` is the call `` `%op%`(a, b) ``. A `%…%` operator that the standard-library stubs declare
is checked and typed as that call, so `"a" %in% valid` is `logical` and `m %*% m` is a `matrix`.
Every other `%…%` operator, including a project's own, gives `Unknown`, because a user operator may
quote its right operand instead of evaluating it, as magrittr's `%>%` does. Using any `%…%` operator
still counts as a read of its name, so a project's own operator is never reported as unused.

### Comparison operators

`<`, `<=`, `>`, `>=`, `==`, and `!=` compare two `logical`, `integer`, `double`, or `character`
operands, mixed freely. R coerces both operands to a common type before comparing, so
`Sys.getenv("RSTUDIO") == 1` and `1L < "a"` are legal R and are not reported. `complex` and `raw`
operands are not supported, so `1i < 2` is a type error. A map-like vector takes part through its
compatibility with an array-like vector. A `NULL` operand, or a `NULL` member of a union, is
accepted, because R answers an empty `logical` vector instead of failing, as
[union operands](#operators-over-union-operands) describe. A list compared with an atomic value
is accepted, because R compares it element by element when each element is a length-one atomic,
so `parts[parts != "null"]` on a parsed list and `lapply(xs, anyDuplicated) > 0` are not reported.
Two lists never compare, so `list(1L) == list(1L)` is a type error, as it is in R.

An unannotated operand is left unconstrained, whatever the other operand is, so
`function(x) x > 0` is `<T> fn(x: T) -> logical` and `function(a, b) a < b` is
`<T, U> fn(a: T, b: U) -> logical`. A comparison against a number is often how R code tests a
string or a flag, so it is not evidence that the operand is numeric. The cost is that a caller's
mistake can pass unreported: with `f <- function(x) x > 0`, `f(function() 1)` is accepted, although
R fails the comparison. Comparing a value whose type is known, as in `1 > function() 1`, is still a
type error.

The result is always `logical`: scalar-like when both operands are scalar-like, and array-like
otherwise. So `1L == 1.5` and `1L < "a"` are `logical`, and `c(TRUE, FALSE) > 0` is `logical[]`.

### Unary `!`

Logical negation coerces its operand exactly as a [scalar condition](#conditions) does, so `!0` is
`TRUE` and `!5` is `FALSE`. Its result is always logical:

- `!logical`, `!integer`, and `!double` are `logical`.
- `!logical[]`, `!integer[]`, and `!double[]` are `logical[]`.
- A map-like operand gives `logical[]`, because negation does not preserve map-likeness.
- A `matrix` or `array` negates to itself, so `!as.matrix(flags)` is a `matrix`, and so does a
  class with a `!` or `Ops` method, which R dispatches `!` to. A `-` or `Arith` method is not
  enough, so `!Sys.Date()` is a type error, as it is in R.
- `!NULL` is `logical[]`, the empty vector R returns, so a value that may be `NULL` negates without
  error: `!x` on `logical | NULL` is `logical[]`.
- An `Any` or `Unknown` operand gives `Unknown`.
- An operand whose type is still undetermined is constrained to `logical`, and the result is
  `logical`, except for an unannotated formal with a default, which stays open as it does in a
  [condition](#conditions).
- A union negates when each member does, and an undetermined member counts as one that does. An
  unannotated parameter shaped by an `is.null()` test has such a type, so after
  `if (is.null(read)) read <- !write` the `!write` is not an error.
- Any other operand is a type error.

### Range operator `:`

`from:to` builds a numeric sequence. Each endpoint may be an `integer`, a `double`, or a `logical`,
which R takes as a number, or a union of those. A vector endpoint is accepted too, because R uses its
first element and a vector type carries no length; only a `c()` call with two or more arguments is
known to be too long, so `1:c(1L, 2L)` is a type error, and so is a non-numeric endpoint. The
result is `integer[]` when both endpoints are `integer` or `logical`, and `double[]` when either
may be `double`, so `1:TRUE` is `integer[]` and `1:n` on `n` of type `integer | double` is
`double[]`. A whole-number `double` literal such as `1` or `10`
counts as `integer` here, matching what R does at run time, so `1:10` is `integer[]` and `1.5:3L` is
`double[]`.

R rejects a `NULL` endpoint, and so does the checker, except for an endpoint read through a `$`
field of a value the body computed (`b$off[i]`, with `b` returned by a call). Such a field is
typically filled under a flag, as in mgcv's `off`, and read only by callers that set the flag, so
its `NULL` member is dropped. A local, a value indexed directly, and a field of a parameter keep
their `NULL`, so `cfg$off:3L` on a parameter `cfg: list{off: integer | NULL}` is reported.

Base R's `seq(from, to)` without `by` or `length.out` returns `from:to`, so it follows the same
rule: `seq(1, 10)` is `integer[]`, and so is `seq(n)` with one argument, while `seq(0.5, 3)` and
`seq(1, 10, by = 2)` are `double[]`. A project that defines its own `seq` gets its own typing.

An unannotated operand, as in `1:n`, is required to be a scalar `integer` or `double`. Passing a
numeric vector through the enclosing function is therefore a type error at the call, because R's
warning about truncating the endpoint marks a bug. The result is `double[]`, because the endpoint may
turn out to be a `double`.

### Combine `c(...)`

`c(...)` builds a vector from arguments of any shape:

- With no arguments, `c()` is `NULL`, as in R.
- `NULL` arguments are dropped, as in R, so `c(x, NULL)` is `c(x)` and `c(NULL)` is `NULL`.
- A union-typed argument takes part member by member. Its `NULL` members are dropped first, and every
  remaining member joins the coercion like a separate argument. So with `acc` of type
  `double[] | NULL`, `c(acc, 1.0)` is `double[]`, and `c(if (a) list(1), if (a) list(2))` is
  `list[double]`.
- When any argument is a list, `c` concatenates into a list-like `list[T]` whose element type is the
  join of every argument's elements, with an atomic argument contributing its own type:
  `c(list(1L), "a")` is `list[integer | character]`. The atomic rules below apply only when no
  argument is a list.
- An argument whose element type is not known statically, such as `Any`, `Unknown`, an unannotated
  parameter, or a union or vector that holds one (`T | NULL`, `T[]`), is tolerated, and the whole
  result is `Unknown`, because a concrete element type could
  be widened by a later argument. So `function(x) c(x, 1L)` is `<T> fn(x: T) -> Unknown`. Under
  strict mode, an unannotated parameter makes the `c()` call the origin, an `Unknown` argument was
  already reported where it arose, and an `Any` argument is not reported.
- Mixed atomic arguments coerce to the widest type in R's order,
  `logical < integer < double < complex < character`.
- `c()` never reports an argument, because R's `c()` accepts every value. An argument the order
  does not cover, such as a function or a `raw` beside another atomic type, makes the result
  `Unknown`, so `c(as.raw(1L), 2L)` and `c(function() 1, 2)` are `Unknown`.
- When every argument is named, the result is a map-like `T[named]`; otherwise it is an array-like
  `T[]`.

For example, `c(TRUE, 1L)` and `c(1L, NA)` are `integer[]`, `c(1L, "a")` is `character[]`, and
`c(foo = 1L, bar = 2L)` is `integer[named]`.

### Assignment operator `<-`

`name <- expr` writes the type of `expr` into the variable slot for `name` in the current scope,
creating the slot on the first write (see [value names](#value-names) for the slot model). The
assignment expression itself has the type of `expr`, so `y <- (x <- 1L)` gives both `x` and `y` the
type `integer`. When the assignment carries an annotation, `expr` is checked by the annotation rules.

- A string in place of the name binds that name: `"x" <- 1` is `x <- 1`, and so is `` `x` <- 1 ``.
  For a string target, the range of any finding is the literal, quotes included.
- A target that is not a name, such as a computed value or a number, is reported as a
  `syntax-error`, because R refuses it at run time. A target headed by `!` is exempt, because `!`
  binds tighter than `<-`, so rlang's `expr(!!name <- value)` builds an assignment instead of
  performing one.
- A later assignment in the same scope writes the same variable. On a straight-line path the new
  write replaces the old type, and writes that arrive from different paths are joined (see
  [control-flow joins](#control-flow-joins)). So after `x <- 1L; x <- "foo"`, `x` is `character`, and
  after `x <- 1L; if (flag) x <- "foo"`, it is `integer | character`.
- `x <<- v` writes the nearest enclosing frame that defines `x`, or the global environment. When
  an enclosing function defines `x`, the rest of the writing function reads `x` as `v`, and that
  function joins `v` with its own writes, because a closure may run at any time after it is created. A write whose type is still
  undetermined, such as a callback's result, joins as a union member instead of binding the other
  writes, so a reset `cache <<- TRUE` beside `cache <<- fun()` leaves `fun` generic. A write to a
  top-level variable is read back in the rest of the writing body: after `cache <- 1L`, the body
  `cache <<- "a"; cache` reads `cache` as `character`. A write on one path joins with the
  top-level binding, so `if (flag) cache <<- "a"; cache` reads `integer | character`, except
  that a top-level `NULL` is a placeholder the write fills and does not join. Other items still
  read the top-level binding, and so does the enclosing body of a nested function that writes it.
- A closure may run many times, so on entry an enclosing variable that may still be `NULL` holds
  either that or what the closure's own first `<<-` writes. The lazily filled cache
  `if (is.null(cached)) cached <<- dir("css"); cached` therefore reads as `character[]`. A read
  before that first write already fixes the type, so a first write of another type is an error:
  after `y <- if (is.null(x)) 0 else x + 1`, the write `x <<- "a"` is reported.

#### Recursion

A function can call itself, because its own name is visible inside its body.
`fact <- function(k) if (k <= 1L) 1L else k * fact(k - 1L)` is `fn(k: integer) -> integer`, and a
call that violates the recursively inferred signature is an error. The recursive uses share one
instantiation, so there is no polymorphic recursion.

Two local functions that call each other are beyond this, because names are bound one at a time. The
forward reference still resolves, since a closure sees later writes to its frame, but it stays
`Unknown`.

At a package's top level, a self-recursive definition and a group of mutually recursive definitions
are both re-derived until their types stop changing, starting from `Unknown`. Simple recursion
converges to its precise type: a top-level `fact` exports `fn(n: integer) -> integer`, and the pair
`is_even` and `is_odd` exports `<T: numeric> fn(n: T) -> logical`.

A self-reference whose type would grow without bound cannot converge without recursive types. A tree
fold is one: its parameter would need `T = double | list[T]`, so such a group settles at `Unknown`. A
cycle can also converge with an `Unknown` inside it, and a pure self-call such as
`f <- function() f()` settles at `fn() -> Unknown`. Either way, strict mode reports it, and an
explicit annotation on the binding closes the cycle exactly.

### Boolean operators `&&` and `||`

Both operands are [scalar conditions](#conditions), and the result is a scalar `logical`. As in a
condition, a vector operand is accepted unless it is a `c()` call with two or more arguments, so
`v && TRUE` on a `logical[]` passes, while `c(TRUE, FALSE) && TRUE` and `TRUE || c(FALSE, TRUE)` are
type errors.

### Elementwise operators `&` and `|`

Each operand is a `logical`, `integer`, or `double` scalar or vector, and the result is `logical`.
It is a scalar when both operands are scalars, and `logical[]` otherwise, so `a > 0 & b > 0` on two
`double[]` parameters is `logical[]`. An operand whose type is `Any` makes the result `Any`, and
one whose type is `Unknown` makes it `Unknown`, which strict mode reports where the operand's type
was lost. An operand with no type yet, such as an unannotated parameter, could be a scalar or a
vector, so the operator gives `Unknown` and strict mode reports it; annotate the parameter.

### Formula operator `~`

A formula, one-sided (`~ x`) or two-sided (`y ~ x + z`), is the nominal type `formula`. Its operands
name model variables, which are usually columns of a data frame rather than bindings in scope, so
they are not checked: `y ~ undefined_name + "text"` reports nothing. Annotate a formula variable or
parameter as `formula`.

## Calls

### Function calls

A call evaluates to its callee's return type. When the callee expression or its return type is
`Unknown`, the call is `Unknown`. When the callee is a union whose members are all function types,
the call must be valid against every member, since the value could be any of them, and it evaluates
to the union of the members' return types. No member's argument bindings leak into another's.
Calling a function looked up in a list, as in `handlers[[name]](...)`, has this shape, and so does
a variable that holds such a lookup, as `handler <- handlers[[name]]` does.

A union of functions that take different parameters but is not a lookup usually comes from code
that picks a function by an argument value, as rlang's `compat("warn")` returns a one-message shim
while `compat("is_interactive")` returns a function of no arguments. A call through such a value
presumes a member that accepts it, so it is reported only when no member does. When some members
accept the call and others do not, the call is `Unknown`.

A callee whose union joins functions with plain values, such as `(fn(id: T) -> character) | character`,
comes from a function whose result kind depends on an argument, as `prefixer(namespace)` below
returns its inner function exactly when `id` is missing. The call presumes the function: it is
checked against the function members only and is `Unknown`. A union of functions and `NULL` alone
is different and is reported, as [called names](#called-names) describes.

```r
prefixer <- function(namespace, id) {
  f <- function(id) paste(namespace, id, sep = "-")
  if (missing(id)) f else f(id)
}
scoped <- function(namespace, name) prefixer(namespace)(name)
```

An argument that names a variable the body assigns without an annotation drops its `NULL` member
when the parameter's type admits no `NULL`. The `NULL` there comes from a `switch` without a default,
an `if` without `else`, or a helper that returns `NULL` on some path, and the code presumably does
not reach the call on that path. A `switch()` without a default written directly as the argument
is treated the same way, as in Matrix's `new(switch(shape, g = "dgeMatrix", t = "dtrMatrix"))`. So `type <- switch(type, logical = "a logical %s", integer =
"an integer %s")` followed by `sprintf(type, kind)` is clean. A parameter the body does not
reassign, and a variable whose assignment is annotated, keep their `NULL`, so passing a
`name: character | NULL` parameter on to a `character` parameter is still reported. The `NULL` of
an unannotated parameter is a placeholder of the same kind, whether it comes from a `NULL` default
or from an `is.null()` test: in `function(H = NULL, Z) { ...; if (quadratic) scale_by(Z, H) }`, where
`quadratic` was set from an `is.null(H)` test, `H` passes to a numeric parameter without its `NULL`.

Length works the same way. A variable the body computes as `character | character[]`, because a
helper returns a vector on some path, passes to a parameter that takes one `character` as that one
string, so `pattern <- format_message("^%s=", name)` followed by `sub(pattern, "", spec)` is clean.
Only such a union qualifies: a variable known to hold a vector, as `flags <- c(TRUE, FALSE)` does,
is still reported at a `logical` parameter, and so is a declared vector.

A call is a type error when a required argument is missing, when it passes too many arguments to a
callee without a rest parameter, or when an argument is incompatible with its parameter's type. The
[named and positional parameter rules](#named-and-positional-parameters) apply throughout. A missing
named argument is reported by name, as in "this call leaves out `y`, which the function requires",
and too many arguments are counted as the positional arguments against the
positional slots that named arguments left open.

#### Matching arguments to parameters

Arguments are matched in R's order, and names compare case-sensitively:

1. Every argument given by name claims the parameter of exactly that name, before any positional
   argument is placed.
2. A remaining named argument claims a parameter declared before the rest parameter whose name it
   is a prefix of, when exactly one unclaimed parameter has that prefix. So
   `list.files(".", full = TRUE)` sets `full.names`. Parameters after the rest parameter match only
   exactly, as in R.
3. The positional arguments then fill what is left: first the fixed positional parameters, then the
   unclaimed named parameters declared before the rest parameter, in declaration order. When the
   function is not variadic, they fill all the unclaimed named parameters.
4. The rest parameter absorbs whatever remains, positional or named.

So in `vapply(xs, character(1), FUN = f)`, the named `FUN` is claimed first, and `character(1)`
reaches `FUN.VALUE`, exactly as R matches it. In `lapply(1:2, fmt, x = data)` the lowercase `x`
does not match `lapply`'s `X`, so it goes to the rest parameter and is forwarded to `fmt`.

A rest parameter follows R's rules for the formals around the dots:

- It adds no required arguments, so `paste()` is legal.
- Positional arguments fill the parameters declared before it first, so `wrap("a", "b")` on
  `fn(x: character, ...: character)` gives `x = "a"` and sends `"b"` to the rest.
- It then absorbs any number of remaining positional arguments, each checked against its element
  type.
- A parameter declared after it can only be matched by name, so `sum(1, 2, na.rm = TRUE)` on
  `fn(...: integer[] | logical[], [na.rm]: logical)` sends `1` and `2` to the rest and `na.rm` by
  name.
- It also absorbs a named argument that matches no declared parameter, as in
  `read.csv(file, colClasses = "character")`.
- A named argument that duplicates a parameter already given is still an error, because R rejects a
  formal matched twice.

When an argument is the enclosing function's bare `...`, as in a wrapper
`function(x, ...) helper(x, ...)`, it forwards an unknown number of arguments, possibly none. Such a
call skips both arity checks, and the `...` argument itself matches no parameter. The call's other
arguments are still checked as usual.

#### Argument compatibility

Arguments are checked for compatibility, not exact equality:

- The ordinary coercions apply at parameter positions, including a scalar-like `T` into an
  array-like `T[]`, and `T` or `NULL` into `T | NULL`.
- The promotion order from [vector coercions](#vector-coercions) applies, so `mean(1L)`,
  `sd(c(1L, 2L))`, and `sum(x > threshold)` are not errors.
- A type parameter that several parameters share, directly as `T` or as the items of `list[T]` or
  `List<T>`, takes the join of what the arguments pass, whatever their order. Tags join to their
  union, so with `light: :Red | :Green`, `Bool.is_eq(:Red, light)` checks just as
  `Bool.is_eq(light, :Red)` does, and `pick(:Red, :Green)` on `<T> fn(a: T, b: T) -> T` is
  `:Red | :Green`. Numbers join in R's promotion order, so `Num.add(1L, 2.5)` and
  `List.concat(list(1L), list(2.5))` are `double` and `list[double]`. Any other mix is a type
  error, as in `Bool.is_eq(1L, "one")`, and every argument, a callback's parameters included, is
  then checked against the joined type, so `fn(f: fn(T) -> logical, a: T, b: T)` rejects a
  callback that accepts only `:Red` when `a` and `b` are `:Red` and `:Green`.
- A whole-number `double` literal counts as `integer` at a parameter, as it does at the endpoints of
  `:`, so for `fn(n: integer)`, `f(10)` is as valid as `f(10L)`. A fractional literal such as `2.5`
  is still rejected, and so is a `double` variable that happens to hold a whole number. `-3` is unary
  minus applied to a literal, not a literal, so `f(-3)` is rejected too.
- An argument whose type is `Unknown` is accepted at any parameter, because whatever made the value
  `Unknown` was already diagnosed where it happened.
- A `character` argument is accepted at a parameter of function type, because R's functional
  helpers resolve a function's name with `match.fun`, which makes `lapply(calls, "[[", "call")` and
  `apply(m, 1, "mean")` idiomatic. At the base helpers that call `match.fun`, such as `lapply`,
  `sapply`, `vapply`, `Map`, `Filter`, `Reduce`, `do.call`, and `apply`, a string literal that names a
  known function is checked as that function, so `lapply(list(1, 2), "sqrt")` is `list[double]`.
  Any other string is accepted unchecked. `match.fun` also looks a bare name up as a function, past
  a binding that holds something else, so after a mocking placeholder such as `nchar <- NULL`,
  `vapply(words, nchar, integer(1))` calls the library's `nchar`. A name the library does not
  export is still checked as the value it holds.
- At a parameter of type `T | NULL` with `T` still open, which is what a callee that tests
  `is.null(x)` infers, `T` binds to the argument's non-`NULL` part. Passing a value there says that
  the callee tolerates `NULL`, not that the caller's value may be `NULL`, so with
  `check <- function(x, allow_null = FALSE) if (allow_null && is.null(x)) ...`, a caller that runs
  `check(thing)` and then reads `thing$field` keeps `thing` open.
- A scalar parameter type that ry inferred from an unannotated body records how the body uses the
  value, not a length, because a vector type carries none. Such a parameter accepts a vector of the
  same atomic type, so `rlength <- function(x) if (all(!x)) length(x) else min(which(x)) - 1L`
  accepts `flags > 0`. An inferred `logical` parameter also accepts an `integer` or a `double`,
  scalar or vector, because that claim comes from a condition or `!`, which coerce numbers, so
  `skip <- function(line.id) if (!line.id) 0L else 1L` accepts `skip(0L)`. An inferred `integer`
  slot also accepts a `double`, because R's integer-taking functions truncate one: a callback
  shape that a first call `col.fun(n = length(levels))` pinned to `integer` accepts
  `col.fun(n = length(levels) + 1)`. An annotated signature
  keeps its scalars: under `#: fn(flag: logical) -> double`, `pick(c(1, 0, 2) > 0)` is a type
  error. A type parameter bound by an earlier argument still widens as usual, and an inferred
  `character` parameter still rejects a number. The same holds for an element that the apply family
  passes to an inferred callback, so `lapply(0:3, not)` over `not <- function(value) if (value)
  FALSE else TRUE` is `list[logical]`, and `lapply(c("a", "b"), not)` is still reported.
- An inferred `logical` parameter that the body reads only as the whole condition of an `if` or a
  `while` accepts a `character` argument the way that condition does: a string literal only when it
  spells `TRUE` or `FALSE`, and any non-literal string. So `not(Sys.getenv("CHECK", unset =
  "TRUE"))` and `not("TRUE")` are accepted, and `not("yes")` is reported. A parameter that `!`,
  `&&` or `||` reads gets no such leniency, because R rejects any string there, so `neg("TRUE")`
  over `neg <- function(x) !x` is reported.
- At a base helper that calls `match.fun`, a bare unannotated formal that the body also reads as a
  value (as an operand, a condition, or an assigned value) is not inferred as a function there,
  because `match.fun` takes a function or its name and looks a bare name up as a function. So
  `spread <- function(x, var = 1) { co <- apply(x, 2, var); if (var < 10^-3) stop(); co }` calls
  base `var` and compares the number, and `lapply(chunks, op, n)` beside `op == "tail"` accepts a
  string `op`. A formal used only as a function, as in `each <- function(f) lapply(list(1, 2), f)`,
  still infers as `fn(double) -> T`.
- An argument bound to a formal that the callee reads only through `substitute()` is code the callee captures, not a value, so it is not typed in the caller's frame.
  withr's `wrap <- function(f, pre) { pre <- substitute(pre); ... }` splices `pre` into a function
  that takes `f`'s formals, so `wrap(sink_to, { if (append) "a" else "w" })` reads `sink_to`'s
  `append`, not base's `append`. A callee that also evaluates the formal checks the argument as usual,
  and so does one that passes the formal on to another function, which may evaluate it.

#### The native pipe

R's parser rewrites `x |> f(y)` into `f(x, y)` before anything runs, so the pipe types exactly like
that call. The piped value becomes the first positional argument, and every call rule applies to it:
arity, argument compatibility, and overload selection. A chain composes from left to right, and a
type error in the piped value is reported on the left-hand expression.

The `_` placeholder follows R's rule: it is legal only as the entire value of exactly one named
argument, which then receives the piped value instead of the first positional slot. So
`x |> lm(y ~ z, data = _)` is `lm(y ~ z, data = x)`, and `2 |> f(tag = _)` supplies only `tag`.

A pipe that R itself would reject is not guessed at. That covers a right-hand side that is not a
call, a positional or repeated `_`, and a `_` nested inside a subexpression. Such a pipe types as a
silent `Unknown`, and its reads are not reported.

### Overload sets

A standard-library stub may declare several signatures for one name, forming an ordered overload
set ([authoring stubs](/development/authoring-stubs.md#overloads-and-generics) describes how). A call
to such a name is resolved separately at each call site:

- Candidates are tried in declaration order, and the call commits to the first one whose parameters
  accept the arguments. That candidate's return type is the call's type, so `sum(1L, 2L)` is
  `integer` and `sum(1.5, 2.5)` is `double`. Nothing a failed candidate bound leaks into the next
  candidate or into the result.
- A candidate that leaves the caller's undetermined types as they were beats one that constrains
  them, whatever the declaration order. A wrapper like `function(x) cumsum(x)` therefore keeps its
  parameter open, because `cumsum`'s `Any` fallback accepts it without constraining anything. Strict
  mode reports a call that resolves to such a fallback. When only one candidate fits, it is selected
  and whatever it determines stands.
- When several candidates fit only by narrowing the caller's undetermined types, the call keeps that
  narrowing only if they all narrow the same way. Otherwise the type becomes `Unknown`, and so does
  the call: `function(xs) lapply(xs, f)` infers `fn(xs: Unknown) -> Unknown`, because `lapply`'s
  candidates for a named list and for a vector return different shapes. One disagreement is
  settled instead: when one candidate narrows to a scalar such as `character` and the others to
  that atom's vector, which accepts the scalar, the scalar wins. `grepl` also takes a vector
  `pattern`, yet `function(p, x) grepl(p, x)` infers `p: character`.
- The exception is a set that preserves its argument. `Filter`, `head` and `unique` declare one
  candidate per shape, and each returns exactly the shape it accepted. When every fitting candidate
  other than an all-`Any` catch-all returns what it narrowed the same undetermined type to, the call
  returns that type unchanged and leaves it undetermined. So `function(xs) Filter(f, xs)` is
  `<T> fn(xs: T) -> T`, and passing it a `data.frame` gives back a `data.frame`. The same holds for a
  declared `<T>`, so that signature can be written back as an annotation. A record passed through
  such a function keeps its record type although `Filter` or `head` may drop fields; that misses an
  error rather than reporting a false one.
- A function literal among the arguments does not belong to the caller, so narrowing its
  parameters is no guess: that is how `lapply(xs, function(v) v + 1L)` gives `v` a type. When the
  parameter is a function type with a `...: Any` rest, such as plumber's `handler: fn(...: Any) ->
  Any`, the literal's formals past the declared ones are `Any`, so `function(req) req$postBody` reads
  `req` without a strict finding.
- An argument whose type is not known statically fits every candidate, so the call does not guess
  among candidates whose results differ, and it is `Unknown`. So
  `function(w) sort(unique(unlist(w)))` is `<T> fn(w: T) -> Unknown` rather than taking `sort`'s
  `factor` candidate. A catch-all candidate, one whose results are all `Any`, is left out of that
  comparison when a more specific candidate fits and every unknown argument lands on a parameter
  that accepts any value there, because then the known arguments chose the candidate. So with `n`
  unknown, `rep(0, n)` is `double[]`, since `n` is `rep`'s `times: Any`, while `rep(x, 2)` with `x`
  unknown stays `Unknown`, since `x` is what `rep`'s vector candidate and its fallback differ on.
- The [whole-number literal rule](#argument-compatibility) does not influence which candidate is
  selected. Candidates are first tried against the arguments' true types, so `sum(1, 2)` selects the
  `double` candidate, matching what R computes. Only if no candidate accepts them is the set tried
  again with literals allowed as integers.
- When no candidate accepts the arguments, the call is a type error. Normally the error names the
  overloaded callee and how many signatures were tried, and gives the first candidate's failure as a
  hint. One candidate's own finding is reported instead, at its own argument range, when every
  candidate rejects the call for the same reason, or when one candidate got strictly further into the
  argument list than all the others.
- Passing an overloaded name as a value, or hovering over it, sees the *last* declaration, which by
  convention is the most general. Go-to-definition jumps to the *first* declaration.
- The exception is an overloaded name passed by name to `lapply`, `sapply`, `vapply` or `Reduce`.
  There the set is resolved once per element type, as R calls it once per element, so
  `lapply(list(units = c(1L, 2L)), sum)` is `list[named: integer]` and `sapply(list(a = 1L), sum)`
  is `integer[named]`. Each field of a record or frame is its own element type, and an element no
  candidate accepts is an error. A class whose first argument declares a `sum.<class>` or
  `Summary.<class>` method is dispatched to that method instead of the set, as R dispatches it.
- `Reduce` with a function named directly, or chosen by an `if` between two names, folds that
  function over the elements instead of matching it against `fn(U, T) -> U`. R hands each return
  back as the next accumulator, so the accumulator's type is the join of the start (`init`, or the
  element type) and every return. With `same <- function(x, y) if (identical(x, y)) x`,
  `Reduce(same, list(1, 2))` is `double | NULL`. A step the function rejects is an error at that
  argument, so `Reduce(add, list(1, 2), "start")` with a numeric `add` is reported at `"start"`. A
  function that closes over the enclosing function's own type variables, `right =`, `accumulate =`
  and `simplify =` keep the stub's signature.
- A function whose body ends in `Reduce(f, x, init = init)` over its own formals folds the same way
  at its call sites. This covers a purrr-style wrapper whose `f` is a local
  `function(a, b) .f(a, b, ...)`. With `reduce <- function(.x, .f, ..., .init)` written that way,
  `reduce(sizes, .init = list(0), function(output, input) c(output, list(input)))` folds the callback
  from `list(0)` instead of pinning the accumulator to the start's type, and
  `reduce(list(1L, 2L), function(total, item) total + item, .init = "zero")` is reported at
  `"zero"`. A wrapper with an early `return`, or a call that also passes arguments on through the
  wrapper's `...`, keeps its ordinary signature.

Only a declaration file can overload a name, because a name with several signatures has no single
most general type and must be resolved by search rather than inferred. A `#:` annotation on your own
function declares exactly one signature; to make one name accept several shapes, give the parameter
a [union type](#union-types), or split the shapes into separate functions.

A local or package binding that shadows a stub name switches its overload set off, and the binding is
used everywhere, calls included. A project override stub may declare overload sets, because a
`.Rtypes` file is a declaration file wherever it lives.

## Control flow

### `if` expressions

#### `if` without `else`

An `if` without `else` takes a [scalar condition](#conditions). If the branch has type `T`, the whole
expression is `T | NULL`, because the missing branch contributes `NULL`. Union normalization applies,
so a `NULL` body stays `NULL`, a nullable body stays a single `T | NULL`, and an `Unknown` body stays
`Unknown`.

#### `if ... else`

An `if ... else` takes a [scalar condition](#conditions) and joins the types of its two branches. The
join does not merge or coerce branch types beyond unification; it records the alternatives:

- Branches that unify share that type. `if (flag) 1L else 2L` is `integer`, and `if (cond) a else b`
  over two unconstrained values keeps them unified as one polymorphic type.
- A `NULL` branch joins by union without constraining the other branch, so `if (flag) NULL else 2L`
  is `integer | NULL`.
- Branches with genuinely different types give their union: `if (flag) 1L else "foo"` is
  `integer | character`, not a type error.
- A branch whose type is still undetermined is never pinned by the other branch.
  `function(flag, x) if (flag) x else "s"` is `<T> fn(flag: logical, [x]: T) -> T | character`, not
  `fn(flag: logical, x: character)`, because unifying would make a caller wrong because of a line
  that is not wrong. A variable that only carries a bound such as `numeric` is not pinned by a
  branch that is not a plain vector either, so in
  `if (is.null(L)) rho + rho0 else L %*% rho + rho0` the result is `T | matrix`, not a `rho` that
  must be a matrix. The same holds for a variable nested inside a branch, so
  `if (identical(dp, FALSE)) list(character(), character()) else list(dp, dp)` is
  `list{character[], character[]} | list{T, T}`.
- A branch whose variable the body has already constrained may unify with the other branch, because
  that adds nothing the program did not already require. That is how the recursive `fact` above
  converges to `fn(n: integer) -> integer`.
- Two branches that are both still open are tied to each other.
  `function(value, fallback) if (is.null(value)) fallback else value` is
  `<T> fn(value: T | NULL, [fallback]: T) -> T`.
- An `Unknown` branch makes the whole conditional `Unknown`.
- An `if` whose value is discarded, such as a statement in the middle of a block, does not join its
  branches at all, so a branch that only has a side effect never ties its types to the other
  branch's.

#### Diverging branches

A branch *diverges* when it never falls through to the code after the `if`: `return(...)`,
`stop(...)`, `break`, or `next`, a block ending in one of those, or an `if ... else` whose branches
both diverge. The `else` of an `exists("name")` test counts as diverging when `name` is a function
that a stub of an attached package types and the project does not define, because that fallback
exists only for older versions: `if (exists("emptyenv")) emptyenv() else NULL` is `environment`.
A probe for a name no stub types keeps both branches. A diverging branch contributes neither its value nor the state of its variables, so
`x <- if (c) return(NULL) else 5` gives `x` the type `double`, and a variable written inside a
diverging branch does not join into the state after the `if`.

A call that never returns has no bottom type of its own. A `stop(...)` call types as `Any`, which
fits every context and which strict mode does not report, so `function() stop("no")` is
`fn() -> Any`. `stop(...)` is recognized by its bare name, as `local` and `return` are, so
rebinding `stop` is not modelled.

### Guard narrowing

A condition that applies a type-guard predicate to a plain local variable refines that variable's
type along each edge of the `if`. Inside each branch, the variable keeps the refined type until a
write replaces it, and the refinements merge back at the join exactly as branch writes do. A
branch the guard does not refine holds the value from before the test, so `if (!is.null(x)) ...` on
an untyped `x` leaves `x` untyped after the `if`, not `NULL`. With `x`
a local variable or parameter, or an assignment to a local written inside the test
(`is.integer(limit <- check_limit(limit))`, which narrows `limit`), the recognized guards are:

- `is.null(x)` makes `x` a `NULL` in the true branch, and removes `NULL` from its union in the false
  branch.
- `is.character(x)`, `is.logical(x)`, `is.integer(x)`, `is.double(x)`, `is.function(x)`, and
  `is.list(x)` keep only the members of that family in the true branch, and remove them in the false
  branch. `is.numeric(x)` does the same for the `integer` and `double` family, and `isTRUE(x)` and
  `isFALSE(x)` narrow like `is.logical(x)`. That is deliberately loose in the false branch, which
  also drops the logical member: code like car's `if (isFALSE(fit)) 0 else fit$m` returns `FALSE`
  only to signal failure, so the other branch reads the non-logical members.
- `is.null(x$field)` removes from `x`'s union, in the false branch, each member that cannot carry
  the field: `NULL`, the empty `list()` placeholder, and a record with no field the name partially
  matches. The true branch keeps every member, because the field itself may hold `NULL`. So
  `url <- list()`, a loop that fills `url`, and then `if (is.null(url$scheme)) stop(...)` leave
  `url` as the filled record.
- `length(x)` as a condition, or `length(x)` compared with a numeric literal, removes `NULL` from `x`'s union
  in whichever branch a length of zero cannot reach. So after
  `if (length(range) != 2) return(0L)`, `range` is no longer `NULL`, and `if (length(range))` or
  `if (0 < length(range))` drops it in the true branch. `length(range) < 3` admits zero and refines
  nothing.
- `!cond` swaps the two branches.

Combined with a [diverging branch](#diverging-branches), the surviving edge's refinement persists
after the `if`, which is the idiomatic early-exit guard:

#### Inline

```r
f <- function(x: integer | NULL) -> integer {
  if (is.null(x)) {
    return(0L)
  }
  x + 1L   # x : integer here
}
```

#### Comments

```r
#: fn(x: integer | NULL) -> integer
f <- function(x) {
  if (is.null(x)) {
    return(0L)
  }
  x + 1L   # x : integer here
}
```

The details:

- A family test covers both the scalar and the vector of that atomic type, so `is.character` is true
  for `character` and `character[]`. `is.list` covers every list shape, and `is.function` covers
  function types.
- Narrowing filters union members. A member whose family cannot be decided statically, such as an
  unannotated value or an opaque nominal, is kept on both edges.
- An unannotated parameter whose runtime type the body inspects is `Unknown`, because code that
  inspects a type uses the value as a different type on each branch, so no one type describes it.
  The inspections are `typeof()`, `class()`, `mode()`, `storage.mode()`, `inherits()`,
  `is.object()`, `oldClass()`, the `is.*` family tests, such as `is.character()`, and rlang's
  type predicates, such as `is_string()`, `is_function()`, `is_formula()`, `is_bare_list()` and
  `is_scalar_integer()`. These count by name, whatever the name refers to, since packages vendor
  rlang's standalone files and define the predicates themselves. So
  `function(x) if (is.character(x)) x else "other"` is `fn(x: Unknown) -> Unknown`. `is.null()`,
  `is.na()`, and `is.finite()` test a value rather than its type, so they keep the parameter typed,
  and an annotated parameter still narrows.
- `is.null(x)` on an `Any` or `Unknown` variable refines the true edge to `NULL`, because the runtime
  guarantees it. A family guard does not refine `Any` or `Unknown`, because inventing a concrete shape
  there would cause reports on standard-library functions that declare a scalar result for a value of
  any length.
- `is.null(x)` on a value with no constraints yet, such as an unused unannotated parameter, *shapes*
  it: the test asserts that `NULL` is possible, so the variable becomes `T | NULL` for a fresh `T`, and
  the edges narrow as for an ordinary union. That is how the `value`/`fallback` function under
  [`if ... else`](#if--else) types without annotation. Testing a parameter for `NULL` and then
  passing it unguarded to a parameter that excludes `NULL` is therefore a genuine finding, although
  arithmetic and comparison on it are accepted, as [union operands](#operators-over-union-operands)
  describe. The shaping never fires on a variable that already
  carries a constraint, or on a declared rigid type parameter.
- When a guard cannot fire, such as `is.null(x)` on a union with no `NULL` member, nothing is refined.
  Dead branches get no special typing.
- Only a read of a variable narrows: a parameter, a function local, or a top-level variable assigned
  by an earlier statement. `is.null(f(x))` and `is.null(x$field)` do not narrow.
- A refinement does not outlive the top-level statement it was made in. Inside a function body, or
  one braced top-level block, `if (is.null(x)) stop(...)` narrows `x` for the rest of the body,
  because the guard and the later reads are one statement. Written as bare top-level statements, the
  guard and the read after it are two statements, and the read is not narrowed.
- A read from inside a closure narrows when the guard is in the same statement, just as a local
  does. The guard's own subject must not itself be a deferred read: that body runs later, so the test
  proves nothing about the value it will see then.
- Guards compose across `&&` and `||`. The right operand of `&&` runs only on the left's true edge,
  so it is checked under that refinement, and the whole condition refines its true edge by both
  tests: `!is.null(x) && length(x) > 0L` reads a non-`NULL` `x`. `||` does the same on the false
  edge. The other edge of a compound condition is not refined. A family test on an untyped local
  makes the value unchecked on the true edge rather than constraining it, so after `y <- a`,
  `is.numeric(y) && y + 1 > 0` leaves `a` open, where `y + 1 > 0` alone would require it to be
  numeric.
- `is.na(x)` is not a type guard, because being `NA` is a property of a value, not of a type.
- A test that two values differ in being `NULL` ties them together for the rest of the body. After
  `if (is.null(A) != is.null(b)) stop(...)`, a later `!is.null(A)` also rules `NULL` out of `b`.
  The same holds for `xor(is.null(A), is.null(b))` and for the spelled-out
  `is.null(A) && !is.null(b) || !is.null(A) && is.null(b)`. A write to either variable, even on one
  branch, ends the tie.
- A one-argument call to a function that is not a type test, such as `is_loaded(package)`, is
  remembered on its true edge. A callee whose only `NULL` return is a statement
  `if (!pred(x)) return(NULL)` in its body, on a formal it never rewrites and with no other return
  that may be `NULL`, returns without `NULL` when the caller's argument is a variable on which
  `pred` was already found true.
  With `ns_env <- function(package) { if (!is_loaded(package)) return(NULL); asNamespace(package) }`,
  `if (!is_loaded(package)) stop("not loaded")` followed by `parent.env(ns_env(package))` checks,
  while the same call without the test is reported. A write to the variable after the test, even
  on one branch or in a loop, forgets it.

#### Lazy arguments and required formals

R evaluates an argument only when the body forces it, and omitting an argument is an error only at
that moment. A formal without a default is therefore required at call sites only when every path
through the body forces it, so `function(x, unused) x` may be called as `f(1)`, and
`function(x, y) if (is.null(x)) y else x` may be called as `f(1)`, because the branch that reads `y`
is not taken. This relaxes only an inferred
signature. An annotation is honored as written, so under `#: fn(a: integer, b: character) -> integer`,
`function(a, b) a` still requires `b`, and to let callers omit it the annotation says `[b]`. A read forces the formal, with these
exceptions and additions:

- A read on only some paths does not force the formal. The branches of `if`, `switch()`, and `match`
  force only what all of them force, and an `if` without `else` or a `switch()` without an unnamed
  default forces nothing. The right operand of `&&`, `||`, or `%||%` and the body of a loop may not
  run, so they force nothing either, except that the branch an `if (a && b)` takes has run `b`.
- A path that leaves through `return()` forces only what it read before returning, so in
  `function(flag, value) { if (flag) return(NULL); value }`, `value` is optional. `stop()` is not a
  return: a path that stops never completes the call, so it does not relax what the other paths
  force.
- Passing the formal on under its own name to a project function, as in `inner(x, finally = finally)`,
  does not force it, because the callee decides whether it is needed. A call to a library function
  still forces it, except for a base R parameter that has no default and that the function tests
  with `missing()`: `Reduce(f, x, init = .init)` and `base::tryCatch(expr, finally = finally)` leave
  the formal unforced.
- Passing the formal bare, under any name or position, to a project function's parameter that the
  callee may leave unread does not force it either. Such a parameter is optional without a default,
  or tested with `missing()` in the callee's body. A missing formal passed on does not take the
  callee's default, so in `table_of <- function(x, format) pick_format(format)`, `format` is
  optional when `pick_format <- function(format = NULL)` tests `missing(format)`, and required when
  `pick_format` never tests it. As for a formal's own `missing()` test, the order of the test and
  the reads is not checked.
- Passing the formal positionally to a function that the enclosing body defines further down,
  as in `format_advice <- function(x) format_advice_cli(x)` before `format_advice_cli <- function(x)
  "advice"` in the same `local()`, does not force it either. The sibling runs only after its
  definition, and the checker does not look at what it reads, so the formal stays optional even
  when the sibling reads it, and a call that omits it is not reported.
- A body that dispatches with `UseMethod()` forces none of its formals, because it hands them to a
  method unevaluated, and the method decides what it needs. So
  `describe <- function(x, ...) UseMethod("describe")` may be called as `describe()`.
- A read guarded by `missing(name)` does not make the formal required; see below.
- An argument of `substitute()` or `quote()` is not evaluated, so a formal named only there is not
  forced. The same holds for rlang's `enquo()`, `enquos()`, `enexpr()`, `enexprs()`, `ensym()`,
  `ensyms()`, and `maybe_missing()`, so `quo <- function(expr) enquo(expr)` may be called as
  `quo()`.
- A formal assigned before any read, as in `function(x) { x <- 1; x }`, is never forced. The order
  is evaluation order, so `n <- n / 2` forces `n`, and a `for` variable is assigned by the loop.
- A write on some paths covers those paths, so a later read forces the formal only on the paths
  that did not write it. `function(x, flag) { if (flag) x <- 1; x }` may be called as `f(flag =
  TRUE)`, and so may a formal written in a `while` or `for` body, the right operand of `&&` or `||`,
  or some arms of a `switch()`, because a call that takes the writing path never needs the
  argument. A path that forced the formal before writing it still forced it, so
  `if (flag) x <- x + 1; x` requires `x`, and a write inside `local()` binds a new frame and covers
  nothing.
- `x <<- 1` writes an enclosing frame, so it never assigns the formal `x`.
- A function that writes a name with `<<-` reads that name as the binding it keeps updating, such
  as a Reference Class field, never as the shipped function of the same name. In `t <<- t[-drop]`,
  `t` is `Unknown` rather than base `t`, so indexing it reports nothing, and strict mode reports the
  read. A project binding of that name still types the read.
- A read inside a nested function forces the formal, because the closure may run, unless the
  nested function has its own parameter or assignment of that name.
- A read inside another formal's default forces the formal only when that default runs, which is
  when the call omits the formal that owns it and the body forces that formal. So in
  `g <- function(x, y = x) y`, `x` is required exactly when `y` is left out: `g(y = 1)` and `g(2)`
  are accepted, and `g()` is reported as leaving out `x`, as R fails with "argument "x" is
  missing". A formal with its own default, or one the body tests with `missing()`, stays optional.

#### `missing()` on a defaultless formal

A formal that the body tests with `missing(name)` (or rlang's `is_missing(name)`) is optional at call sites, which is how R writes an
optional argument without a default: `function(name, punct) if (missing(punct)) … else …punct…` may
be called without `punct`. The test also narrows whether the formal was supplied, like a type guard:

- On the true edge, reading `name` is an error, because R fails that read with "argument is missing,
  with no default". Writing it is legal and supplies it, as in `if (missing(punct)) punct <- "!"`.
- On the false edge the formal is supplied, and reads are ordinary.
- A diverging true edge, such as `if (missing(x)) stop(...)`, leaves the rest of the body on the
  supplied edge, and `!missing(name)` swaps the edges.
- After the branches rejoin, the formal counts as unsupplied only when it is unsupplied on both
  edges, so only definite failures are reported.
- A formal with a default is never narrowed, because reading it while unsupplied evaluates the
  default.
- As in R, `missing()` applies only to the immediate function's own formals.

### Blocks

A block evaluates to the type of its last expression, so an empty block is `NULL`. A trailing `;`
adds no expression in R's grammar, so `{ 1L; }` is `integer`.

### `return`

`return(x)` exits the enclosing function with `x`, and `return()` exits with `NULL`. It is a
control-flow construct recognized by its bare name, as `local` is, rather than a call.

- A function's return type is the union of every `return` value in its body with the body's trailing
  value, so `function() { if (c) return("foo"); 5 }` is `fn() -> character | double`.
- A body that always exits, because it ends in a `return`, or in a `repeat` that no `break` leaves,
  contributes no trailing value, so `function() return(TRUE)` is `fn() -> logical`, not
  `fn() -> logical | NULL`. A body that ends in `stop()` contributes none either, so
  `function(x) { if (x) return(1L); stop("no") }` is `fn(x: logical) -> integer`.
- An inferred return type reads a bare `return(NA)` as a missing value of the other returns' type
  when they all share one atomic type, so a function that returns `NA` on one path and a string on
  the others is `-> character`. Otherwise the `NA` joins as `logical`, as in
  `fn(x: logical) -> list{double} | logical`. A declared return type still checks `return(NA)` as
  `logical`, so declare `-> character` with `return(NA_character_)`.
- The `return` expression itself yields no value where it stands, so it types as `NULL` locally and is
  not a strict-mode origin, just like `break` and `next`.
- The returned expression is checked like any other expression.
- A `return` inside a loop exits the whole function, so it abandons the loop the way `break` does.
- A `return` at the top level is an R runtime error. Its value is still checked, and joins no
  function's return type.

### `switch`

`switch(subject, a = ..., b = ..., default)` selects one branch by the subject's value at run time.
That selection cannot be modelled statically, but the call is still checked in full:

- The subject and every branch are type-checked.
- The call's type is the union of the branch value types. `NULL` joins the union unless there is a
  default branch, because an unmatched `switch` returns an invisible `NULL`. A default branch is any
  branch without a name, including the first.
- A named branch with no value falls through to the next branch, as in R, and contributes no type of
  its own.
- A branch label may be `NULL`, as R's grammar allows: `switch(typeof(x), NULL = 1, 2)` labels the
  case for the string `"NULL"`.
- With a subject `typeof(x)` on a local variable, each named branch runs only for values whose type
  its labels (together with the empty labels falling through to it) name, so `x` is narrowed inside
  the branch. A union keeps the members a label can match. An unannotated parameter tested this way
  is `Unknown`, as [guard narrowing](#guard-narrowing) describes, so `logical = if (x) ...` does not
  pin the type the other branches and callers see:
  `function(x) switch(typeof(x), logical = if (x) "T" else "F", "other")` is
  `fn(x: Unknown) -> character`.
- Exactly one branch runs, so assignments inside them fork and join exactly like the arms of an
  [`if`](#if-expressions), and a branch that cannot fall through contributes no state. A name
  introduced only inside the branches is not defined on the path where nothing matches, which R
  reports as `object 'r' not found`.
- `switch` is recognized by its bare name, so a local binding named `switch` makes the call an
  ordinary one again.

### `for`

`for (name in value) body` needs an iterable source, and binds `name` to its element type:

- A vector of any shape iterates with its scalar element type.
- A list-like `list[T]` and a dict-like `list[named: T]` iterate with `T`.
- A tuple-like or record-like list iterates with the union of its item types, so
  `for (item in list(a = 1L, b = "two")) ...` binds `item` as `integer | character`. The empty list
  iterates with `NULL`, the union of zero item types.
- A union of iterables iterates member by member.
- `NULL` is iterable and runs zero times, which is legal R. It binds the variable as `NULL`.
- `Any` iterates with `Any` items, and `Unknown` with `Unknown` items.
- An opaque nominal iterates with `Any` items, because its element shape is not visible.
- Iterating does not constrain a value whose shape is undetermined, such as an unannotated
  parameter, because R iterates both vectors and lists. The loop variable becomes `Unknown`.
- Any other source, such as a function, is an error, reported on the source expression.

The source is evaluated once, before the first iteration, and the loop does not change its type. The
loop variable is re-initialized from the source on every iteration, so an assignment to it in the
body does not carry over into the next iteration.

After the loop, R keeps the variable's last value, or sets it to `NULL` when the source was empty.
A read there is therefore the element type joined with `NULL`, and with the variable's type at the
end of the body when the body assigns it. A write that a `break` or `next` cuts off from the end of
the body is not counted, which is a known gap, and so is a nested loop that reuses the name. A `from:to` range always has at least one element, so after
`for (i in 1:n) {}` the variable `i` is `integer`, while after `for (value in x) {}` with
`x: double[]` it is `double | NULL`. A loop at the top level of a file leaves its variable bound
like a top-level assignment, so a later statement or item reads the same type. When the item also
binds the name in another way, the name exports as `Unknown`.

### `while`

A `while` loop takes a [scalar condition](#conditions), which is re-evaluated before every iteration,
so reads in the condition see the loop's joined state. The loop evaluates to `NULL`.

### `repeat`

A `repeat` loop has no condition and runs its body at least once, so a variable written in the body is
definitely assigned after the loop. It evaluates to `NULL`. A `repeat` that no `break` leaves never
completes, so code after it is unreachable and a function body ending in it contributes no trailing
value.

## Naming and scoping

### Project file order

Project files are ordered the way R collates a package: by the `Collate` field of `DESCRIPTION` if it
has one, and otherwise by the `C`-locale collation of the source file names. An earlier or later file
on this page means earlier or later in this order.

### Value names

A top-level value name in a package is global across its files:

- Any file may refer to a top-level binding in another.
- When several files define the same name, the later file wins, and both definitions are reported.
- Every top-level assignment binds a package global, wherever it sits in the statement: in a bare
  `{ }` block, in an `if`, `for`, or `while` body, in a block passed to a call such as
  `suppressWarnings({ x <- f() })`, or in the value of another assignment.

A reference from another file sees the binding's generalized exported type. Type information does not
flow back into the exporting file, so a call in one file never changes the inferred type of a
function defined in another. Within one file, a top-level name also resolves to its final exported
type, so a use placed before the definition still sees it.

A conditionally executed top-level assignment behaves like a variable slot within its own document:
a later top-level read resolves to it, and reports the maybe-undefined warning when a path without the
assignment also reaches it. A read from another item, or from another file, sees the join of every
conditional writer's type, so `for (i in 1:3) total <- i` followed by
`report <- function() total` types `report` as `fn() -> integer`. Past eight conditional writers, the
slot is `Unknown`.

Inside executable code, naming is lexical, over *mutable variable slots*, matching R's environments:
a scope holds one variable per name, and assignment mutates it.

- A function body, a `local(expr)` call, and a script's top level each form one scope, called a
  *frame*.
- A parameter introduces a slot in the function's frame, and assigning to the parameter's name writes
  that slot.
- The first `<-` or `=` assignment to a name in a frame creates its slot. Every later assignment
  writes the same slot rather than creating a new, shadowing binding.
- An assignment inside a branch or a loop body writes the enclosing frame's slot, because braces and
  control flow do not create scopes.
- A slot shadows an outer or package-global binding of the same name. But a slot that no write reaches
  at a given read does not shadow, and the read resolves outward, just as R's lookup would.
- `for` introduces a loop-local slot, re-initialized from the source on every iteration.
- `local(expr)` evaluates `expr` in a fresh child scope and takes its type. Assignments inside are
  local, while references still see the enclosing names.

Two families of calls evaluate an argument non-standardly. Each is recognized by its bare name, and
rebinding the name to a user function does not change that:

- `library(pkg)`, `require(pkg)`, and `help(topic)` read a bare first argument as a package or topic
  name, so `library(stats)` means `library("stats")`. The name is never resolved as a variable and
  never warned about. A string argument, a named first argument, or a qualified callee makes it an
  ordinary call.
- `quote(expr)`, `substitute(expr)`, `bquote(expr)`, and `expression(expr)` build an expression
  instead of running it, so an assignment written inside one binds nothing: `quote(x <- 1)` leaves `x`
  undefined. Nothing inside is checked for arity or argument types, and a name it mentions need not
  exist, so `expression("density " * f[1] - f[2])` is not a type error. The call is `Any`. Those
  names still count as reads, because `eval` may run the expression later. A project function with
  one of these names is an ordinary call.

### Name references

A name reference evaluates to the type currently bound to the name. When the name is not bound, the
checker reports it as unresolved, and treats the reference as `Unknown` from then on, so checking
continues without a cascade of follow-on errors.

### Called names

R looks up the name in a call `f(...)` as a function: a binding whose value is not a function is
skipped, and the lookup continues outward. A string call head is the same lookup, so
`"toupper"(x)` calls `toupper` exactly as `toupper(x)` does. A called name therefore resolves to the nearest binding
whose type can be a function, so this is clean:

```r
upper_names <- function(x) {
  names <- toupper(names(x))
  names(x)
}
```

- A binding whose type is definitely not a function (`NULL`, an atomic vector, a list, a record, a
  tuple, a tag, a frame, or an opaque nominal such as `matrix` or `Date`) is skipped. The lookup tries the enclosing frames' slots of the same name,
  then the package's top-level binding, then the library. A top-level `l10n_info <- NULL` therefore
  leaves `l10n_info()` calling base's function. In a package file the top level is the namespace
  itself, so past it only the library remains. A test file's top level encloses in the helpers'
  bindings and then the package namespace, and a script's in the namespace, so
  `path <- path("a")` in a test still leaves `path("b")` calling the package's `path`.
- A top-level `setGeneric("f", ...)` binds `f` as a function, and so does one inside a top-level
  `if` with no `else`, such as `if (!isGeneric("type")) setGeneric("type", fun)`: whichever branch
  runs, `type` is a function afterwards. So a `type` parameter holding a string still leaves
  `type(object)` calling the generic.
- A binding typed as a function, `Unknown`, `Any` or a nominal type is used.
- A binding whose type joins functions with `NULL` is called as the functions when the body
  computed it, such as `handler <- switch(kind, ...)` without a default, because the code presumably
  rules the `NULL` path out. A parameter, or a variable whose last assignment is annotated, admits
  that `NULL` on purpose, so calling it is reported until an `is.null()` test rules it out.
- A binding with no type information yet, such as an unannotated parameter nothing has constrained
  or a parameter annotated with a type parameter `T`, may hold anything. When the body only ever
  calls it, it is a callback, and the call checks against it as usual: both
  `function(x, callback) callback(x)` and `function(format) format(1L)` infer the parameter as a
  function, even though base has a `format`. A call declares no parameter names, so a later call
  may name an argument the first call passed by position: after `f(pars, arglist)`, the call
  `f(pars = pars + 1, arglist)` takes a slot without checking it. A later call may also omit an
  argument an earlier call passed, relying on the callee's default, so after
  `api(op, options = list(), version = "v1")` the call `api(op, version = "v1")` checks. An argument
  beyond the slots the first call used is still an error, unless the body reads `formals()` or `formalArgs()` of that
  parameter anywhere. Code that does so picks the call by the callback's arity, as in
  `if (length(formals(handler)) == 1) handler(src) else handler(src, call)`, so a call with
  another argument count is not checked. Which slot the name took is unknown, so the call's
  positional arguments are not checked either. When the first call forwarded `...`, as
  `f(x, ...)` does, a later name may also go to `...`, so it takes only a slot that the call's
  positional arguments leave free. When the body also reads it as a value and an outer
  binding of the same name is a function, the call could reach either one, so it types as `Unknown`
  and constrains neither. So `function(x, names) x[names(x) %in% names]` does not make `names` a
  function parameter, and `dir <- path; dir(dir)` calls base's `dir` unchecked. A function that a
  default-attached package exports counts as such an outer binding even when no stub types it, so in
  `function(range, pretty = TRUE) if (pretty) pretty(range) else range` the call reaches base's
  `pretty` and is `Unknown`. A package import that ry has no export list for counts too, so under
  `import(fs)`, `path <- path(path, "DESCRIPTION")` calls fs's `path` and is `Unknown`.
- When no binding of the name is a function, R reports the call, and so does the checker: the error
  names the nearest binding's type. A `NULL` binding is the exception, because it is usually a
  placeholder that a package fills in later, from `.onLoad` or with `<<-`. A call on a callee whose
  type is `NULL`, such as `reject(1)` after a top-level `reject <- NULL`, or `registry$invoke()` on
  a `NULL` `registry`, is unchecked and types as `Unknown`. A function the body computes that only
  may be `NULL`, such as `fn <- switch(kind, upper = toupper, lower = tolower)`, is called as the
  function, because the `NULL` path is one the code presumably rules out (`match.arg(kind)`). A
  parameter whose default or declared type admits `NULL`, such as
  `transform: (fn(x: character) -> character) | NULL`, is still reported, because the caller
  supplies that `NULL`.
- Hover and go-to-definition on the called name follow the binding the call reaches.

`pkg::name` is never looked up this way: it names one namespace, as described next.

### Namespace access

`pkg::name` and `pkg:::name` read one name directly from a package's namespace, bypassing lexical
scoping.

- A namespace is *known* when stubs declare it. The shipped standard-library packages are known, and
  so is any namespace a project stub file declares: `stubs/dplyr.Rtypes` declares the namespace
  `dplyr` (see [stubs](/development/authoring-stubs.md)).
- The project's own package is always known. Qualifying a name with the package you are editing, as
  `withr::defer()` does inside the package `withr`, reads the definition the checker already holds,
  and wins over a stub namespace of the same name. It reads the namespace only, so in a test file or
  a script `pathpkg::path` skips that file's own `path` binding. The name itself is not validated,
  because a package exports names its sources never bind: re-exports, S4 generics from
  `setGeneric`, datasets under `data/`, and bindings installed by `.onLoad`.
- When the stubs declare `name` in `pkg`, the qualified read has the stub's type. A project binding
  of the same name does not change it: `base::date()` calls base's `date` even when the package
  defines its own `date`. A name that only the namespace's [export manifest](#standard-library-exports) lists
  validates the same way, and types as `Unknown`.
- An unknown namespace warns, and so does a known namespace that neither declares nor lists the name
  ("not exported"). An unknown namespace stays quiet when it belongs to the package's
  [declared universe](#package-imports-namespace-and-description).
- A [conditional namespace](#conditional-stub-namespaces-datatable-dplyr-ggplot2-and-testthat), and
  any shipped export manifest outside R's own packages, stays inactive until the project uses the
  package, and a `pkg::name` read does not count as use. The read is still accepted, because
  `pkg::name` loads a package without attaching it, so a script may use a package that way alone.
  Until the package is used, the read types as `Unknown`, but its name is still checked against
  the package's shipped export manifest and stubs, so in a script with no `library(dplyr)` and no
  `DESCRIPTION`, `dplyr::mutate` passes and a misspelled `dplyr::mutat` warns "not exported". A
  shipped package with typed stubs but no export manifest is not checked this way, because its
  stubs may describe only part of it.
- A project stub that overrides a shipped name's type does not remove the name from its shipped
  namespace, so `stats::sd` stays valid under an `sd` override.
- A qualified read that could not be validated types as `Unknown`, and is a strict-mode origin.
- `:::` reads an internal name, so a name the namespace does not export is not reported there.

### Package imports (`NAMESPACE` and `DESCRIPTION`)

The package's `NAMESPACE` and `DESCRIPTION` files at the package root extend name resolution across
the whole package. Without them, analysis behaves as though both were empty.

- `importFrom(pkg, name)` makes `name` a known bare read that is never reported as unresolved. The
  read has the stubs' type for the name when there is one, and `Unknown` otherwise. An `importFrom`
  naming something a stub-described namespace does not export is an error at the import, rather than
  the warning a qualified read gets, because R refuses to load such a package.
- `import(pkg)` of a namespace the stubs describe makes exactly `pkg`'s exports known bare reads.
  When no stubs describe `pkg`, its export set cannot be known, so every otherwise-unresolved bare
  read in the package is tolerated instead of guessed at.
- A `library(pkg)` or `require(pkg)` call anywhere in the project is the script-world equivalent of
  `import(pkg)`, and follows the same rule. Because R's search path is project-wide, so is the
  tolerance. An [export manifest](/development/authoring-stubs.md#export-manifests) is enough to lift
  it; types are not required. The tidyverse, `knitr`, `rlang`, `glue`, `jsonlite`, `R6`, and the rest
  of the shipped manifests therefore keep unresolved-name detection on. A package nothing describes
  switches it off, and a two-line `stubs/<pkg>.Rtypes` of your own switches it back on.
- Attaching a meta-package activates the packages it attaches, not the names it exports.
  `library(tidyverse)` makes `mutate`, `read_csv`, and `str_to_upper` reachable because it attaches
  `dplyr`, `readr`, and `stringr`, types included where they have them.
- Attaching or importing the project's *own* package, the one named in the `Package` field of
  `DESCRIPTION`, does not switch the tolerance on, because its exports are the project's own
  definitions. Otherwise the `library(yourpkg)` that `usethis` writes into `tests/testthat.R` would
  turn off unresolved-name detection for the whole package.
- A `pkg::name` read of a namespace the stubs do not know does not warn when `pkg` belongs to the
  package's *declared universe*: a `DESCRIPTION` dependency field (`Depends`, `Imports`, `Suggests`,
  or `Enhances`), or the source namespace of any `NAMESPACE` import. Such a read types as `Unknown`.
- `useDynLib(lib, ...)` binds native symbols, which read as `Unknown`. Each listed symbol binds its
  name with the `.fixes` prefix in front, so `useDynLib(lib, hash, .fixes = "c_")` binds `c_hash`.
  With `.registration = TRUE`, R binds every routine the compiled code registers, and those names
  are known only to the compiled code, so two reads resolve: any name that starts with a non-empty
  `.fixes` prefix, such as `C_endpoints` under `.fixes = "C_"`, and any bare name that is the routine
  argument (the first positional one, or `.NAME`) of `.Call`, `.External`, `.External2`, `.C`, or
  `.Fortran`.

### Standard-library exports

The shipped stubs pair each namespace with a vendored *export manifest*: the complete list of names
the namespace really exports, generated from a live R session (see
[authoring stubs](/development/authoring-stubs.md#export-manifests)). Every manifest name is a known
global:

- A bare or qualified read of a manifest name always resolves, with no unresolved or not-exported
  warning. It has the stub's type when one exists, and `Unknown` otherwise.
- Typo suggestions for names that really are unresolved draw on manifest names as well as on typed
  declarations.

Manifests follow the way R exposes each namespace:

- The default-attached packages, `base`, `stats`, `utils`, `graphics`, `grDevices`, `methods`, and
  `datasets`, resolve bare and qualified, unconditionally.
- The packages R ships but does not attach, `tools`, `parallel`, `compiler`, `grid`, `splines`,
  `stats4`, and `tcltk`, always validate a qualified read. A bare read resolves only once the project
  attaches the package with a `library()`-family call or declares it as a dependency, exactly as in
  R.
- A conditional namespace's manifest activates together with its stubs (see
  [conditional stub namespaces](#conditional-stub-namespaces-datatable-dplyr-ggplot2-and-testthat)).
  While the namespace is inactive, its names stay unknown, bare and qualified alike.
- A read satisfied only by an import still counts as a use for the unused check. A read with no
  known type, bare or qualified, is a strict-mode origin, whether it is a call or a value read such
  as `template <- glue`. A bare `base` name read as a value, such as `c` in `lapply(xs, c)`, is
  the exception: it is `Unknown` and not reported, because those names are intrinsics whose calls
  are typed specially.
- An arithmetic, comparison or logical operator read as a value, such as `` `+` `` in
  ``Reduce(`+`, xs)``, is `fn(e1: Any, [e2]: Any) -> Any`, because its result depends on the
  operands' classes.

### Replacement-form assignment

A replacement-form assignment (`x$field <- v`, `x[["name"]] <- v`, `x[[key]] <- v`, or
`x@slot <- v`) reads the base variable, applies the write, and writes the result back to the base's
slot, so the slot's type reflects the update:

- A write to a known field, `x$field <- v` or `x[["literal"]] <- v`, on a record-like `x` sets that
  field's type to the type of `v`, adding the field if it is absent. The same write on an empty
  `list()` starts a record `list{field: V}`, and on a list whose names are not tracked,
  `list[named: T]` or `list[T]`, it gives `list[named: T | V]`. Writing `NULL` removes a field, so
  it adds no type.
- When `x` is a union, as after a loop that may or may not have filled it, each member takes the
  write and the results join, so `ret <- list()`, a loop of `ret[[i]] <- part`, and then
  `ret$count <- n` leave every shape of `ret` holding the count.
- The same write on a *nominal* `x` is checked rather than applied, because a nominal type's
  representation is its invariant: `v` is checked against the field's declared type, a field the
  representation does not declare is an error, and `x` keeps its nominal type either way.
- A write with a computed key, `x[[key]] <- v` where `key` is not a literal, refines the container's
  element type instead:
  - an empty `list()` becomes a dict-like `list[named: V]`;
  - a dict-like `list[named: T]` becomes `list[named: T | V]`;
  - a list-like `list[T]` becomes `list[T | V]`, and stays list-like;
  - a record-like `list{a: A, b: B}` becomes `list[named: A | B | V]`, because the write may add a
    field or replace any one, so `globals[[key]]` afterwards may be `v`;
  - a tuple-like container is left unchanged.
- A write through `[`, `x[i] <- v` or `x[i, j] <- v`, on an atomic `x` with an atomic `v` coerces
  `x` to the wider of the two atomic types, as R does. So after `prob <- rep(NA, n)`, the write
  `prob[i] <- 0.5` makes `prob` a `double[]`, and `x[1] <- "a"` makes a numeric `x` a
  `character[]`. A scalar `x` stays a scalar, because a type carries no length. A `[` write on a
  list, or of a value that is not atomic, leaves `x` as it was.
- A write through a chain of accessors, such as `x[[1]]$private <- v` or `x$a$b <- v`, rewrites
  each container on the way back to the root: the innermost one takes `v` by the rules above, and
  each enclosing one takes the rewritten child at its own step. A step whose position is known
  (`$name`, `[["name"]]`, or `[[1]]`) updates that field or position, and a computed `[[i]]` step
  follows the computed-key rules above. A `@` step, or a `[` step before the last, is not tracked. So after
  `old <- list(list(private = NULL)); old[[1]]$private <- list(deep_clone = 1)`, reading
  `old[[1]]$private$deep_clone` is a `double`. Writing a field of a `NULL` grows it into a one-field
  record, as R does, so `x <- NULL; x$a <- 1` makes `x` a `list{a: double}`.
- `formals(f) <- v` and `body(f) <- v` rewrite the function itself, so `f` is `Unknown` afterwards
  and calls to it are not checked. Other replacement calls, such as `names(x) <- v` or
  `attr(f, "kind") <- v`, leave the base's type as it was.
- The accessor chain and the index or key expressions are ordinary reads, so their own errors surface.
  A replacement whose accessor chain has no variable at its root, such as `f(x)$a <- v`, is an
  unsupported construct: it types as `Unknown` and is a strict-mode origin.

Building a map with computed-key writes and then reading a key back gives `V | NULL`, because a
dict-like read may miss (see [`[[` on lists](#-on-lists)), so guard the read with `is.null` before a
use that needs a `V`.

### Control-flow joins

A read of a variable sees every write that can reach it, so wherever control flow merges, the
variable's possible states are joined:

- After an `if` without `else`, a variable written in the branch joins its type from before the `if`
  with the type the branch wrote.
- After an `if ... else`, a variable joins the outcomes of the two branches, and a branch that does
  not write it contributes the state from before the `if`.
- A loop body may run zero or more times, so reads inside the body and after the loop join the state
  from before the loop with the state flowing around the back edge.
- `repeat` runs at least once, so after the loop the variable has the state the body left it in.
- Joining equal types keeps the type, and joining different types gives their union.
- After an `if`, a variable that one path left `Unknown` is `Unknown`, because the value may be
  anything. So after `if (in_memory) db <- cache else db <- list.files(dir)`, where `cache` is
  untyped, `db[[id]]$hashes` is not checked.
- Around a loop's back edge, joining with `Unknown` keeps the other side, so a pass that recovered
  from an error with `Unknown` does not erase the type the error was reported against.

So `f <- function(flag) { x <- 1L; if (flag) x <- "two"; x + 1L }` is a type error, because `x`
reads as `integer | character`, and `+` rejects the `character` member.

A variable that still holds an untyped value, usually an unannotated parameter, joins differently
when one path rebinds it. A union would let a later use of the rebound value constrain the
parameter that the other path still holds, so the joined variable is `Unknown` instead, and the
parameter stays open: `function(x, flag) { if (flag) x <- 1L; x + 1L }` is
`<T> fn([x]: T, flag: logical) -> Unknown`. The default idiom `if (is.null(x)) x <- 0L` joins the
same way, so `x` reads as `Unknown` after the `if`. A parameter that only carries a bound such as
`numeric` still counts as untyped, so `if (flag) omega <- omega + m %*% m` leaves `omega` a
`T: numeric` that a caller may fill with a plain vector, and a loop's `x <- n` does not make two
parameters one type.

A variable with exactly one reaching write keeps that write's generalized type, so
`f <- function(x) x` inside a body stays `<T> fn(x: T) -> T`, and so does an alias of it: after
`g <- f`, both `g(1L)` and `g("a")` check. When writes merge at a join, the variable holds a single
type instead, so two conditionally assigned functions read as a union of both signatures. A call on
that union returns the union of their return types. An argument whose type is still open, and which a
member accepts only by narrowing it, becomes `Unknown`.

Definite assignment follows four rules:

- A read that some path reaches with no prior write reports
  [`maybe-undefined`](/reference/diagnostic-codes.md), because R raises `object 'x' not found` on that
  path. Inside a function, a binding of the same name outside the function would be read instead,
  which this check does not yet consider. The finding is off by default; turn it on with
  `[check] maybe-undefined = true`. Two conditions that always agree at run time are still two
  branches to the checker, so `if (ok) v <- …` followed by `if (ok) use(v)` is reported, although it
  is safe.
- A `repeat` is left through its `break` points, so one that always assigns before breaking reports
  nothing, and nothing after a `repeat` without a `break` is reachable. A branch that cannot fall
  through contributes no path.
- A read that no write can reach does not resolve to the variable at all (see the shadowing rule
  under [value names](#value-names)).
- A top-level variable is different, because a path without a write reaches the enclosing
  environment. The read then sees the name's binding elsewhere in the script or package, and that type
  joins into the slot like any other reaching write. After `p <- "word"`, the body of
  `while (cond) p <- p - 1L` is a type error, because the first iteration reads a `character`. A name
  with no such binding stays `Unknown`.

An item whose check reports an error exports `Unknown`, so one mistake does not cascade across a file.
An item with a `#:` annotation is the exception: even when its body violates the annotation, every
call site is still checked against the declared signature.

#### Unused assignments

With the `unused` check enabled, an assignment whose value no read can observe on any path reports
`unused` on the assigned name. Top-level assignments visible to the package, parameters, `for`
variables, and names starting with `.` or `_` are never reported.

A read inside a nested function is a *capture*. The closure runs after its frame has finished, so
every write to the captured name stays observable, and none of them is a dead store. That holds only
for the frame the read resolves to: a same-named binding in an enclosing frame is shadowed, not read,
and still warns.

- `f <- function() { x <- 1L; x <- 2L; y <- x; y }` warns that the first write to `x` is unused.
- `f <- function() { x <- 1L; g <- function() x; x <- 2L; g }` is clean, because both writes stay
  alive through the capture.
- `f <- function() { x <- "outer"; g <- function() { x <- TRUE; function() x } }` warns, because the
  innermost function reads the `x` of `g`.

`on.exit(expr)` reads the same way: R runs the expression when the function returns, so it observes
the last value of every name it mentions. The standard rollback guard is therefore clean:

```r
with_transaction <- function(con, body) {
  committed <- FALSE
  on.exit(if (!committed) dbRollback(con))
  body(con)
  committed <- TRUE          # read by the exit handler, not a dead store
  invisible(TRUE)
}
```

A string template reads too. glue and cli evaluate each `{...}` segment of a string in the calling
frame, and so does any wrapper that forwards `parent.frame()`, so a name inside the braces of any
string literal keeps the binding it would resolve to alive. Such a name is never reported as
unresolved, because the string may be plain text. `{{` is glue's escaped brace, a segment that opens
with `.` is cli markup whose style name is not a read (`{.path {file}}` reads only `file`), a segment
that opens with `?` is cli pluralization text, and a name after `$`, `@` or `::` is a member:

```r
report <- function(files) {
  n <- length(files)          # read by the template, not a dead store
  cli::cli_inform("Found {n} file{?s}: {.path {files}}")
}
```

#### Names bound at run time

In a file that calls `R6Class`, the names `self`, `private`, and `super` resolve and type as
`Unknown`, because R6 creates those bindings when an object is constructed. So do they inside a
method added with `Gen$set("public", "name", function(...) ...)` in any file. Elsewhere, a file
that defines no R6 class still warns about `self`. The recognition is syntactic, so a local binding
that shadows `R6Class` is not honored.

A Reference Class method runs in its object's frame, which sits between the method body and the
package namespace. Inside a method that `setRefClass(methods = list(...))` or
`Gen$methods(...)` defines, a field or method of the class therefore resolves and types as
`Unknown`, and it shadows a top-level function of the same name:

```r
getBaseFont <- function(wb) wb$font
Workbook <- setRefClass("Workbook", fields = c(font = "character"))
Workbook$methods(getBaseFont = function() font)
Workbook$methods(widths = function() nchar(getBaseFont()))  # the method, so no `wb` is needed
```

The members are the names in `fields` and `methods`, the names that `Gen$fields(...)` and
`Gen$methods(...)` add anywhere in the project, those of every superclass in `contains` that the
project defines, `.self`, and the methods every object inherits (`callSuper`, `initFields`, `copy`,
`field`, `show` and the rest of `envRefClass`). A misspelled member is still an unresolved name. A
class with a superclass the project does not define, or a `Gen$methods(...)` call on a generator
the project does not bind to `setRefClass`, has members ry cannot see, so its methods resolve every
name.

Inside any function body, the S3 dispatch variables `.Generic`, `.Method`, `.Class`, `.Group`,
`.GenericCallEnv`, and `.GenericDefEnv` resolve and type as `Unknown`, because `UseMethod`,
`NextMethod`, and group-generic dispatch bind them in the method's frame and any function can be
called as a method. At the top level they are unresolved names.

Inside a function body, `assign("name", value)` and `delayedAssign("name", value)` with a string
literal name and no other argument bind `name` in the function's frame, as R does. A later read of
`name` sees that local binding, typed `Unknown` even when `name` was a parameter or an earlier
local, rather than an outer one, so after
`delayedAssign("length", parse_int(read_bytes(2)))` the call `read_bytes(length)` does not read
base's `length`. A call that names an environment, as in `assign("x", 1, envir = globalenv())`,
binds nothing locally.

A top-level `globalVariables(c("a", "b"))` or `utils::globalVariables(...)` call with literal string
arguments declares those names as bound dynamically for the whole package, which suppresses the
unresolved-name warning for them everywhere.

### Type names

`@type` and `@alias` declarations share one project-global namespace:

- A type reference may resolve to a declaration in the same file or another, and forward references
  are allowed.
- A duplicate type name is an error whatever the declaration kind: `@type` twice, `@alias` twice, and
  one of each all conflict, and every declaration involved is marked as erroneous.
- A duplicate is judged within the namespace the declaration lives in. Package files share the
  project-global namespace, so two package files that declare one name conflict. A script's
  declarations belong to that script alone, so two scripts may each declare `Thing`, while declaring
  `Thing` twice within one script is a duplicate.
- Type parameters are local binders, and shadow project-global type names.
- A type reference that resolves to nothing is an error at the referencing token, with a hint when a
  close match exists. A reference can resolve to a built-in type, a binder in scope, a project `@type`
  or `@alias` declaration, or a class declared in a stub. An undeclared name then compares like
  `Unknown` everywhere, so the typo is reported exactly once.

### Non-package documents

A file that is not a package source file, such as a script under `scripts/`, contributes neither to
the package's global value namespace nor to the project-global type namespace. A script runs top to
bottom, so its top level is one sequential lexical scope, like a function body:

- A top-level binding is visible only after its assignment, and rebinding a name changes the uses
  after it.
- A use before any script-local or package-global definition is an unresolved name. That includes a
  read inside the very statement that first binds the name, such as `x <- x + 1L` with no earlier `x`.
- A read from inside a nested function resolves against the whole document, because the closure runs
  after the frame has settled, and the last top-level binding of the name wins. That includes the
  enclosing statement's own binding, so self-recursion resolves.
- A conditional top-level write creates the document's variable slot exactly as in package files.
- A masked read, from `with` or from data.table indexing, and a read inside an opaque operator, which
  is a user `%op%` or a pipe R would reject, are never reported as unresolved. Each still counts
  as a use for the unused check, and navigation connects it.

Scripts are type-checked like package files, against the package-global values and project-global
types, plus their own local bindings and type declarations:

- A script may resolve package-global value names and project-global `@type` and `@alias` names.
- A script's top-level value bindings and type declarations are visible neither to package files nor
  to other scripts.
- A package file and a script may reuse the same top-level value or type name without conflict.
- Duplicate top-level value names inside a script do not produce the package-global duplicate-binding
  warning; they behave like ordinary rebinding.

Files directly under `tests/testthat/` are test files, except that a file whose name starts with
`helper` or `setup` is a helper file. testthat sources the helper files into one environment whose
parent is the package namespace, and runs each test file in its own child of that environment. A
test or helper file therefore reads the package's names but never adds to them:

- A test or helper file resolves a name first in its own sequential scope, exactly like a script,
  then in the helpers' namespace, then in the package-global namespace.
- The helpers' namespace holds the top-level bindings of every helper file, the last one in project
  order winning. A test file's own bindings are invisible to every other test file, so a name one
  test file defines and another reads is an unresolved name.
- Inside a closure, a test file's name resolves to the binding written by the same top-level
  statement when there is one, and otherwise to the file's last binding. Each `test_that()` block
  is one statement, so `f <- function() g()` calls the `g` its own block defines even when a later
  block defines another `g`.
- A test file's bindings are invisible to package files, so `names <- letters[1:4]` in a test does
  not change what `names` means under `R/`, and a package file reading a name that only a test
  defines is an unresolved name.
- A test binding and a package binding of the same name are not duplicates, and neither are two test
  bindings. Test files' `@type` and `@alias` declarations are file-local, like a script's.

## Data frames and non-standard evaluation

R evaluates some arguments inside a data frame's own environment, where a bare name is a column
reference that no lexical scope can see. In these *masked* positions, a read that resolves to no
binding is treated as a column reference: a silent `Unknown`, with no unresolved-name warning and no
strict-mode origin. The recognized masks are:

- A single `[` bracket whose subject types as the `data.table` nominal masks all of its index
  arguments, so `DT[speed > 20]` and `DT[, x]` are column references.
- A `[` call carrying an unambiguous data.table signature masks all of that bracket's index arguments,
  even when the subject's type is unknown. The signatures are a `by =` or `keyby =` argument, a `:=`
  column assignment, a `.()` list call, and the specials `.SD`, `.N`, `.I`, `.BY`, `.GRP`, and
  `.EACHI`.
- The base masking family, `with()`, `within()`, `subset()`, and `transform()`, masks every argument
  except the data. Which argument is the data follows R's own matching: a named argument claims its
  formal first (`data` for the `with` pair, `x` for `subset`, `_data` for `transform`), and the
  remaining positional arguments fill what is left, so `with(speed > 20, data = frame)` masks the
  condition. The `base::` spelling masks exactly like the bare one, while another package's export of
  the same name masks nothing. Each masked argument is its own scope, because R evaluates it in an
  environment made from the data: `within(d, total <- a + b)` binds `total` there, never in the
  caller, and such a write is never reported as unused. The results are typed: `subset` keeps a data
  frame, a matrix, or a vector's element type, `transform` and `within` give a `data.frame`, and
  `with` gives `Any`, since its value is whatever its expression computes.
- A call to a [`@masked`](#conditional-stub-namespaces-datatable-dplyr-ggplot2-and-testthat) stub
  declaration.

A name inside a mask that does resolve, such as a local variable or a function like `sum`, keeps its
ordinary resolution and typing, because data.table itself falls back to the lexical scope for names
that are not columns. Inside any single `[`, a `..name` read is data.table's way to name the
variable `name` from the enclosing scope, so it resolves to `name`. Base indexing such as `m[i, j]`
carries no data.table marker, so it keeps full lexical checking. A function written inside a masked argument is masked too, because it is created
inside the data's frame.

### data.table result classes

A bracket with a data.table signature but an unknown subject types as `Unknown`. When the subject
*is* the `data.table` nominal, the class of the result follows from the bracket's syntax, even though
the columns are unknown. Here `j` is the second positional slot or a `j =` argument:

```r
DT[i]                        # data.table: a row filter or a join returns a table
DT[, x := 1]                 # data.table, returned invisibly
DT[, .(m = mean(x))]         # data.table: `.()` and `list()` build a table
DT[, sum(x), by = g]         # data.table: a grouped result is always a table
DT[, x]                      # Unknown: the shape would need column knowledge
```

Anything not covered above, such as an ungrouped computed `j` or a `with =` form, is `Unknown` and a
strict-mode origin.

The class is a real type. It flows through chains, so `DT[a > 1][, .(m = mean(b)), by = g]` stays a
`data.table` from end to end, and it satisfies or violates annotations and parameter types like any
other. Column-level knowledge is out of scope for the `data.table` nominal: element types, membership
checks, and the evolution of columns through `:=` are not tracked. A `data.table` whose columns are
known, such as the result of `fread`, and the built-in DataFrame below track all three.

### DataFrames

A `DataFrame` is ry's built-in table. Its type lists its column vectors, written like a `list{...}`
record with `DataFrame` in front:

#### Inline

```r
price_of <- function(prices: DataFrame{id: integer[], price: double[]}) -> double[] prices$price
```

#### Comments

```r
#: fn(prices: DataFrame{id: integer[], price: double[]}) -> double[]
price_of <- function(prices) prices$price
```

A column is always a vector, so a scalar column type broadens: `DataFrame{id: integer}` is
`DataFrame{id: integer[]}`. A bare `DataFrame` is one whose columns are unknown, and every column
reference on it is a silent `Unknown`. Three more types share this shape: `LazyFrame{...}` is a
query plan, `GroupBy{k: K; a: A}` is a grouped DataFrame whose key columns come before the
semicolon, and `LazyGroupBy{...}` is a grouped plan. A `data.table` with known columns is written
`data.table{...}` in the same way.

A DataFrame is no `data.frame`: its run-time class is `"DataFrame"` alone, so passing one to a
`data.frame` parameter is a type error. `as.data.frame()` converts it and loses the column types,
because a base data frame's columns are not typed, while `as.data.table()` and `as.DataFrame()`
keep every column. A DataFrame satisfies a `list` parameter, because `lapply()`, `Map()` and
`Filter()` call `as.list()`, which turns it into the list of its columns. This is unsound for a
function that indexes its `list` argument with `[`, which on a DataFrame selects rows; overloads
that take a DataFrame directly would close the gap.

`DataFrame()` builds one. Each named argument becomes a column of its vector type, and an unnamed
variable keeps its name:

```r
sales <- DataFrame(team = ["a", "b"], amount = [1, 2])   # DataFrame{team: character[], amount: double[]}
```

An unnamed computed argument, a repeated name, or `...` leaves the columns unknown, and so does a
project's own function named `DataFrame`, which shadows the builtin.

A `List<T>` argument is a column of the R vector type `T` is stored as (`List<F64>` is a `double[]`
column): the frame stores the column as a plain vector. Reading a column back, as `sales$amount` or
`sales[["amount"]]`, gives that plain vector, even when no step could have put an `NA` into it.
`List.from_r(sales$amount)` is the checked way back to a `List`, and it stops with an error on an
`NA`. A read never gives a `List`, because a `List` changes how arithmetic on it behaves: two lists
are never recycled and never mix item types, so `sales$units * sales$price` would stop with an
error. Whether a column holds an `NA`
depends on the data, such as a left join's unmatched rows, so a read that gave a `List` only when
the column had none would make the same code fail or pass depending on its input.

#### Verbs

Each verb of the [DataFrame API](/reference/dataframes.md) types as a new column list, computed from the
syntax of its arguments. A string argument names a column, and any other argument is an
expression built from `Expr.col("x")`:

| Call | Result |
| --- | --- |
| `DataFrame.select(df, ...)` | one column per argument |
| `DataFrame.with_columns(df, ...)` | `df`'s columns, each argument replacing the column of its name or added after them |
| `DataFrame.filter(df, ...)`, `DataFrame.sort(df, ...)`, `DataFrame.head(df)`, `DataFrame.tail(df)` | the columns of `df` |
| `DataFrame.group_by(df, ...)` | `GroupBy{keys; rest}`: the key columns, then `df`'s other columns |
| `GroupBy.agg(groups, ...)` | `DataFrame{keys, aggregates}` |
| `DataFrame.join(df, other, on, how)` | `df`'s columns, then `other`'s non-key columns, with `suffix` added to a name `df` already has; `"semi"` and `"anti"` keep `df`'s columns only |
| `DataFrame.join_asof(df, other, on, by)` | as a left join on the `by` columns and then `on` |
| `DataFrame.lazy(df)`, `LazyFrame.collect(plan)` | the same columns, as a `LazyFrame` or a `DataFrame` |
| `DataFrame.read_csv(path)`, `LazyFrame.scan_csv(path)` | the columns of the file, sniffed as for `fread` (see [Reading files](#reading-files-and-datatables-functions)); with `strings_as_factors = TRUE`, text columns are `factor` |

Every `LazyFrame.` verb types like its `DataFrame.` namesake and returns a `LazyFrame`.

An expression's column is named by `Expr.alias` or by the argument's name, and otherwise by the
first column it reads, as Polars names it. Its type follows R's rules for the operation:

| Expression | Column type |
| --- | --- |
| `Expr.col("x")` | the type of `x` |
| `a + b`, `a - b`, `a * b`, `-a` | `integer` when both sides are `integer` or `logical`, otherwise `double` |
| `a / b`, `a ^ b`, `Expr.mean`, `Expr.median`, `Expr.std`, `Expr.var`, `Expr.cor` | `double` |
| comparisons, `&`, `\|`, `!`, `Expr.is_null` | `logical` |
| `Expr.sum` | `integer` for an `integer` or `logical` column, otherwise `double` |
| `Expr.min`, `Expr.max`, `Expr.first`, `Expr.last`, `Expr.head` | the type of the column, except that `Expr.min` and `Expr.max` of a `logical` column are `integer`, as in R |
| `Expr.len()`, `Expr.count` | `integer` |
| `Expr.if_else(test, yes, no)` | the type `yes` and `no` share |
| `Expr.lit(value)`, a plain R value | the value's type |

A string or `Expr.col("x")` naming a column the subject does not have is a type error on that string,
and so is a join key missing on either side. Inside `GroupBy.agg`, an expression that reads a
column must aggregate it, since `agg` needs one value per group. The exception is an item that is
exactly `Expr.head(n)`, whose up to `n` values per group become rows; `Expr.head` inside a larger
expression is the same error:

```text
type-mismatch

  x `units` gives one value per row, but `agg` needs one value per group. Aggregate it, for example with `Expr.sum` or `Expr.first`
    --[a.R:10:62]
 10 | bad2 <- sales |> DataFrame.group_by("region") |> GroupBy.agg(Expr.col("units"))
    |                                                              ^^^^^^^^^^^^
```

An argument whose expression the checker cannot read, such as a variable holding an `Expr`, leaves
the result's columns unknown.

The operands of an expression must have types the operation takes, as the table engine checks
before it runs a query. In the rules below, a number is an `integer` or `double` column or value,
and text is a `character` or `factor` one:

| Operation | Operands |
| --- | --- |
| `+`, `-`, `*`, `/`, `^`, `%%`, `%/%`, unary `-` and `+`, `Expr.sum`, `Expr.mean`, `Expr.median`, `Expr.std`, `Expr.var`, `Expr.cor` | numbers or `logical`, never text |
| `&`, `\|`, `!` | `logical` or numbers, never text |
| `==`, `!=`, `<`, `<=`, `>`, `>=` | never text on one side and a number on the other |
| the test of `Expr.if_else` | `logical` |

An operand that breaks a rule is a type error on that operand, and a comparison is one on the whole
comparison:

```text
type-mismatch

  x `>` compares `character[]` with `integer`, text with a number, which almost always means the wrong column
   --[a.R:2:35]
 1 | sales <- DataFrame(region = ["eu", "us"], units = [1L, 2L])
 2 | kept <- sales |> DataFrame.filter(Expr.col("region") > 1L)
   |                                   ^^^^^^^^^^^^^^^^^^
```

The engine compares an `integer` with a string by formatting the number, as R does, so that
comparison runs, but it is still an error here: a schema that puts text against a number almost
always means the wrong column. The rules check only operands of known type, so an expression over
a frame whose columns are unknown is never an error. In strict mode, a verb that names a column of
such a frame, with a string or `Expr.col("x")`, is an error on the verb's subject. A chain is
reported once, at its first step that names a column: a later step is not reported again, while a
step that names no column, such as `DataFrame.head(5L)` or `DataFrame.lazy()`, neither reports nor
hides a report.

#### Tables in typed code

A typed function holds a `DataFrame`, `LazyFrame`, `GroupBy`, `LazyGroupBy` or `Expr` as one opaque
value. It cannot look inside one, but it passes it to the [DataFrame API](/reference/dataframes.md),
and those calls compile to native code like the rest of the function:

```r
revenue_by_region <- function(sales: DataFrame{region: character[], units: integer[], price: double[]}) -> List<F64> {
  totals <- sales |>
    DataFrame.with_columns(revenue = Expr.col("units") * Expr.col("price")) |>
    DataFrame.group_by("region") |>
    GroupBy.agg(total = Expr.sum(Expr.col("revenue"))) |>
    DataFrame.sort("region")
  List.from_r(totals$total)
}
sales <- DataFrame(region = c("north", "south", "north"), units = c(1L, 2L, 3L), price = c(10, 10, 10))
print(revenue_by_region(sales))
#> [40, 20]
```

Three rules cover what such a function may write:

- **Table calls nest.** A call of the DataFrame API that gives a table value may stand anywhere,
  including inside another call's arguments, and an operator with an `Expr` operand
  (`Expr.col("units") * Expr.col("price")`) is such a call. An ordinary R call inside another R
  call's arguments does not compile natively, because R's lazy arguments decide the order they
  run in, and a table call changes nothing that order could show.
- **A column is an R vector.** `totals$total` and `totals[["total"]]` stand only where an R call's
  value may: inside `List.from_r`, `Num.from_r`, `Str.from_r` or `Bool.from_r`, which give the
  column a ry type. `totals[...]` is not available; select rows and columns with the verbs.
- **Numbers cross as for any R call.** An `I64` reaches a table function through `Num.to_r`, so
  `Expr.col("units") >= least` with an `I64` is a `type-mismatch`, and
  `Expr.col("units") >= Num.to_r(least)` is the way to write it.

The functions that read a property of a table instead of giving one (`DataFrame.height`,
`DataFrame.width`, `DataFrame.columns`, `DataFrame.schema`, `DataFrame.key`, `LazyFrame.explain`)
and the ones that write (`DataFrame.set_key`, `DataFrame.write_csv`, `DataFrame.write_parquet`)
are ordinary R calls.

#### data.table queries

DataFrames also accept data.table's bracket syntax for compatibility, and the checker types it on
a DataFrame and on a `data.table` whose columns it knows, such as the result of `fread`. The rest
of this section describes that syntax.

`f[i, j, by]` evaluates `i`, `j`, and `by` with the frame's columns in scope, as data.table does. A
bare name that is a column types as that column's vector, ahead of any lexical binding of the same
name. A name that is no column keeps its lexical type, and a name that is neither is reported:

```text
unresolved

  ! the frame `sales` has no column `amuont`, and nothing else defines that name. Did you mean `amount`?
   --[a.R:6:13]
 6 | print(sales[amuont > 1])
   |             ^^^^^^
```

This is an `unresolved` warning rather than a type error, because R looks a non-column up in the
enclosing scope, so only a name nothing defines is certainly wrong.

When the columns are not known, a local whose value is `NULL` reads as a column of unknown type.
Packages write `time <- nTest <- NULL` before `dt[nTest > 0][order(-time)]` only to silence
R CMD check's "no visible binding" note, so the `NULL` is never the value the query reads. The same
holds inside `[` on a value of no known shape (an unannotated parameter, an `Unknown` result), which
may be a data.table, and it covers everything inside the brackets, nested calls and functions
included. On a vector, `values[order(-time)]` still reports the `NULL`. `.N`, `.GRP`, and `.NGRP` are
`integer`, `.I` is `integer[]`, and `.SD` is the source frame without its group columns, or the
columns `.SDcols` selects (see [Every column at once](#every-column-at-once)). A called
name, such as `sum` in `sum(amount)`, is looked up as a function and never reads a column. A
`..name` read is the variable `name` from the enclosing scope, never a column, and a bare `..name`
as `j` selects the columns it names, which makes the result a `DataFrame` with unknown columns.

The result of the query follows from its arguments:

| Query | Result |
| --- | --- |
| `f[i]`, `f[order(x)]` | the frame type of `f` |
| `f[, x]`, with `x` a column | the column vector |
| `f[, sum(x)]` | the value of `j`, for an atomic or `NULL` value; otherwise `Unknown` |
| `f[, .(a = e1, b = e2)]` or `list(...)` | `DataFrame{a: T1[], b: T2[]}` |
| any `j` with `by` | the group columns first, then the `j` columns |
| `f[, y := v]` | `f` with `y` added, or with its type replaced |

In a `.()` or `list()` `j`, an unnamed bare column keeps its name, `.N` becomes the column `N`, and
any other unnamed item is named by its position, as data.table names it: `f[, .(id, price * 2)]` is
`DataFrame{id: integer[], V2: double[]}`. Under `by`, a bare `.N` as `j` is the column `N`, and any other
unnamed computed `j` becomes the column `V1`. The groups can be written `by = g`,
`by = .(g, h)`, `by = c("g", "h")`, or `by = "g"`, and `keyby` works the same way. A group named
in a string must be a column, so a misspelled one is a type error:

```text
type-mismatch

  x the frame `sales` has no column `taem`. Did you mean `team`?
   --[a.R:8:44]
 8 | print(sales[, .(total = sum(amount)), by = "taem"])
   |                                            ^^^^^^
```

A query's row index `i` must be logical or numeric when its type is known. A frame as `i` is reported
with a hint to add `on =`, because without it data.table joins on a key that ry cannot see. Queries
chain, and each step sees the columns the step before it produced:

```r
sales[amount > 0][, .(total = sum(amount)), by = team][order(-total)]
# DataFrame{team: character[], total: double[]}
```

#### Every column at once

`f[, lapply(.SD, g)]` applies `g` to each column of `.SD`, so its result has one column per column
of `.SD`, each typed as `g` applied to that column alone. Under `by`, the group columns come first:

```r
sales <- DataFrame(team = ["a", "b"], units = [1L, 2L], price = [1.5, 2.5])
sales[, lapply(.SD, sum), by = team]
# DataFrame{team: character[], units: integer[], price: double[]}
sales[, lapply(.SD, round, digits = 1), .SDcols = "price"]
# DataFrame{price: double[]}
```

Because each column is checked on its own, a function that does not fit one column is reported
with that column's name, not against the union of all column types:

```text
type-mismatch

  x this function is passed `character[]`, but its parameter `v` is used as a numeric value (`integer` or `double`), for the column `team` of `.SD`
   --[main.R:2:27]
 1 | sales <- DataFrame(team = ["a", "b"], units = [1L, 2L], price = [1.5, 2.5])
 2 | print(sales[, lapply(.SD, function(v) v * 2)])
   |                           ^^^^^^^^^^^^^^^^^
```

A finding that every column causes is about `g` itself, so it is reported once and without a
column name.

`.SDcols` selects `.SD`'s columns, in the frame's order, in any of these forms:

| `.SDcols` | Columns of `.SD` |
| --- | --- |
| `"a"`, `c("a", "b")` | the named columns |
| `a:b` | the columns from `a` to `b` |
| `is.numeric`, `is.integer`, `is.double`, `is.character`, `is.logical` | the columns of that type |
| any of the above after `!` or `-` | the other columns |

A named column must exist, so a misspelled name in a string or a range is a type error on that
name. `.SDcols` names `.SD`'s columns exactly, so a group column it names stays in `.SD`, and the
result then repeats that column's name, as data.table repeats it. A frame type cannot hold two
columns of one name, so such a result has unknown columns, as does any other `.SDcols` form, such
as `patterns()` or column positions.

`c("a", "b") := lapply(.SD, g)` assigns the applied columns to the named ones in order, and
`(c("a", "b")) := ...` does the same. Column names can also come from a variable, in `.SDcols = cols`
and `(cols) := ...`, when the variable is assigned once, in the same function, to a string or a
`c()` of strings:

```r
relabel <- function(sales) {
  cols <- c("units", "price")
  sales[, (cols) := lapply(.SD, as.character), .SDcols = cols]
}
```

A misspelled name is then reported on its string in the assignment. A variable written more than
once, changed in place (`cols[2] <- "team"`), or assigned in another top-level statement names
columns ry cannot see, so the result has unknown columns.

#### Column updates

`f[, y := v]` is copy-on-write: the statement rebinds `f` with `y` added, or with `y`'s type replaced.
An alias taken earlier keeps the old type, and `y := NULL` removes the column:

```r
sales <- DataFrame(team = ["a", "b"], amount = [1, 2])
before <- sales
sales[, tax := amount * 0.2]    # sales: DataFrame{team: character[], amount: double[], tax: double[]}
before$tax                      # error: the frame `before` has no column `tax`. Its columns are `team`, `amount`
```

The left side may also be a string, `c("a", "b")` paired with a `list()` of values, or the functional
form `` `:=`(a = v, b = w) ``. Any other left side, such as `(columns) := v`, makes the columns
unknown, silently. `f$y <- v` and `f[["y"]] <- v` update a column in the same way.

data.table coerces a value written into an existing column to that column's type, so the column
keeps its type whenever the value does not replace it whole. That is the case with a row index, as in
`f[id > 1, price := 0L]`, with `by`, and with a literal value, as in `f[, price := 0L]`. A value that
replaces the whole column, as in `f[, price := 1:3]`, replaces its type, and a column the statement
creates takes the value's type. Only a literal counts as a single value: a call such as `sum(x)` also
returns one value at runtime, but the checker types `f[, price := sum(id)]` as a replacement.

A value the column keeps its type for must fit it. Strings written into a logical or numeric column
are parsed, so a string that is no number becomes `NA`, and a literal with a fraction written into an
integer column is truncated. data.table only warns about either, but each is a type error here:

```text
type-mismatch

  x column `amount` holds `integer[]`, so this `character` value is parsed as a number, and a string that is not one becomes `NA`
   --[a.R:7:27]
 7 | events[id > 1L, amount := "none"]
   |                           ^^^^^^
```

A number written into a string column is converted without loss, so it is accepted, and a value that
replaces the whole column, such as `f[, amount := as.character(id)]`, replaces its type instead.

The rebinding applies only to a name the current scope already binds: any top-level name, or a
function's own local or parameter. A `:=` on any other name, such as a global updated inside a
function, creates no local binding, so the name keeps resolving to its original definition for
goto-definition, references, and rename. That is what data.table code, which updates a shared table
by reference, needs. When that name is a global frame, later reads in the same function still see
the updated columns, while other top-level code keeps the frame's declared type:

```r
sales <- DataFrame(team = ["a", "b"], amount = [1, 2])
with_tax <- function() {
  sales[, tax := amount * 0.2]
  sales$tax                       # double[]
}
unchanged <- sales                # DataFrame{team: character[], amount: double[]}
```

#### Joins

`x[i, on = conditions]` joins two frames. Each condition pairs a column of `x` with a column of `i`
through `==` or one of the orderings `<`, `<=`, `>`, `>=`, and every form data.table documents is
typed:

| Form | Conditions |
| --- | --- |
| `"id"`, `.(id)`, `c("id")` | `id == id` |
| `"a==b"`, `.(a = b)`, `c(a = "b")` | `a == b` |
| `"id,t>=lo"`, `c("id", "t>=lo")` | `id == id` and `t >= lo` |
| `.(id, t >= lo, t < hi)` | `id == id`, `t >= lo`, and `t < hi` |

Each column a condition names must exist on its side. A missing column is a type error, and in a
condition string the error points at the name inside the string:

```text
type-mismatch

  x the frame `windows` has no column `low`. Its columns are `id`, `lo`, `hi`
   --[a.R:5:38]
 5 | print(events[windows, on = "id, t >= low"])
   |                                      ^^^
```

The two columns of a condition must hold values the join can compare, as data.table requires: numbers
with numbers (an integer column joins a double one), strings with strings, and logicals with
logicals. Any other pair is a type error, and so is an ordering on a column of strings, because only
`==` joins strings:

```text
type-mismatch

  x the join condition `t > label` compares numbers, but `label` is `character[]`. Only `==` joins strings.
   --[a.R:6:32]
 6 | print(events[names, on = .(t > label)])
   |                                ^^^^^
```

A factor column is typed `Any`, so it is not checked. `roll =` keeps the type of the join, and
combining it with an ordering condition is a type error, since a rolling join needs every condition
to be `==`.

The result follows data.table's layout. First come `x`'s columns, where a column a condition compares
takes the values, and so the type, of `i`'s column in its first condition. A further condition on the
same column `t` adds a column `t.1`, then `t.2`, carrying that condition's values of `i`. Last come the
columns of `i` that no condition uses, renamed `i.name` when `x` has the same name. A name that still
repeats takes the first free numeric suffix, as R's `make.unique` gives it:

```r
events <- DataFrame(id = 1:3, t = [1, 2, 3], v = ["a", "b", "c"])
windows <- DataFrame(id = 1:2, lo = [0, 1], hi = [2L, 5L])
events[windows, on = .(id, t >= lo)]           # DataFrame{id: integer[], t: double[], v: character[], hi: integer[]}
events[windows, on = .(t >= lo, t < hi)]       # DataFrame{id: integer[], t: double[], v: character[], t.1: integer[], i.id: integer[]}
```

Inside the join, `j` can also read either side by prefix: `x.t` is `x`'s own `t`, which the join
replaced with `i`'s values, and `i.lo` is the joined frame's `lo`. This works for a compared column
and for a column whose name does not clash. A prefixed name the side does not have is reported like
any other missing column, and a prefixed name in a query that is no join ry can see is a silent
`Unknown`. A join whose `i` is not a frame, or whose `on` is some other form, such as a variable
holding the conditions, is `Unknown`.

`by = .EACHI` runs `j` once per row of `i`. The result's group columns are the compared columns, in
the order of their conditions and named as in the join's layout, followed by `j`'s columns. Within
`j`, a column carrying `i`'s values is that row's single value, while a column of `x` is the vector of
the rows the row matched, and `.N` counts those rows:

```r
counts <- DataFrame(t = [1, 2, 3], v = [10L, 20L, 30L])
counts[windows, on = .(t >= lo), .(n = .N, total = sum(v), wide = if (hi > 2L) "yes" else "no"), by = .EACHI]
# DataFrame{t: double[], n: integer[], total: integer[], wide: character[]}
```

The `if` on `hi` is accepted because `hi` is one value per row of `i`; the same `if` on `v` is a type
error, since `v` is a vector.

#### Columns

`f$x`, `f[["x"]]`, and `f[[1L]]` type as the column. A missing column is a type error that names the
frame and suggests the closest column, like a missing record field:

```text
type-mismatch

  x the frame `sales` has no column `amuont`. Did you mean `amount`?
   --[a.R:7:13]
 7 | print(sales$amuont)
   |             ^^^^^^
```

#### Reading files and data.table's functions

`fread`, `rbindlist`, `melt` and `dcast` return a `data.table`, and the checker sharpens its
columns from the arguments it can see, so the result is a `data.table{...}`. A DataFrame satisfies a
`data.table` parameter, so data.table's functions accept one.

`fread("data/prices.csv")` types with the columns the file has. ry sniffs the head of every `.csv` and
`.tsv` file in the project (gitignored ones included) with the same rules as the runtime's reader,
which follow `fread`: the header, the separator, and each column's type out of `logical`, `integer`,
`double` and `character`. The path is relative to the project root. `fread(text = "...")`, and an input
holding a line break, sniff the literal itself.

```r
prices <- fread("data/prices.csv")   # data.table{id: integer[], ticker: character[], price: double[]}
cheap <- prices[prce < 10]           # warning: the frame `prices` has no column `prce`, ... Did you mean `price`?
```

`select`, `col.names` and `stringsAsFactors = TRUE` are applied to the sniffed columns. A computed
path, a file the project does not have, and any other argument that changes the columns (such as
`colClasses` or `skip`) give a `data.table` with unknown columns. `DataFrame.read_csv` and
`LazyFrame.scan_csv` sniff their file the same way and give a `DataFrame` or `LazyFrame`, and
`read_csv`'s `strings_as_factors` must be a literal `TRUE` or `FALSE` for the columns to be known.

The other functions follow data.table's rules:

| Call | Type |
| --- | --- |
| `setnames(f, old, new)`, `setnames(f, new)` | renames the columns of `f` from here on; `old` must name columns of `f` unless `skip_absent = TRUE`, and `new` alone must name every column |
| `setcolorder(f, c("b", "a"))` | moves the named columns of `f` to the front from here on |
| `setkey(f, a, b)`, `setorder(f, a, -b)`, `setkeyv(f, cols)`, `setorderv(f, cols)` | `f` unchanged; each named column must exist |
| `rbindlist(list(f, g))` | binds by position; each column takes the widest type of its pieces (`logical` < `integer` < `double` < `character`, and a factor with strings stays a factor) |
| `rbindlist(..., use.names = TRUE)`, `rbindlist(..., fill = TRUE)` | binds by name; `fill` adds the columns only some pieces have |
| `rbindlist(..., idcol = "source")` | adds a first column of each piece's name (`character[]`), or its position (`integer[]`) when the list is unnamed |
| `melt(f, id.vars, measure.vars)` | the id columns, `variable: factor` (`character[]` with `variable.factor = FALSE`), and `value` of the measures' widest type; either list defaults to every other column |
| `dcast(...)` | `data.table` |
| `fifelse(test, yes, no, na)` | a vector of the type `yes`, `no` and `na` share; integers and doubles widen to doubles, a bare `NA` fits any type, and any other mix is a type error |
| `shift(x)`, `nafill(x)`, `fcoalesce(x, ...)` | the type of `x` |
| `rleid(...)`, `x %chin% table`, `between(x, lower, upper)`, `uniqueN(x)` | `integer[]`, `logical[]`, `logical[]`, `integer` |
| `tstrsplit(x, split)` | `list[character[]]` |

`setnames` and `setcolorder` change their subject by reference, so ry treats them like `:=`: the name
holds the new columns after the call.

### Conditional stub namespaces: data.table, dplyr, ggplot2 and testthat

Four packages have shipped stubs that do not join name resolution by default:

- `data.table`, with the `data.table` nominal, `fread`, and the `set*()` family;
- `dplyr`, with the `@masked` verbs, the joins, the tidy-select helpers, and the rest of its
  vocabulary;
- `ggplot2`, with the `ggplot` and `gg` nominals, `+.ggplot`, the geoms and scales, and the `@masked`
  `aes`;
- `testthat`, with the expectations and `test_that`.

`tidyr` and `tibble` are conditional the same way. Their shipped stubs declare only the `@masked`
verbs (`pivot_longer`, `drop_na`, `unnest`, `tibble`, `add_column` and the rest), and every other
export comes from the package's export manifest. A column selection such as
`pivot_longer(d, cols = c(a, b))` and a later column read such as `tibble(x = 1:3, y = x * 2)` are
therefore not unresolved names.

R does not attach these packages by default either, and their names must not suppress typo warnings
in projects that never use them. So a conditional namespace activates only when:

- the project declares the package, through a `DESCRIPTION` dependency field or a `NAMESPACE`
  `import` or `importFrom` that names it;
- any project file attaches it, with a `library()`, `require()`, `requireNamespace()`, or
  `loadNamespace()` call whose package argument is a literal name or string; or
- the project ships its own `stubs/<pkg>.Rtypes` override for the namespace.

While a namespace is inactive, it behaves exactly like any package the stubs do not describe.

The shipped dplyr verbs preserve their data argument's class, as `<T> fn(.data: T, ...) -> T`, so a
native-pipe chain keeps its class from end to end: `fread(path) |> mutate(r = a / b)` stays a
`data.table`, and every column reference inside those verbs' `...` stays masked.

A project stub can declare its own masking function with the `@masked` attribute:

```
filter : @masked fn(.data: Any, ...: Any) -> Any
mutate : @masked fn(.data: Any, ...: Any) -> Any
```

A call to a `@masked` name, bare or as `pkg::name`, evaluates the arguments absorbed by its `...`
rest parameter inside the data's frame. An argument that matches a formal declared before the `...`,
such as `.data` above, resolves normally. A declaration whose only parameter is `...`, such as
`join_by : @masked fn(...: Any) -> Any`, masks every argument. A locally defined function of the same
name masks nothing. `@masked` on a declaration that is not variadic is a stub error.

## Object systems (S3, S4, R6)

The checker covers the parts of R's object systems that are written down as declarations, and stays
out of the parts decided at run time from a value's class attribute:

- An operator on a nominal type dispatches statically; see
  [operator methods on a class](#operator-methods-on-a-class).
- A directly called S3 method, such as `speak.dog(x)`, is an ordinary call, checked against that
  function's own signature.
- `UseMethod("speak")`, and any call to an S3 generic, gives `Any`, with no strict-mode finding.
- `structure(list(...), class = "dog")` keeps the argument's type, because a `class` attribute is
  data, not a type, so the record's fields stay checkable. A `dim` attribute is the exception: it
  makes the value an array, whose shape is not tracked, so such a value is `Unknown`.
- `setClass`, `setGeneric`, `setMethod`, and `new` are not modeled, so `new(...)` is `Unknown`.
- `x@slot` reads an S4 slot and types as `Unknown`, and is a strict-mode origin. The subject
  expression is still inferred and counts as a read for naming, the unused check, references, and
  rename. A slot write `x@slot <- v` is an ordinary
  [replacement-form assignment](#replacement-form-assignment) of its base variable.
- `R6Class(...)`, `$new(...)`, and R6 fields and methods are not modeled and are `Unknown`; `self`,
  `private`, and `super` are covered under [names bound at run time](#names-bound-at-run-time).
  In strict mode, an R6 value is an origin where it is first bound, as in
  `account <- Account$new()`.

### Declaring a checked type for your own classes

A class is a [nominal type](#nominal-types) with a representation. Wrapping the constructor is
enough to get slot types, constructor arity, and field access checked on an S4 or R6 class:

#### Inline

```r
type Point = list{x: double, y: double}

setClass("Point", representation(x = "numeric", y = "numeric"))

make_point <- function(x: double, y: double) -> Point {
  @Point(new("Point", x = x, y = y))
}

norm2 <- function(p: Point) -> double sqrt(p$x^2 + p$y^2)

norm2("nope")   # type-mismatch: the argument is not a `Point`
make_point(1)   # type-mismatch: a required argument is missing
```

#### Comments

```r
#: @type Point {list{x: double, y: double}}

setClass("Point", representation(x = "numeric", y = "numeric"))

#: fn(x: double, y: double) -> Point
make_point <- function(x, y) {
  #: @new Point
  new("Point", x = x, y = y)
}

#: fn(p: Point) -> double
norm2 <- function(p) sqrt(p$x^2 + p$y^2)

norm2("nope")   # type-mismatch: the argument is not a `Point`
make_point(1)   # type-mismatch: a required argument is missing
```

The `setClass` call stays opaque, and the annotation is what the checker reads. Operators on the
class work the same way: declare `Arith.Point`, and `p1 + p2` is checked. Method dispatch, on the
other hand, needs the argument's class at the call site, and inside an unannotated
`function(x) speak(x)` that class is not known.

## Strict mode

Strict mode is an opt-in check, switched on with `[check] strict` and off by default. It changes
nothing about inference and adds no typing rules. It reports the places where the checker could not
determine a type, together with the [parameters nothing constrains](#untyped-parameters), and it
escalates unresolved references to errors. It also holds each function written in ry types to
[running natively](#native-functions).

A value typed `Any` by an annotation or a single declaration is an intentional opt-out and never
produces a strict finding. A call that falls back to an overload set's `Any` candidate is the
exception, because the fallback marks a call the declarations could not describe.

Strict mode also reports each read that the
[attached-package tolerance](#package-imports-namespace-and-description) silenced, and points at the
[stub](/development/authoring-stubs.md) that would make it checkable. Without that, a clean run after
`library(unknownpkg)` would look the same as a run that checked nothing.

### Unresolved references escalate to errors

An unresolved reference carries the `unresolved` code, and comes in three kinds:

- a bare name the resolver cannot find in the package, its imports, or the builtins;
- an unknown package namespace in `pkg::name`;
- a name that a known namespace does not export, read as `pkg::name`.

Outside strict mode these are warnings; under strict mode they are errors, whether strict mode comes
from the configuration or from the per-file directive. Turning strict mode on can therefore raise the
severity of findings without changing their count, which matters when a `--min-severity error` gate
reads them.

Two `unresolved` findings are errors in every mode, because they stop the package from loading: a
`NAMESPACE` `importFrom` naming something the namespace does not export, and an `export()` naming
something that is not in the package's namespace. That namespace holds every top-level binding of a
package file, including each target of a chained assignment such as `memoise <- memoize <-
function(f) f`, and every imported name, so a package may re-export what it imports: a name from an
`importFrom`, such as `importFrom(magrittr, "%>%")` with `export("%>%")`, or from an `import(pkg)`
whose namespace exports it. An `import(pkg)` of a namespace without stubs may supply any name, so it
silences the check.

### Per-file directive

A plain top-level comment sets one file's typing mode, overriding the configured `[check]` switches
in both directions:

```r
# typing: strict
```

- `off` silences the file's type errors and strict diagnostics, even when the configuration checks
  types. `on` opts a single file into type checking, with strict mode off. `strict` also switches on
  strict mode for the file.
- The comment must hold nothing but the directive: `# typing: off  # reason` is reported as an
  unknown directive.
- A directive must be a comment between top-level expressions. Inside any expression, such as a
  function body or an `if` block, it is ignored.
- The older `#: @strict` form is still supported: `#: @strict` means `# typing: strict`, and
  `#: @strict off` means `# typing: on`.
- If a file has several directives, the last one wins. A `typing:` comment with any other value is
  reported as an error.
- The directive changes only which diagnostics are published for the file. Inference and every other
  check are untouched, so hover and the other editor features keep working under `off`.

### A package file's top level

Under strict mode, the top level of a library file may hold only definitions, so that loading the
package binds names and registers classes and does nothing else. A library file is a file in the
package's `R/` directory. Every other file is an entry: a script that `ry run` starts, a test file
or helper under `tests/`, and each console command. Entries may run anything at their top level.

A top-level statement of a library file is a definition when it is one of these:

- `name <- value` or `name = value` whose value is a function, a class definition form, or a
  constant (below), including a chain such as `a <- b <- function(x) x`. zeallot's
  `c(a, b) %<-% value` counts the same way.
- A call to a class definition form: `setClass`, `setClassUnion`, `setGeneric`, `setMethod`,
  `setReplaceMethod`, `setValidity`, `setOldClass`, `setAs`, `setRefClass`, or `R6Class`, bare or
  namespace-qualified. Their arguments are not inspected.
- A call that imports a package (`library`, `require`, `requireNamespace`, `loadNamespace`,
  `attachNamespace`) or only declares something (`globalVariables`, `suppressForeignCheck`,
  `delayedAssign`, `makeActiveBinding`, `.S3method`, `registerS3method`).
- A `type` or `alias` definition, or an expression with no effect, such as `NULL`.
- An `if` whose condition has no effect, or is an import call such as
  `requireNamespace("x", quietly = TRUE)` (negated or not), and whose branches are definitions, or a
  `{` block of definitions.

A constant's initializer must have no effect. Literals, names, `pkg::name`, function literals,
formulas, and the built-in operators have none. A call has none when its function is declared pure
and its arguments have none; the arguments of `quote`, `expression`, `alist` and `substitute` are not
evaluated, so they are not inspected. Inside `local()`, assignments and loops touch only the local
environment and are allowed, but a call to a function bound inside that `local()` is an effect,
because nothing declares it pure. A replacement inside `local()` of a name bound outside it, such as
`local({ defaults$a <- 2; defaults })`, is allowed when the project binds that name once, at the top
level, to a literal or to `c()` or `list()` of literals. R then replaces in a local copy, which leaves
the outer value alone. Any other outer value might be an environment, which the replacement would
change, so it is an effect.

Anything else is an effect, which is a `strict` error reported on the expression that causes it.
Only the first effect of a statement is reported. The effects are:

- a call to a function that is not declared pure, including a `%op%` operator;
- a call whose function is computed, such as `handlers[[1]]()`;
- a `for`, `while` or `repeat` loop outside `local()`;
- `<<-`, which assigns outside the package namespace;
- a replacement such as `names(x) <- value` or `x$field <- value`, which changes a value after its
  definition;
- an assignment nested inside an expression, such as `f(x <- 1)`;
- `?`, which looks up help.

#### Purity

A function is pure when calling it has no effect beyond returning a value, whatever its arguments.
Purity is declared and never inferred, and the declaration is trusted: ry does not check the body.
A project function is declared pure with a `#: @pure` comment line above its definition or an inline
`@pure` before `function` (or `\(x)`), and a stub declares one with `name : @pure fn(...)`. With
inline annotations turned off, an inline `@pure` declares nothing and carries the `inline-annotation`
warning. The
standard library's stubs mark base R's pure functions, such as `paste0`, `seq_len` and `sum`, and
`c`, `list`, `switch`, `expression` and `alist` are pure without a stub.

A project definition of a name shadows the stub's declaration, so a package's own `paste0` is pure
only if it is marked. A bare call to a stub-declared function takes its purity from the declaration
the name resolves to, the same one its type comes from: when two packages declare the same name, the
later one wins, and its marker alone decides. `pkg::name` asks the named package's declaration. A function defined inside a condition, such as `if (cond) f <- function() 1`,
is never pure, because which definition exists depends on the condition.

Purity belongs to each definition alone. Adding `cat()` to the body of a function marked `@pure`
re-checks only that function, and removing the marker re-checks only the statements that call it.

#### Lazy constants

`ry load` binds a library file's functions lazily, and under strict mode its constants too: a constant
whose name has exactly one top-level writer becomes a promise that evaluates its initializer on first
use. Every package name the initializer mentions must also be written exactly once, by a statement
earlier in collation order, and otherwise the constant runs eagerly in order. A `<<-` anywhere in a
package function counts as a writer of its target that comes after every top-level statement,
because the namespace locks once loading finishes and such a write can only land while `.onLoad`, or
something it calls, runs. Because the initializer
has no effect and what it reads cannot change after it, evaluating it later gives the value a load
would have computed. A reload binds the constant again whenever anything its initializer reaches changed, such
as the body of a pure function it calls.

### Untyped parameters

A parameter without an annotation is reported when nothing constrains it, because it then accepts
any value unchecked. That is the case when its inferred type is `Unknown`, or is still a fresh type
variable of its own function that neither another parameter nor the return type mentions:

```r
describe <- function(x) cat("a value\n")
```

```text
x strict mode: parameter `x` has no type. How the function uses it does not determine one, so any
  value is accepted unchecked. Annotate it, as in `x: TYPE`
```

A type variable that the signature mentions twice is genuine polymorphism, so `function(x) x`
(`<T> fn(x: T) -> T`) and `function(flag, a, b) if (flag) a else b` are not reported. Neither is a
constrained variable such as `<T: numeric>`, a variable tied to an enclosing function, such as the
inner `x` in `function(f) function(x) f(x)`. A lambda passed as an argument is not judged at all,
because the call gives its parameters their types only after the lambda is inferred. A `...` formal is
never reported, and a default does not count as a type, because an unannotated parameter takes its
type from its uses. Annotate a parameter that really accepts anything as `Any`, which strict mode
treats as a deliberate choice.

The parameter finding is about the declaration, so it can stand beside an origin in the body that it
feeds, as in `function(node) node$value`, where annotating `node` would fix both.

Returns and bindings are not reported separately. An undetermined return or binding always traces
back to one of the origins below, a type error, or a reference to a project binding whose own
definition is reported, so reporting the declaration too would repeat that finding.

### Where an undetermined type is reported

An undetermined value is reported once, where it first became undetermined, not at every later
expression that carries it. There are three such origins: a construct the type system does not
describe, a reference to a binding whose type is not known, and a recursive definition that could not
be typed. A declaration whose return type is `Unknown` produces no finding at its call sites, and an
`Unknown` nested inside a larger type is not reported either.

A reference to a binding defined in this project is not an origin; the binding's own definition is
reported instead, so one undetermined value does not produce a finding in every file that reads it.
An unresolved bare name is not an origin either, because naming already reports it. An unresolved
`pkg::name` is currently reported both ways. A value under any `#:` annotation (checked, `@trust`,
`@if-unknown`, or `@new`) is not an origin, because the annotation gives it a type, and neither is
anything inside that value: `#: double[]` above `x <- as.numeric(df$age)` covers `df$age`. A function
literal or a braced block inside the value keeps its own origins, because its statements can be
annotated where they are.

### Native functions

In strict mode, a function whose signature is written entirely in ry types is a *native function*.
It is compiled to machine code, and its body may hold only ry values. `ry check` reports each
construct that would send it to the interpreter instead, under one of two codes:

| Code | Severity | What it marks |
| --- | --- | --- |
| `native` | error | an R value used outside a conversion, which breaks the rule |
| `interpreted` | warning | legitimate ry that the native compiler does not compile yet |

A native function with neither finding runs natively. This is a `native` error:

```r
label_width <- function(label: Str) -> I64 {
  width <- nchar(label)
  Num.from_r(width)
}
print(label_width("native"))
```

```text
native

  x `nchar` is an R function, and a native function holds only ry values, so its result cannot be
    used here. Convert the result where it returns: `Num.from_r(nchar(label))`
```

**Which types are ry types.** The ry types are `I64`, `F64`, `Bool` and `Str`, `List<T>`, `Set<T>`
and `Dict<K, V>`, records, tuples, tags and tag unions, nominal types over those, type parameters,
function types whose parameters and result are ry types, and the table types `DataFrame`,
`LazyFrame`, `GroupBy`, `LazyGroupBy` and `Expr`. `NULL` alone is neither. Every other type is an R
type: `double`, `integer`, `character`, `logical`, R vectors such as `double[]`, R lists,
`data.frame`, classes, `Any` and `Unknown`.

**Which functions are judged.** A function literal is a native function when every parameter is
annotated with a ry type, the declared result is a ry type, `NULL` or left out, and at least one of
them is a ry type. A signature written in a `#:` comment, or on the name the function is assigned
to, is judged by the same rules and compiles exactly like the inline form
([Annotations at run time](#annotations-at-run-time)). The one exception is a signature that is
only the name of a type alias. The runtime reads the types where they are written, so such a
function runs in the interpreter and gets an `interpreted` warning that asks for the function type
in place of the alias.

A type parameter bounded by an R type, as in `<T: numeric>`, counts as an R type.

A function with an R type anywhere in its signature is a *boundary function*. It is where R values
and ry values meet, it runs in the interpreter when it has to, and it is not judged. So an R type in
the signature is how a function opts out: `function(path: character) -> F64` may read a file with
any R code and hand a ry value back. A function with an unannotated parameter is not judged either.
A function literal without annotations is judged as part of the native function whose body holds
it, and not at all anywhere else.

**What a native function may do with R.** An *R function* is any function that is not a ry
[standard library](/reference/standard-library.md) function, a
[table function](/reference/dataframes.md) that gives a table, a group or an expression, another
native function of the project, or a local function. A boundary function and an unannotated
project function count as R functions when a native function calls them. A native function calls
an R function only in these positions:

1. directly as the argument of `Num.from_r`, `Str.from_r`, `Bool.from_r` or `List.from_r`, which
   turns the result into a ry value;
2. as a statement whose value nothing reads, which is not the last expression of the function;
3. as `stop(...)`, whose arguments may hold anything.

Each argument of such a call is a ry value that shares R's representation (an `F64`, `Bool` or
`Str`, or a list of them), an R literal such as `42L`, or `Num.to_r(x)` or `List.to_r(x)` written
directly as the argument. The arguments of a table function follow the same rule, and so do the
operands of an operator that builds an `Expr`, as in `Expr.col("units") >= Num.to_r(least)`; they
may also be table values and nested table calls
([Tables in typed code](#tables-in-typed-code)). This function is native:

```r
simulate <- function(draws: I64, label: Str) -> F64 {
  set.seed(42L)
  noise <- List.from_r(stats::rnorm(Num.to_r(draws)))
  if (List.is_empty(noise)) stop("no draws for ", toupper(label))
  cat(label, List.sum(noise), "\n")
  List.sum(noise) / Num.to_f64(draws)
}
print(simulate(4, "noise"))
```

```text
1 file checked, no problems
```

An operator applied to ry values is native. So is an operator with an `Expr` operand, which builds
a bigger expression, and its other operand may be an R literal: `Expr.col("units") > 3L`.

#### What is reported

Each function is judged on its own body, so a function that calls a blocked native function gets no
finding for the call. An R value is reported once, where it first appears, and not again at each
expression it flows into.

**An R call whose value is used.** The first example shows it. The fix names the conversion that
fits the R function's result type, when the checker knows it.

**An R call inside the arguments of another R call.** R evaluates an argument only when the function
reads it, so native code cannot run the two calls in a fixed order. A conversion around the inner
call does not change that, and neither does a table function on the outside, so
`cat(Str.from_r(format(amount)))` is reported the same way:

```r
report <- function(label: Str, amount: F64) -> NULL {
  cat(label, format(amount, nsmall = 2), "\n")
  NULL
}
report("total", 12.5)
```

```text
native

  x this calls R's `format` inside the arguments of R's `cat`. R evaluates an argument only when the
    function reads it, so native code cannot run the two in a fixed order. Compute the inner call
    into a variable first, as in `value <- Str.from_r(format(...))`, and pass the variable
```

**A variable that holds an R value.** A native function reads its own parameters and variables. A
global that holds an R value is converted once, outside, and passed in:

```r
#: character
unit <- Sys.getenv("UNIT")
report <- function(amount: F64) -> NULL {
  cat(amount, unit, "\n")
  NULL
}
report(2.5)
```

```text
native

  x `unit` comes from outside the function and holds an R value, and a native function holds only ry
    values. Convert it once where it is made, as in `Str.from_r(...)`, and pass the ry value in as a
    parameter
```

**A boundary function called for its value.** It may return any R value its body builds, so its
result converts like an R call's:

```r
read_rate <- function(path: character) -> F64 {
  Num.from_r(as.numeric(readLines(path)))
}
taxed <- function(amount: F64) -> F64 amount * (1 + read_rate("rate.txt"))
print(taxed(100))
```

```text
native

  x `read_rate` has an R type in its signature, so here it counts as an R function, and a native
    function holds only ry values, so its result cannot be used here. Convert the result where it
    returns: `Num.from_r(read_rate("rate.txt"))`
```

**A column read.** `table$column` and `table[["column"]]` give an R vector, so they stand directly
inside a conversion. The table functions that give an R value do too: `DataFrame.height`,
`DataFrame.width`, `DataFrame.columns`, `DataFrame.schema`, `DataFrame.key`, `DataFrame.set_key`,
`DataFrame.write_csv`, `DataFrame.write_parquet` and `LazyFrame.explain`.

```r
total <- function(sales: DataFrame{units: integer[], price: double[]}) -> F64 {
  units <- sales$units
  List.sum(List.from_r(sales$price))
}
```

```text
native

  x reading a column gives an R vector, and a native function holds only ry values. Convert it where
    it is read: `List.from_r(sales$units)`
```

**An R value written as a literal or an operator.** `a:b` builds an R vector, and `NA` and complex
literals have no ry type, so each is a `native` error. Write `List.range(a, b)`, and use a `Result`
or a tag for a missing value. `Num.to_r` and `List.to_r` give an R value too, so they stand directly
inside the arguments of an R call.

**A construct that is not compiled natively yet.** The program is legitimate ry and runs with the
same results, but the function that holds the construct runs in the interpreter. The finding is an
`interpreted` warning, and each message gives the way to write the step that compiles:

```r
count_up <- function(limit: I64) -> I64 {
  total <- 0
  step <- function(amount: I64) -> NULL {
    total <<- total + amount
    NULL
  }
  step(limit)
  total
}
print(count_up(2))
```

```text
interpreted

  ! this function runs in the interpreter, because `<<-` is not compiled natively yet: a native
    function changes only its own variables. Return the new value and assign it in the caller
```

| Construct | What to write instead |
| --- | --- |
| a function with `...` | name each parameter, or take one `List` |
| a parameter that takes a function, a function literal used as a value, a call of a variable that holds a function | define the function inside the native function, or pass the literal straight to a standard library function such as `List.map` |
| a standard library function passed by name, as in `List.map(xs, Num.to_f64)` | wrap it: `function(x: I64) -> F64 Num.to_f64(x)` |
| a standard library function without native code, such as `List.drop_at` | a loop or another standard library function |
| parameter types in a `#:` comment or on the assigned name, as in `f: fn(x: I64) -> I64 <- function(x) x` | write the types on the parameters |
| a call of a typed or standard library function with named arguments, or one that leaves a default out | pass every argument by position |
| a standard library function called with a `ry::` prefix | the name without the prefix |
| an `I64`, a `List<I64>`, a `Dict` or a `Set` passed to an R function as it is | `Num.to_r(x)`, `List.to_r(xs)`, `Dict.keys` and `Dict.values`, or `Set.to_list` |
| `<<-`, and an assignment to anything but a variable or `xs[[i]]` | return the new value; build a new record with `(..record, field = value)` |
| a local function defined inside a branch or a loop, and `return` inside a local function | define it once at the top, and end it with its value |
| a name first set inside a branch or a loop and read after it | set it before the branch |
| a variable, a parameter or a loop variable that holds values of different types, branches that set a name to different types, and a variable that holds a tag and is assigned again | a new name for each value |
| the value of an `if` without `else` | an `else` branch that gives a value of the same type |
| `xs[i]` with a position, which takes a part of a list | `xs[[i]]` for one item, `List.sublist` for a part |
| a column read by its position, as in `table[[2]]` | the column's name: `table[["price"]]` |
| a table value inside a record, a tuple, a tag or a list | a variable of its own for the table value |
| an operator applied directly to a table expression that a local function, a function whose result type is an alias, an `if` or a `match` gives | assign the expression to a variable, and apply the operator to the variable |
| a `Dict` whose keys or values are not `I64`, `F64` or `Str` | keep the values in a `List` and store their positions |
| `try` | `match` on the result, and return the `:Err` from its arm |
| a `match` on a list or a scalar (so every list pattern), a nested pattern, and an arm with an `if` guard | match a tag, a record or a tuple, and test inside the arm |
| a read of a global that holds a ry value, or of a variable of an enclosing boundary function | pass the value in as a parameter |
| a function that ends in a loop or another expression whose value R returns invisibly | end with the value, or with `NULL` |

The rule covers the function's body. How R code calls a native function is not checked, so these
calls from the interpreter run in the interpreter with no finding:

- a call that passes a function, or an argument that runs R code to compute (anything but a
  constant, a variable, arithmetic of them, and list, record, tuple and tag literals of them);
- a call that passes a variable to a native function that calls R, because that R code could change
  the variable before R would read the argument;
- the first call of a native function that calls into a namespace R has not loaded yet, such as
  `tools::file_ext`, or that converts a value whose type the checker does not know, with
  `Num.from_r` or with a `List.from_r` such as `List.from_r(get("prices"))`: the interpreter runs
  that call once, which loads the namespace or gives the type, and later calls run natively;
- a call in which such a conversion gives a type other than the one it gave before. The native code
  stops there, and the interpreter runs the call again from the start, with each R call the native
  code already made giving the value it gave then instead of running a second time, so what those
  calls printed or assigned happens once. From then on the conversion's type is not known before
  it runs, so every call of the function runs in the interpreter;
- a call of a function that returns a `Dict` or a `Set`.

A native function called from another native function has none of these limits.
`RY_TYPED_LOG=1` prints each such call with its reason.

### Diagnostics

Strict diagnostics carry the code `strict`, so they can be filtered separately from type errors. Each
origin is reported once, at the exact range of the originating expression. A binding and a bare
expression are worded differently, because a binding can be annotated and a bare expression cannot.
An R value in a [native function](#native-functions) carries the code `native`. All three are
errors, and `ry run` refuses to start a program that has one. A construct that sends a native
function to the interpreter carries the code `interpreted` and is a warning, so the program runs.

## Syntax errors

A file with syntax errors is still analyzed, under one rule: a broken region reports its syntax error
and, strict mode aside, nothing else, because the checker draws no conclusions from source it could
not read.

- Every well-formed statement in the file is analyzed normally. Definitions keep their exports,
  references resolve, and a genuine type error outside the broken region still surfaces.
- A broken statement contributes nothing: no names, no reads, and no diagnostics beyond the syntax
  error covering it. Strict mode is the exception, and can still report an undetermined type there.
- An unterminated argument or parameter list ends at the next statement, so the mistake stays on the
  line that made it. A list that runs onto the next line is ordinary R, and a fragment there such as
  `beta)` really is a forgotten separator and is reported as one. But a line that assigns is the next
  statement, because adopting it would report a "missing separator" on that line and every line after
  it, and cost each adopted line its own definitions.
- A broken assignment whose name side is intact keeps its definition. The value becomes a hole that
  types as `Unknown`, so its dependents neither lose resolution nor see a wrong type while the value
  is being edited. The hole is not a strict-mode origin, because the syntax error already marks it.
- A checked annotation on such a broken definition binds its declared type without checking it, so
  the definition keeps its contract for callers until the value parses again, and is then checked
  against the annotation as usual.

## Limitations

Most gaps are silent, because a value the checker cannot type is `Unknown` and its checks are
skipped. [Strict mode](#strict-mode) reports most of the places they occur.

Not checked:

- **Base data frame columns.** Everything read out of a `data.frame` is `Unknown`, so `df$whatever`
  passes even if the column does not exist. A [`DataFrame`](#dataframes) types its columns.
- **Matrix dimensions.** Matrix arithmetic is checked, but a non-conformable product is not.
  Indexing with several indices, as in `m[i, j]`, or with `drop = FALSE` gives `Unknown`.
- **S4 and R6 objects** are `Unknown`, and calls to an S3 generic that dispatches through
  `UseMethod()` return `Any`. Operator methods such as `+.Date` and methods called directly are
  checked.
- **Packages without a stub.** Their names are `Unknown`, and attaching one switches off
  unresolved-name reports for the whole project.
- **`$` on an atomic vector in a package that defines a `$` method**, because a classed vector may
  carry that method.
- **Some paths a test elsewhere in the body rules out.** A list member beside a number in
  arithmetic, a list or `NULL` beside an operand of unknown type, the `NULL` of a computed list
  field used as a `:` endpoint, and the logical member in the false branch of `isTRUE()` or
  `isFALSE()` are not reported, because correct R usually guards them in ways the checker cannot
  follow.
- **A placeholder local**, a variable whose only visible value is `NULL` or a bare `NA`, filled
  later by `assign()` or `<<-`, where it is passed as an argument or tested as a condition.
- **A project's own `%op%` operators**, because one may quote its right operand, as magrittr's `%>%`
  does.

Known bugs, where correct code is reported:

- **A bare `NA` under a declared return type.** A function declared `-> character` that returns
  `NA` on one path is reported, because `NA` is `logical`. Return `NA_character_` instead.
- **A trailing comma for rlang's dynamic dots.** dplyr's verbs accept `mutate(d, y = 1, )`, but the
  trailing comma is reported as it is for `c(1, 2, )`.
- **Package-qualified calls to a package ry does not know.** `pkg::fun()` reports an unknown
  namespace when ry has no stub or export list for `pkg`, even if a file calls `library(pkg)`.
- **A generic function passed inline as an argument.** `lapply(xs, function<T>(v: T) -> T v)` is
  reported, because type parameters on a function that is not bound to a name are not
  instantiated. Leave the function's types off, or bind it to a name first.
