Skip to content
ry

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 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 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). 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.

Annotations are written in two ways that share one type grammar: in #: comments, described here, and inline, 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:

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 written as @param and @return lines, or a definition block of @type, @alias and @opaque lines.

value: integer <- 1L
double_count <- function(count: integer) -> integer 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:

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

A block attaches to the expression that starts on the line directly after it. A braceless function body, a braceless if branch, a parenthesised expression, and an argument are valid targets. In an argument list the block types the argument’s value, so a lambda gets its signature where it is passed:

#: fn(m: matrix) -> double[]
row_sums <- function(m) apply(
m, 1,
#: fn(row: double[]) -> double
function(row) sum(row)
)

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. A roxygen2 #' line is a plain comment here, so the #: block goes below the roxygen block, directly above the definition;
  • the block follows code on its own line, as in x <- 1 #: integer or x <- 1; #: integer, which would otherwise read as an annotation on the next line’s statement;
  • the block has no content beyond the #: marker.

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

A block is refused as a whole when it mixes forms, repeats a directive other than @param, 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. An annotation that names an undeclared type, or writes X[] over an element that is not atomic (Rec[] with Rec a record alias), is refused the same way, so the code it covers is typed as if it had no annotation. A block the annotation grammar could not read at all, such as the bare optional parameter in fn(integer, [character]), is refused silently, because the parse error has already said what was wrong.

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

count: integer <- 0L
add <- function(x: integer, y: integer = 1L) -> integer {
x + y
}
first <- function<T>(items: list[T]) -> T 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, 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 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). 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.

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: count: integer <- 0L is #: integer above count <- 0L.
  • A function’s inline types form a compact annotation naming the annotated parameters, so function(x: integer, y) is #: fn(x: integer) over function(x, y). 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, alias and opaque definitions are the @type, @alias and @opaque 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 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.

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, alias and opaque 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:

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.

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, alias and opaque 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}.

ry build --plain-r keeps the types instead of deleting them: each statement’s inline annotations become a #: block above it, so count: integer <- 0L is written as #: integer over count <- 0L, a function’s signature as #: <T> fn(x: T, [y]: double) -> T, @pure as a #: @pure line, and a statement’s value @Name(value) as #: @new Name. An annotation with no statement to sit above, such as the signature of a function passed as an argument, is erased (the CLI reference lists the cases).

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 or opaque), 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:

#: fn(price: double, rate: double) -> double
apply_discount <- function(price: integer, rate) price * (1 - rate)
! 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

[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.

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:

scale <- function(values: double, by: double) -> double values * by
scale("a", 1)
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): a type written on the function wins, then the function type on the name it is assigned to, then the #: block attached 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 in any of the three forms.

#: fn(values: double, by: double) -> double
scale <- function(values, by) values * by
halve: fn(value: double) -> double <- function(value) value / 2
halve("a")
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.

print shows the annotations; deparse does not. A function that keeps no source references, such as one from an installed package or, by default, any function under ry run, prints from its code, and print writes the signature’s types and type parameters into it. deparse and dput write the erasure, because they produce R code that another R may read:

scale <- function(values: double, by: double = 1) -> double values * by
scale
deparse(scale)
twice <- function<T: numeric>(y: T) -> T y * 2
twice
function (values: double, by: double = 1) -> double
values * by
[1] "function (values, by = 1) " "values * by"
function<T: numeric> (y: T) -> T
y * 2

Two 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.
  • 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.

A signature that is only the name of a type alias, as in #: Scaler with #: @alias Scaler {fn(values: double, by: double) -> double}, is checked and compiled like the function type it names, because ry run, the console, ry load, ry install, ry build and a parse of a file on ry’s runtime write that type out in place of the name before the code runs. Code parsed from text, such as parse(text = ) or eval(str2lang()), is not rewritten, so there such a function has no run-time checks and runs in the interpreter.

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).

  • 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.

  • A logical vector holding only NA arrives as character where the type is character. A bare NA and a vector computed from no data, such as ifelse() over an empty test, are logical in R, but the checker lets them stand for any atomic type. integer, double and complex admit logical storage as it is, while a character parameter or return value converts such a value, keeping its attributes, so typeof() on it says "character" where GNU R running the erasure says "logical". Every other check passes the value through unchanged, except the I64 conversion described under number literals.

    label <- function(x: double[]) -> character[] ifelse(x > 0, "positive", "other")
    label(double())
    character(0)
  • 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), so an installed function with a parameter p: Point, where alias Point = Record{x: F64, y: F64}, checks p as a record. An annotation that spans lines stays 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. A missing argument the caller passes on stays missing, so missing() in the callee is TRUE, as in GNU R. An argument written in R code stays lazy, also when a typed function passes it on as ... (one it names, such as ..1, is computed first): R computes it where the body first reads the parameter, so an R call the body makes before that read can change what it is. With y <- 1 and rebind <- function() y <<- 100, twice <- function(x: F64) -> F64 { rebind(); x * 2 } gives 200 for twice(y), compiled or not. Native code computes an R call argument, such as step(as.double(i)), at entry when the body reads the parameter before it runs any other code, because R would compute it at that point too. A read reaches into the arguments of a call of a builtin or a typed function, which take their arguments left to right, but the call itself ends the reads: x + sqrt(y) reads x and then y, and sqrt(x) + y reads only x. An if, &&, ||, <-, = or match ends the reads after its condition, value or scrutinee, and a call of an R closure, a name that is not a parameter, a named or empty argument and ... end them at once. Every parameter up to the last of these arguments must be passed, since a default runs code. A body that is nothing but reads, such as function(x: F64) -> F64 x or return(x), reads nothing this way, so that ident(invisible(1)) keeps R’s visibility. The argument’s code runs in a frame for the call, after the entry checks, and swapped <- function(a: F64, b: F64) -> F64 b - a computes b’s argument before a’s. Otherwise the call runs in the interpreter, which computes the argument at the read. Argument code that rebinds a function the body calls differs from R in one case: when the body looked the function up before it read that argument, as h(a) does, R calls the function it found and ry calls the new one.

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)
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 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:

> 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 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.

  • 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.

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

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
  • 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.

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} ``.

  • 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 closed 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.

A record type ending in .. is open: list{tick: fn() -> NULL, ..} asks for a tick field and accepts a record with more fields. It types a dependency by what the code uses from it, so a fake built for a test may carry extra fields:

#: fn(t: list{tick: fn() -> NULL, ..}) -> NULL
run <- function(t) t$tick()
run(list(tick = function() NULL, finished = TRUE)) # accepted
run(list(tock = function() NULL)) # error: expected a field `tick` here, and this list has `tock` instead

A closed record never takes .. implicitly, so list{id: integer} still reports a surplus or misspelled field. Through an open record, $ and [[ read the listed fields by name. A name it does not list reads as Unknown (the field may or may not be there), except a near miss of a listed field, which is reported as a typo. A positional [[ and a [ subset read Unknown, because the listed fields need not be the first ones. An open record does not pass its unlisted fields through: fn(t: list{tick: fn() -> NULL, ..}) -> list{tick: fn() -> NULL, ..} returns only what it lists. Every item of an open record is named. A data.frame{...} or data.table{...} type lists every column, and only ry’s own Record{...} and DataFrame{...} types pass unlisted fields or columns through, with a row.

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 describes.

new.env(), environment() and globalenv() have the type environment, whose bindings are not typed: $ on it reads Unknown. An environment{name: TYPE, ...} type lists the bindings an environment may hold, which types the mutable state R code keeps in one, such as a counter or a cache:

count <- function() -> integer {
#: environment{count: integer}
calls <- new.env()
calls$count <- 0L
calls$count <- calls$count + 1L
calls$count # integer
}

new.env() fits any environment{...} type, and a typed environment passes wherever an environment is expected. An environment is mutable, so a write never changes its type: calls$count <- "many" is an error against integer, and a binding the type does not list can be neither written nor read (calls$total <- 1L is an error that asks to add total: TYPE). $ and [[ with a literal name read the listed bindings. Two typed environments fit each other only when they list the same bindings with the same types, because a write through either one changes both. The type lists every binding, so it cannot end in ...

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 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 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 reports where an Unknown arose, and treats an Any as an intentional opt-out.

Type parameters, aliases, and nominal types

Section titled “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.

A function signature’s type parameters are in scope in the function’s body, so an annotation there can name them. The body sees each parameter as one fixed type, the one the caller chose, so a value of another type is an error even when it would fit some other choice:

twice <- function<T: numeric>(y: T) -> T {
doubled: T <- y + y
doubled
}

In #: <T, U> fn(x: T, y: U) -> T, the body annotation #: T on kept <- y reports “expected T, found U”. A nested function reads the type parameters of every signature around it, and a signature only ry inferred binds no name, so #: T in an unannotated function is an unknown type.

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 whose arithmetic takes two of its values, which an operator method such as "+.Money" <- function(e1: Money, e2: Money) declares.
  • arithmetic admits everything numeric does and any class that declares an arithmetic operator method at all, such as Date, whose +.Date adds a number to a date. add_them(day, day) under <T: numeric> fn(a: T, b: T) -> T reports “expected a numeric value (integer or double) or a class with arithmetic between two of its values, found Date”, as R stops on day + day.
  • num admits everything numeric does and the ry numbers I64 and F64.
  • arithmetic or number admits everything arithmetic does and I64 and F64.
  • arithmetic or F64 admits everything arithmetic does and F64.
  • numeric or F64 admits everything numeric does and F64.
  • 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 can hold: a number, a Bool, a Str, or another ry value. List.from_r uses it to type a list[T] argument.
  • eq admits every value but a function or an environment: the values == compares.
  • comparable admits the R values a comparison takes: an atomic value other than complex or raw in any vector shape, a list, which R compares element by element, and a class.
  • equatable admits what comparable does and complex and raw, which R tests for equality but does not order.
  • ordered admits the ry values with an order: I64, F64 and Str. A number literal passed for an ordered parameter is a ry number, and a string literal a Str.
  • comparable or number admits everything comparable does and I64 and F64.
  • comparable or Str admits everything comparable does and Str.
  • comparable or ordered admits everything comparable does and what ordered does.
  • equatable or number and equatable or Str admit everything equatable does and the ry numbers or Str.

The constraints named ... or ... join an R constraint and a ry one, and they are what unannotated arithmetic and comparisons infer, with a result written Promoted<T>, Subtracted<T>, Compared<T> or Compared<T, U> when R and ry give different results:

Type T a ry value T a class T another R value
Promoted<T> T T, for a class with arithmetic double
Subtracted<T> T T for a class with arithmetic between two of its values, else the class its - method gives for two of it double
Compared<T> Bool, or List<Bool> for a List logical logical

Compared<T, U> is a comparison of two different open values: the longer of Compared<T> and Compared<U>, because R recycles the shorter operand. It is logical[] when either side is a vector, and Bool (or List<Bool>) when either side is a ry value, since the other side must then be the same ry type.

So function(x) x * 2 is <T: arithmetic or number> fn(x: T) -> Promoted<T>: it gives an I64 for an I64, as x * 2 on an I64 does in ry, a double for an integer, as R does, and a matrix for a matrix, because R keeps the class through its arithmetic methods. Subtracted<T> is the difference of two values of one type, so it gives a difftime for two dates, as the stubs’ -.Date does. The three may be written in an annotation too.

A class keeps its type under Promoted<T> when it declares any arithmetic method, whichever operator the method covers. This is a known gap: R refuses some of these operations (x * 2 on a Date, / between two difftimes), and ry types them as the class instead of reporting them.

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, and the message names the constraint: middle("a") under <N: scalar numeric> reports “expected a scalar numeric value (integer or double), found character”. A printed signature names a declared type parameter as the annotation spells it, and an inferred one T, U and so on in order of appearance. A call’s message prints the parameter as the fresh variable the call instantiated, so wrap(gh) under <R> fn(f: fn(...: double) -> R) -> R expects fn(...: double) -> T. A union satisfies a constraint when every member does, so double | integer satisfies numeric, and an undetermined member takes the constraint: a NULL default replaced by a number, T | double, passed where a number is needed makes T a number. 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 binder may carry a type instead of a constraint, written NAME: TYPE. The binder then stands for one type that fits its bound, and the signature can name that type again:

#: <T, U: list[T] | T[]> fn(path: U) -> U
normalize <- function(path) {
vapply(path, nchar, 1L)
path
}
one <- normalize("a") # character
many <- normalize(list("a", "b")) # list{character, character}

Written fn(path: list[T] | T[]) -> list[T] | T[], the signature would return the whole union to every caller. The body may use the parameter wherever its bound fits, and an argument outside the bound, such as normalize(sum), is a type error at the call. A bound whose every member meets a constraint meets it too, so under <N: integer | double> fn(x: N) -> N the body x + x is arithmetic and has the type N. A bound with a logical member does its arithmetic as the bound itself, because R promotes the logical member: under <N: integer | logical> fn(x: N) -> N, x + x is integer, and returning it as N is a type error. @forall T, U: list[T] | T[] and function<T, U: list[T] | T[]>(path: U) -> U declare the same binders. A bound that is a single name reads as a constraint, so a type bound is a union or a compound type such as list[T].

Inference gives an unannotated parameter the same shape when it meets a union and flows to the return: the normalize above infers exactly the declared signature. A parameter that does not reach the return keeps the union, as in <T> fn(path: list[T] | T[]) -> integer. A parameter that meets two unions keeps the members of the first that fit the second, so integer | logical and then character | logical leave logical, and two unions with no common member are a type error at the second use.

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. Arithmetic between two different constrained parameters, a / b under <T: numeric, U: numeric> fn(a: T, b: U) -> double, is double, R’s widest numeric, because neither parameter’s type fixes the other’s. The same holds for any two distinct type parameters, and for an unannotated parameter that a scalar use bounds, such as n in for (i in 1:n): x + n is double, so a call passing 1L and 2.5 checks. A body under a plain <T> that does arithmetic is a type error, and atomic does not imply numeric. Under <T: arithmetic> fn(x: T) -> T, x + 1 checks and x + x is a type error that says to declare <T: num>, because a T such as Date adds a number and not another Date. Unary minus asks num too, as R has no - on a single Date. Under <T: num>, x - x is a T, because num admits no class, and x / x is a type error that says to declare <T: numeric>, because an F64 divides to an F64 and not to the double R’s / gives.

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 are declared with @type, @alias and @opaque, and each 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.
  • opaque NAME = TYPE, or #: @opaque NAME {TYPE}, declares an opaque type: a nominal type whose representation only the file that declares it can see.

The three forms share one namespace, so reusing a name under any of them is an error, except for a #: definition paired with the inline one directly below it (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 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.
  • A wrongly applied name then compares like Unknown, so the one arity error never cascades into mismatches between values.

A type definition cannot take the name of a built-in type: an atomic or ry scalar name (double, I64, Str), Any, Unknown, NULL, a table type (DataFrame, LazyFrame, GroupBy, LazyGroupBy), Record, Tuple, Promoted, Subtracted, Compared, or the standard library’s List, Dict, Set and Expr. Annotations and checks read such a name as the built-in type, so a definition with it would conflict, and ry reports it as an annotation error at its name. The standard library’s Result is an alias, which a project’s own definition of Result replaces.

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. A recursive type, such as a logger whose setters return the logger for chaining, is a nominal type instead: #: @type Logger {list{set_threshold: fn(level: character) -> Logger}} names the type, so log$set_threshold("info")$set_threshold(3) is checked at each call.

alias Box<T> = list{ value: T }
value: Box<integer> <- list(value = 1L)

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 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 is the only place the type’s invariant is established. An opaque type also restricts where @new may appear.
  • A nominal type whose representation is another nominal type extends it, the way R’s class vector c("TradeDate", "Date") does. With @type TradeDate {Date}, a TradeDate passes wherever a Date is expected, and its operators and [ dispatch to TradeDate’s own methods first and then to Date’s, so trade - trade is a difftime through -.Date. The stubs declare data.table over data.frame and ggplot over gg the same way.
  • 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. A union of nominal types projects member by member, so s$radus on Circle | Square is checked against both representations.
  • A nominal type carries no runtime class, so is.list() cannot tell Circle from Square. A field test can: is.null(s$radius) drops, on its false edge, each member whose representation has no such field, and keeps the others as the nominal types they are. After if (is.null(s$radius)) stop("not a circle"), s is Circle. Tags (:Circle(radius: double)) are the discriminated form when the representation is yours to choose.

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:

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))

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.

An abstract 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). 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.
  • Arithmetic and every other structural requirement remain type errors, unless the class declares the matching operator method. The nominal identity itself checks like any other nominal type.

data.frame is not abstract: 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)). 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.

data.frame(...) and data.table(...) know the columns they build, so their result is a data.frame{...} or a data.table{...}, whose columns are written as a DataFrame’s:

frame <- data.frame(id = 1:3, price = c(1, 2, 3)) # data.frame{id: integer[], price: double[]}
frame$price # double[]
frame$volume # error: the frame `frame` has no column `volume`

A column takes its argument’s name, or a bare variable’s. An argument R spreads over several columns (a list, a matrix, another frame), a forwarded ..., a repeated or non-syntactic name, and stringsAsFactors = TRUE or keep.rownames = TRUE leave the columns unknown. frame$x <- v and frame[["x"]] <- v add or replace a column. Any other write that may rename or retype columns (names(frame) <- v, frame[, "x"] <- v, data.table’s set and setattr) forgets them, while setDT and setDF change the class and keep them. Everywhere else a data.frame{...} is a data.frame: it passes to a data.frame parameter, and [ and arithmetic dispatch on the class. A data frame built any other way, such as by read.csv or merge, has unknown columns, so a column read such as frame$amount is Unknown, and strict mode reports it where it is read.

An opaque type is a nominal type whose representation is private to the file that declares it. Inside that file it is an ordinary nominal type. In every other file, test files included, the type can be named, passed, returned and stored, but not built or taken apart, so the declaring file’s functions are the only way to make or inspect one. Its invariant then holds everywhere, not only where @new is written.

Outside the declaring file, each of these is a type-mismatch error that points back at the declaration:

  • @new of the type, or @Name(value).
  • $, [ and [[, read or written, including x$value <- v.
  • A for loop over the value.
  • A match arm that destructures the value. A wildcard or a bare name still matches it.
  • Passing the value where its representation is expected, and arithmetic on it, because the representation is not visible to project it to.

The check covers a value whose type is the opaque type itself, a union containing it, or NULL or an optional of it. R functions that take any value still accept it, so length(x), attr(x, "unit") <- "m" and unclass(x) are allowed: they leave the type system, as they do for every other value. The restriction is static only. At run time an opaque value is its representation, like any nominal value.

R/units.R
opaque Meters = list{value: double}
meters <- function(value: double) -> Meters {
if (value < 0) stop("negative length")
@Meters(list(value = value))
}
in_feet <- function(length: Meters) -> double length$value * 3.28
# R/use.R
in_feet(meters(2)) # fine
@Meters(list(value = -1)) # error: only the declaring file can create one
read_it <- function(length: Meters) -> double length$value # error: the representation is hidden

The error on read_it reads:

x `Meters` is opaque, so its representation is hidden outside the file that declares it. Use that file's functions instead
--[R/use.R:2:29]
1 | #: fn(length: Meters) -> double
2 | read_it <- function(length) length$value
| ^^^^^^
`-> > the type is declared opaque here
--[R/units.R:1:1]

A script that declares an opaque type sees it like the declaring file does, because a script’s definitions are its own.

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. The standard library’s List<T>, Dict<K, V> and Set<T> are the exception: they are immutable values, so every parameter is covariant, and [:Cash], a List<:Cash>, is accepted where a List<:Bond | :Cash> is expected.

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.

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.

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 a parameter the call supplies mentions it and the call left it unconstrained, because no argument then produces such a value. With or_else <- function(value, fallback) if (is.null(value)) fallback else value, typed <T, U> fn(value: T | NULL, [fallback]: U) -> U | T, the call or_else(NULL, "x") is character: the NULL fills nothing of T. 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:

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).

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 are ry’s own values, not R lists. The user guide is Records and tags; 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.

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.

A Record{...}, DataFrame{...}, LazyFrame{...} or GroupBy{...} type may end in a row ..R, where R is a type parameter of the function. The type lists some fields or columns, and R stands for all the others, so a function can take any table that has a code column and return it with one more column:

ids <- DataFrame(code = c("a", "b"), id = c(10L, 20L))
add_id <- function<R>(data: DataFrame{code: character[], ..R}) -> DataFrame{code: character[], id: integer[], ..R} {
DataFrame.join(data, ids, on = "code")
}
out <- add_id(DataFrame(code = c("a", "b"), price = c(1.5, 2.5)))
print(out$volume)
add_id(DataFrame(name = "a"))

out is a DataFrame{code: character[], id: integer[], price: double[]}, so the checker knows both which columns it has and which it lacks:

type-mismatch
x the frame `out` has no column `volume`. Its columns are `code`, `id`, `price`
type-mismatch
x expected `DataFrame{code: character[], ..T}`, found `DataFrame{name: character[]}`
  • R must be declared with function<R>(...) or <R> fn(...), and the row comes last. A list{...} type ends in a bare .. instead (open records), and a Tuple{...}, a tag’s payload, a data.frame{...} and a data.table{...} type list everything, so a row there is an annotation error.
  • At a call, R binds to the fields or columns the argument has beyond the listed ones, so the result carries them with their types. A listed field takes precedence over a field of the same name in the row.
  • Inside the function, R is unknown. Reading a field or column the type does not list is a type-mismatch, and so is a positional [[ such as x[[1]], because the row’s fields or columns may come before the listed ones. Iterating a table with a row, as lapply does, gives columns of unknown type. A record pattern needs a trailing .., as in (a = p, ..).
  • R stands for a row wherever it appears: using it also as a type of its own, as in y: R, or as the row of both a record and a table is an annotation error. A generic alias passes a row on: with alias Rec<R> = Record{a: I64, ..R}, Rec<S> is Record{a: I64, ..S}, and Rec<I64> is an annotation error.
  • A value with a row fits a type with the same row, never a closed type: returning Record{a: I64, ..R} as Record{a: I64} is a type-mismatch, and so is building a closed (a = 1L,) where Record{a: I64, ..R} is expected.
  • A table verb that keeps every column keeps the row: filter, sort, head, tail, unique, with_columns, drop, rename, with_row_index, group_by, lazy and collect, a row selection d[i], a := update, and a join whose left table has the row. select and GroupBy.agg build their result from the columns they name, so it has no row, and a join whose right table has a row, or concat of a table with a row, types as a plain DataFrame.
bump <- function<R>(x: Record{a: I64, ..R}) -> Record{a: I64, ..R} (..x, a = x$a + 1L)
y <- bump((a = 1L, b = "x"))
print(y$b)
#> [1] "x"

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, 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 lone .. lists no tag, so it holds every tag.

  • 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.

A tag union has no row, 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 defines Result<T, E> as {:Ok(T) | :Err(E)}, and a project’s own Result alias shadows it.

A record, tuple or tag union may be the representation of a nominal type, 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(...) 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 record update (..point, y = 3) on a nominal record follows the same rule: the copy keeps the nominal type, so each replaced field keeps its declared type.
  • A match checks its patterns and its coverage 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.

(..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:

p <- (x = 1, y = 2)
q <- (..p, z = 3)
type-mismatch
x field `z` does not exist in `Record{x: I64, y: I64}`

Only a record, or a nominal type whose representation is a record, can be updated this way, and $<- is the statement form of the same change. A nominal record’s copy keeps the nominal type, so with type Point = Record{x: F64, y: F64}, (..point, y = 3) is a Point, and replacing y with a Str is a type-mismatch rather than a change of type.

== and != compare two records, tuples or tags structurally and give a Bool. Two values are equal when they have the same shape (the same fields, or the same tag with the same payload shape) and every field or payload item is equal, compared the same way. A List of them compares item by item, as the list operators do.

type Point = Record{x: F64, y: F64}
p <- @Point(x = 1, y = 2)
p == @Point(x = 1, y = 2)
#> [1] TRUE
:Some((1i64, "a")) != :Some((1i64, "b"))
#> [1] TRUE

The two sides must have types that can hold one value, so comparing values whose types never meet is a type-mismatch:

isOther <- function(kind: :Bond | :Cash) kind == :Other
type-mismatch
x `==` is not defined between `:Bond | :Cash` and `:Other`, because a value of one type never equals a value of the other
  • A number field is equal when it holds the same number, as identical decides, so a field holding NaN equals one holding NaN, unlike == on two F64 values.
  • An R value never equals one of these values, so comparing one with an R value is a type-mismatch.
  • <, <=, > and >= are not defined on records, tuples or tags.

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. The .. takes no name: (x = a, ..others) is a syntax error
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.

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), 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.

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:

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"

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:

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.

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 parameter that the callee only forces and perhaps hands back takes one too, as the object of testthat’s condition, output and visibility expectations does, so expect_error(make_point(-1), "negative") checks while expect_equal(make_point(1), p) is reported (@opaque in the stub, see the stub authoring guide). 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.

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). An R list is never a record, tuple or tag, so passing one where a record is expected is a type-mismatch:

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)
type-mismatch
x expected `Record{time: List<I64>, treated: List<Bool>}`, found `list{time: integer[], treated: logical[]}`. An R list never becomes a record: write a record literal, `(time = ..., treated = ...)`
--[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

When the value is written as a list(...) call, ry check --fix --unsafe-fixes rewrites it as the literal, list(time = t, treated = d) as (time = t, treated = d).

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

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 or tuple that R code builds with as.record() passes to compiled typed code when each field is a scalar, a string, another such record or tuple, or a ry list, and its shape is then its type. One with a longer R vector in a field, an NA string, a class or attributes makes the call run in the interpreter.

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).

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. An unannotated helper takes ry numbers wherever ry’s arithmetic is defined on them, through the constraints that join R’s numbers and ry’s: mul <- function(a, b) a * b multiplies two F64s to an F64, and scale <- function(x) x * 2 makes List.map(xs, scale) with xs: List<I64> a List<I64>. A helper that divides, such as function(a, b) a / b or function(x) x * 0.5, takes an F64 and not an I64, because ry’s / and fractional literals are defined on F64 alone, and passing it an I64 is a type-mismatch.

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, 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), a position into a List (lookup[[j]], which makes j an I64), or the value a function declared with a ry number result ends with, which may be one branch of an if whose other branch is a literal (if (flag) y else 0). 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. Arithmetic on the variable and number literals of its R type (x + 1.5 with x <- 0) is open too, and so is a variable that branches write with literals R gives one type: in a function declared -> F64, x <- 0, then if (n > 1i64) x <- x + 1.5, then x makes every x an F64. Branches that write literals of different R types (1L and 2.5) keep R’s types, inside a value as well: if (c) :Ok(1L) else :Ok(2.5) is an :Ok(integer | double). An if with else or a match whose branches are all number literals of one R type is one such literal, both bound to a variable (m <- if (c) 1 else 2, then m + n with n: I64, makes m an I64) and beside one (score + match (k) { :A => 1, :B => 2 } with score <- 0). A copy holds the same literal, so after a <- 0 and b <- a (or b <- (a)), a use of either decides both. A loop body’s value and the branches of an if or a match whose value nothing reads decide nothing, so in for (x in xs) if (x > 2i64) n <- n + 1 after n <- 0, the use of n after the loop decides it. Any other read gives the variable R’s type, as does a function that never decides it. A literal written as a tuple item, a record field or a tag payload item, or a variable written with a literal there ((e, o) after e <- 0), 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}. In a function declared -> Result<I64, Str>, found <- :Ok(1) then found makes the 1 an I64. A List holds only ry values, so a List item read from such a variable is a ry number that a use decides as for a lone literal item: after e <- 0, [e] is a List<I64>, or a List<F64> in a function declared -> List<F64>, and [e, 1.5] is a List<F64>.
  • A top-level binding in a typed file. In a strict file, a file that builds a ry value (a record, tuple, tag, List or match), or a file with an inline annotation that names one of ry’s own types (a ry number, Str, Bool, List, Dict, Set, Result, a Record{...}, a Tuple{...} or a tag), 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. The tuple items, record fields and tag payload items of a literal bound there are ry values too, also inside a nested literal or a List, so pt <- (x = 3.0, y = 4.0) is a Record{x: F64, y: F64} and pair <- ("a", 1) a Tuple{Str, I64}. A literal inside a call keeps R’s type, as f(1) does: f((x = 1,)) passes a Record{x: double}. Each top-level statement is checked on its own, so nothing later in the file decides the type. A finding this causes names the binding: after total <- 0, List.walk(xs, total, \(sum, x) sum + x) over a List<F64> reports that + is not defined between I64 and F64, marks total <- 0 with “total was settled as I64 here, by the literal 0”, and says to write 0.0 or annotate total: F64 <- 0. In any other file a top-level literal has R’s type, so a file annotated in R’s types alone (f <- function(x: double) -> double, p: list{name: character}) runs like its erasure. A record or tuple type counts by its head, so an R class named Tuple does not, and a #: comment never counts, because comment annotations leave the code ordinary R that computes what R computes.

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 number, string or TRUE/FALSE passed for a ry function’s type parameter is open too, so another argument or the call’s use decides it: in List.walk(words, "", f) with f: (Str, Str) -> Str the "" is a Str, and Result.with_default(:Ok(1), 2) in a function declared -> I64 is an I64.

A tuple item, record field or tag payload item written with a literal in one branch of an if or match is decided by the item in the same place of another branch. In the arms :Buy(quantity = q, price = p) => (q, p) and :Fee(amount = a) => (0, a), the 0 is an F64 when q is an F64 and R’s double when q is a double, so a variable the match writes in a loop has one type on every iteration. A string or TRUE/FALSE beside a Str or Bool is decided the same way, and (2.5, a) beside (q, p) with q: I64 is a type-mismatch at the 2.5.

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

m <- 5i64
m * 2.5
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, the console or ry load 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 parsed on ry’s runtime, by source(), parse(file = ) or a parse whose srcfilecopy() has isFile = TRUE (as sys.source(keep.source = TRUE) and testthat make), is checked on its own and elaborated the same way, and the check prints its annotation warnings, once per session for the same file and text. The check of a script, of a console command and of a sourced file reads the files it source()s by a literal path, resolved against the working directory as R resolves it, so strict code may call what they define. It reads them when the code is checked, before it runs, so a later console command sees what the file defined then, and a script that writes a file before sourcing it is checked against the file’s earlier text. When a name is defined in several sourced files, the file that finishes running last defines it, and a definition in the sourcing file itself takes precedence over a sourced one. The check does not follow an absolute or home path, such as /lib.R or ~/lib.R, sys.source() without keep.source = TRUE, which runs the text unelaborated, or a call that evaluates into another environment, such as source("lib.R", local = new.env()) or source("lib.R", local = TRUE) inside a function, because nothing it defines is visible globally. ry check and the editor do not know the working directory the code will run in, so they try the sourcing file’s own directory first and then the project root, and follow no path that leaves the project. Strict mode applies to a sourced file only when the file turns it on itself (# typing: strict), because the project’s strict mode belongs to the script that sources it. A file with no ry syntax and no # typing: directive is not analyzed and reads no ry.toml, and its literals keep R’s types. Code parsed from text, and sys.source() with its default keep.source = FALSE, is not elaborated: 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.

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 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:

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.

Num.from_r turns an R double into an F64 and an R integer into an I64, Str.from_r turns a character into a Str, and Bool.from_r turns a logical into a Bool. 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:

n <- 4
inc <- function(x: I64) -> I64 x + 1
sqrt(n)
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.

An operator never converts between the two sides, so comparing a ry scalar with an R value is a type-mismatch that names the conversion for the R side: Str.from_r() for a character, Bool.from_r() for a logical and Num.from_r() for a number.

same <- function(a: Str, b: character) -> Bool a == b
type-mismatch
x `==` is not defined between `Str` and `character`. A ry value meets an R value only through a conversion: convert the R side with `Str.from_r()`

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.

[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: [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).

  • 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:

    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:

    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)
    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()`

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.

  • 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 holds the functions that work on lists.

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.

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>.

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
}
  • 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.

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 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 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:

join <- function(...: character) -> character paste0(...)
wrap <- function(x: character, ...: character) -> character {
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 and function type compatibility).

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), 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.

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, and in an annotation on a value that is not a function literal, the return comes from the value’s own type, called with the written parameter types. With f <- function(x) x + 1L, #: fn(integer) on g <- f types g as fn(integer) -> integer. When the value’s return is not known, it is Unknown.

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.

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 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 with its constraint, such as <T: num>, 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 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. The guard may be a block that ends in return(value), and the flag may be negated, so if (!verbose) { ...; return(TRUE) } makes the block the false branch. Several such guards of the same flag all return the same branch, so if (both) return(a) early and if (both) return(b) later join a and b as the true branch. A call that leaves the flag out, or passes a literal, selects one branch, so it returns that branch’s type alone:

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

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 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 explicit NULL argument matches a NULL default, because the callee sees the value it would have seen without the argument. So with search <- function(fun, target = NULL) passing target on to arithmetic, search(fun = f, target = NULL) checks while target = "a" is reported.
  • A default that names a function the checker has no type for, such as timefun = bit::repeat.time in a package it cannot read, makes the parameter’s own type open, so calling it with any arguments checks.
  • A value written to a formal on its missing() path types like the same value given as the default: it fills in for an omitted argument and does not rewrite a supplied one. So after if (missing(tol)) tol <- 1e-8, m * tol bounds what a caller passes as tol, and a call that omits tol sees double. A function written there, as in if (missing(col.fun)) col.fun <- function(n) rep("a", n), is a default the same way. A value written on any other path is a rewrite, so later uses meet both values.
  • Inside if (missing(x)), reading x is an error unless x goes straight on to a parameter a project function may leave unread, because R then forces nothing: if (missing(x)) report(x) checks when report tests missing() on that parameter. A library function forces what it is given, so formatC(x, width = w) there is still reported.

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:

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.

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:

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.
  • An accumulator whose initial state is a settled ry value takes that value’s type, so in List.walk(rows, List.repeat(0f64, 2), \(sums, row) sums + row) the formal sums is a List<F64>. When the step function returns more tags than the state holds, the state widens to the join of both and the step function is checked again under it, so List.walk(xs, :None, \(acc, x) :Some(x)) is :None | :Some(I64) and List.walk(xs, (best = :None, n = 0i64), \(acc, x) (best = :Some(x), n = acc$n + 1i64)) is Record{best: :None | :Some(I64), n: I64}. The initial state is passed as the wider type, and the step function is checked at most three times. A step function may also return the state as the payload of every tag it returns, so List.walk_until(xs, :None, \(acc, x) if (x > 2i64) :Break(:Some(x)) else :Continue(acc)) is :None | :Some(I64). A state with a tag in it widens only with a single candidate callee whose step function returns the state in one of these two ways; anywhere else it gives the formal no context.
  • An accumulator whose initial state is a settled R value starts from that value’s type and widens to what the step function returns, and the step function is checked again under the wider type. R’s arithmetic promotes the start away, so Reduce(function(acc, x) acc / x, 1:3, 1L) takes acc: double and is double, while any other start stays in the union: Reduce(function(acc, x) c(acc, x * 2), 1:3, c()) takes acc: double[] | NULL, and Reduce(function(a, b) a < b, 1:3, 0L) is integer | logical, because a comparison’s logical answer is never promoted away. A start the step function rejects is an error at the start, as for a named function. A number literal without L, such as 0, adapts to the state instead, and a step function with declared parameters fixes the state at its accumulator’s declared type when the start and the return both fit it. A Reduce without an init starts from the first element of x (the last with right = TRUE), so Reduce(function(acc, x) acc / x, 1:3) also takes acc: double, and Reduce(function(acc, x) acc + nchar(x), c("a", "b")) is an error at c("a", "b"). Only the first item of a list built with list(...) starts the fold, and an x whose elements are not known, such as an unannotated parameter, starts nothing.
  • 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:

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

A function literal that is the default of a declared parameter takes its parameter types the same way, from the parameter’s declared function type, under the same limits:

#: fn(dsn: character, [connector]: fn(dsn: character) -> character) -> character
connect <- function(dsn, connector = function(dsn) toupper(dsn)) connector(dsn)

Here the default’s dsn is character, so strict mode accepts it with no annotation of its own. A misuse of such a parameter says that the declaration gave the type: `v` is used as a numeric value (`integer` or `double`) here, but the parameter this function is the default of declares `character` for it.

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.

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.

A union of functions, such as a local chosen by switch(type, a = up_a, b = up_b), is accepted where one function type is expected when each member is, with its own return, and the union of those returns satisfies the expected return. Arguments a call forwards to the callback, as in lapply(names, chosen, new = NULL), reach every member.

A declared function such as apply passes its ... on to its callback, so an untyped parameter that the body also calls takes fn(Any, ...: Any) -> Any when passed there, even from a call that forwards nothing. After apply(m, 1, fun), the body may still call fun(m, na.rm = TRUE). A parameter the body only passes on keeps the exact shape: each <- function(f) lapply(list(1, 2), f) is fn(f: fn(double) -> T) -> list[T].

A function whose parameter types are still being inferred is the one exception to exact parameter types: after uniroot(f, interval, scontrol = scontrol) binds scontrol’s parameter to double, the same body may call scontrol(times) on a double[], because R’s numeric functions are vectorised. An annotated callback keeps its exact type.

sapply and mapply simplify their results to a vector, a matrix or a list depending on what the callback returns, so their type follows the callback’s return type and the simplify flag (SIMPLIFY for mapply):

Call Type
callback returns a scalar-like T, flag left out or TRUE T[]
flag is a literal FALSE list[T]
callback returns anything else, or the flag is not a literal Any

The result is named (T[named], list[named: T]) when the input is named or a character vector, as R names it. USE.NAMES = FALSE drops the names a character input gives, and for mapply and Map the names of a named input too:

xs <- c(1, 2, 3)
doubled <- sapply(xs, function(x) x * 2) # double[]
kept <- sapply(xs, function(x) x * 2, simplify = FALSE) # list[double]
pairs <- sapply(xs, function(x) c(x, x)) # Any: a matrix in R
widths <- sapply(c("a", "bb"), function(s) nchar(s)) # integer[named]

A scalar-like return is trusted as length one, as everywhere else, so a callback typed scalar that returns several elements gives a vector type to what R returns as a matrix. A generic callback is the exception: its return was inferred before its parameter met an element, so it is trusted only over an atomic vector, whose elements are scalars. Over a list, sapply(xs, function(v) v * 2) gives Any, because v may be a vector. A return that depends on the callback’s own type parameters, as identity’s T does, gives Any too. tapply gives Any, because its result is an array shaped by the groups of INDEX. The callbacks are still checked: sapply’s takes the elements of X, as lapply’s does, so sapply(xs, function(v) v + "a") over numbers is an error, and so is sapply(xs, 4):

expected a function that takes `double`, found `double`

Map is mapply with SIMPLIFY = FALSE, so it gives list[T] for a callback that returns T, and list[Any] when the return is undetermined.

ifelse(test, yes, no) takes the shape of test and is either branch’s type, so ifelse(x > 0, 1L, 2.5) is integer[] | double[] for a vector x, and ifelse(TRUE, 1L, 2L), whose test is made of literals, is integer. A bare NA fits the other branch, so ifelse(x > 0, "positive", NA) is character[]. A branch that is not a plain vector, such as a factor, whose class ifelse drops, gives Any, and so does any other test that types as a scalar, because a comparison on a matrix types as one and the result keeps the matrix’s dimensions.

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. The finding sits on the template and names the callback:

`toupper` returns `character`, but this `FUN.VALUE` asks for `double[]`

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

Section titled “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.

An unannotated parameter passed as the callback of a library function that forwards its own extra arguments, as in apply(v, 2, FUN = fun, na.rm = na.rm), takes those arguments too, so it is typed fn(Any, ...: Any) -> Any and a later direct call fun(v, na.rm = na.rm) is clean.

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 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.

value: list[integer] <- 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 instead.

#: @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:

frame <- read.csv("a.csv")
gap: @if-unknown integer <- frame$a # valid: `frame$a` is `Unknown`
value: @if-unknown integer <- 1L # an error: the type is already known

#: @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.

callback <- function(x) x
render_count: @trust fn(count: integer) -> character <- 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.

#: @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 representation is an expected type for the value’s literals, so @Tree(:Leaf(1)) with type Tree = :Leaf(I64) | :Node(Tree, Tree) makes the 1 an I64.
  • 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:

type Person<T> = list{ value: T }
value <- @Person<integer>(list(value = 1L))

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 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.

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 matrix is accepted the same way, as in if (!m[i, j]), and a named vector is accepted exactly when the unnamed vector of its element is.
  • 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.

[[ 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, and fails on a named vector, so there it gives the element type.

$name behaves like [["name"]] on lists, on records, and on abstract 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:

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.

  • 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.
  • 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.

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.

[ 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].

$, [[, 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 abstract nominal, such an access is an unsupported construct under 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}.

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.

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 whose arithmetic takes two of its values negates to itself, because R dispatches unary - through the same methods, so -(m %*% m) is a matrix and -elapsed on a difftime is a difftime. -day on a Date is a type error, as R stops on it.
  • 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.

An unannotated value used as an arithmetic operand is required to be a number rather than rejected: it must end up as an R number (integer or double, in any vector shape), a class with arithmetic, or a ry number where ry’s arithmetic is defined on it. The operator and the other operand pick the constraint and the result:

Operands Constraint Result
x beside a whole number literal (x + 1L) arithmetic or number T
x beside a whole double literal (x * 2) arithmetic or number Promoted<T>
x beside a fractional literal (x * 0.5), or under / arithmetic or F64 Promoted<T>
two of one type, under +, *, %% or %/% num T
two of one type, under - arithmetic or number Subtracted<T>
two of one type, under / numeric or F64 Promoted<T>
two of one type, under ^ num Promoted<T>
beside any other value arithmetic R’s result
x beside a number literal, under <, >, <= or >= (x > 0) comparable or number Compared<T>
x beside a string literal, under <, >, <= or >= comparable or Str Compared<T>
x beside a number literal, under == or != (x == 0) equatable or number Compared<T>
x beside a string literal, under == or != (x == "a") equatable or Str Compared<T>
a value compared with itself under == or != eq Compared<T>
a value compared with itself under <, >, <= or >= comparable or ordered Compared<T>
two open values under == or != eq on each Compared<T, U>
two open values under <, >, <= or >= comparable or ordered on each Compared<T, U>

A whole literal is one with no fractional part, so 2.0 counts as whole and 2.5 does not. A class such as Date adds a number but not another value of its own, so two operands of one type take num under +. A difference a - b is the exception, because R subtracts two dates or two times: it asks only arithmetic on the R side, and the difference of two dates is a difftime, so its result is Subtracted<T>: the class itself when it has arithmetic between two of its values (two difftimes subtract to a difftime), the class its - method declares for two of it (two dates or two POSIXct times give a difftime), and a double for any other class. Beside a number, a class with arithmetic keeps its class: Sys.Date() - 0.5 is a Date.

A family result keeps both outcomes while it is bound, returned, passed to a function, or used as another operand. Anywhere only an R value fits, such as a subscript ((x * 2)[1]), a for sequence, c(), an overloaded base function (abs(x - y)), or an operand beside another open value, Promoted<T> and Subtracted<T> are double, Compared<T> and Compared<T, U> are logical, and the operand takes its constraint’s R half. A value tested as a condition (if (a %% 2L), !a, a && b) takes R’s half the same way, because a condition reads R’s truth of a number, which a ry number lacks.

  • function(x) x + 1L is <T: arithmetic or number> fn(x: T) -> T, and calling it with "oops" is a type error. Calling it with an I64 is an I64.

  • function(x) x / 2 is <T: arithmetic or F64> fn(x: T) -> Promoted<T>: an F64 for an F64, a double for an R number, and a type error for an I64.

  • function(a, b) a + b is <T: num> fn(a: T, b: T) -> T, and calling it with two dates is a type error. Calling it with two I64s is an I64.

  • function(a, b) a - b is <T: arithmetic or number> fn(a: T, b: T) -> Subtracted<T>, and gives a difftime for two dates and an I64 for two I64s.

  • function(x) x > 0 is <T: comparable or number> fn(x: T) -> Compared<T>, a Bool for an I64 and a logical for a double or a character. Calling it with a Str is a type error, because ry compares a Str only with a Str.

  • function(a, b) a < b is <T: comparable or ordered, U: comparable or ordered> fn(a: T, b: U) -> Compared<T, U>. The two operands stay separate types, because R compares an integer with a character and a function may return either operand unchanged: cmp(1L, "s") is a logical, cmp(1L, 1:3) is a logical[], and keep <- function(x, lo) { if (any(x < lo)) warning("low"); x } returns a Date for keep(Sys.Date(), "2020-01-01"). ry compares a ry value only with a value of its own type, so a call that passes one checks the other operand against it, as a parameter of that type would: two Strs give a Bool, cmp(1i64, 2) takes the literal as an I64, and cmp(1i64, "s") and cmp(1i64, 2.5) are type errors. The check follows the pair through a function that forwards it (function(p, q) cmp(p, q)) or returns a function comparing it (function(q) function(a) a < q), and through a function passed where a function type is declared, although the signature does not show it, and through a function with a declared return type. A literal default adapts as a passed literal does, so function(a, lo = 0) a < lo takes an I64, while lo = 2.5 or lo = sqrt(2) keeps its double and refuses one. A default the body adds a fraction to (lo <- lo + 0.5) adapts as a fraction, so it refuses an I64 too. An operand compared with an R value admits only R values, so function(a, b: double) a < b refuses an I64 for a. Two records are a type error.

A ry List meets a comparison’s constraint through its items, as it compares item by item, and a ry nominal through its representation. A declared binder widens over R’s types, so Bool.is_eq(1L, "one") is a Bool, while Bool.is_eq(1i64, "one") is a type error. A complex value passes function(x) x == 0 but not function(x) x > 0, because R tests it for equality and has no order for it. An I64 beside an R integer (cmp(1i64, x) for x: integer) is a type error, because an R number meets a ry number only through Num.from_r(). One gap remains: the result of two different open operands follows the left one alone, so cmp(1L, 1:3) is a logical rather than a logical[].

A callback whose family result must have its operand’s type, as a fold’s accumulator must, takes a type the family keeps. A comparison settles the accumulator as R’s logical when it fits, else as Bool. Arithmetic leaves it open, and the fold’s call gives Promoted<T> of it, so Reduce(function(acc, x) acc * 2, 1:3, 1L) is the double R’s arithmetic makes of the integer init, and so is a callback that returns the accumulator unchanged in one branch (if (x > 1L) acc * 2 else acc). List.walk(xs, k, function(acc, x) acc * 2) with k: I64 is an I64, and an init of a vector or a class gives the fold its own type: Reduce(function(acc, x) acc * 2, list(1:3, 4:6), c(1L, 2L, 3L)) is a double[], and Reduce(function(acc, x) acc - 0.5, 1:3, Sys.Date()) a Date. A fold’s result is its init or its callback’s, so Reduce(function(a, b) a < b, 1:3, 0L) is logical | integer. An init that a function’s parameter gives stays generic:

doubled <- function(ys, init) List.walk(ys, init, function(acc, y) acc * 2)
# doubled: <T: item, U: arithmetic or number> fn(ys: List<T>, init: U) -> Promoted<U>

So doubled([1i64], 1i64) is an I64, doubled([1i64], 1L) a double, and doubled([1i64], "a") a type error. The parameter itself keeps its type, so a function that also returns init returns U. A call of any function with a callback parameter fn(A, T) -> A folds the same way, and its result reads each A as Promoted<A>: for give <- function<A>(f: fn(A, integer) -> A, a: A) -> fn(A, integer) -> A f, give(function(acc, x) acc * 2, 1L) is fn(double, integer) -> double, while a result that does not name A keeps its type. Only a callback that is itself a parameter of one signature folds open, and not through an overloaded function such as purrr::reduce. One inside a record, a list or a union settles its accumulator as double. A callback that subtracts two accumulators folds as their difference, so function(ys, init) List.walk(ys, init, function(acc, y) acc - acc) returns Subtracted<U>: an I64 for an I64 init and a difftime for a Date. R’s fold returns the init itself for an empty xs, which the type does not track: Reduce(function(acc, x) acc * 2, integer(), 1L) types as double and runs as 1L.

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: arithmetic> 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 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.

A logical argument binds a numeric type parameter to integer, the type R’s arithmetic reads it as, so with bump <- function(x) x + 1L, bump(TRUE) is integer, as in R. A function that returns its logical argument unchanged, such as keep <- function(x) { x + 0L; x }, is then reported to return integer where R returns the logical. That claim is safe, because a logical fits wherever an integer is expected, while the opposite claim would type R’s 2L as a flag.

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.

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. A stub sees only the types stubs define, so the methods of a type your R code defines, such as @type Money {double}, are annotated R functions beside it (`+.Money` <- function(e1, e2) ... under #: fn(e1: Money, e2: Money) -> Money). Declaring each method keeps the result 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 abstract 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 arithmetic requirement: passing a Money to function(x) x + 1L is accepted when the project defines +.Money, and refused when it defines no arithmetic method. Passing two to function(a, b) a + b needs a method whose first two operands both take a Money, as function(e1: Money, e2: Money) does.

R also dispatches on a class that class(x) <- "string" sets on a plain list or an environment (ggplot2’s ggproto objects are classed environments), and no type tracks that attribute. So when the project defines an arithmetic or Ops method for a class that no type declares, or registers one through S4’s setMethod("+", ...) or S7’s method(\+`, …), arithmetic with a list or environment operand is left to that method: result + “text”on such a list, and the rest of a chainresult + a + b, give Unknownand 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. The stubs keep Date and POSIXct through [, min, max, range, sort, rev, unique, head and tail, as R’s methods do. A for loop over dates gives its variable the type double, because R strips the class there. Reduce(f, dates) is a type error, although R runs it, because Reduce takes a list[T] | T[] and a Date vector has no element type to write. 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 abstract 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, or that the project defines as a top-level function, is checked and typed as that call, so "a" %in% valid is logical, m %*% m is a matrix, and with `%plus%` <- function(a, b) a + b annotated fn(a: double, b: double) -> double, 1 %plus% "a" is reported at "a". A project operator that captures an operand’s code with substitute() is non-standard evaluation, as magrittr’s %>% is, so it gives Unknown and its operands are not judged. An operator of a package without stubs, or one defined inside a function, gives Unknown too. Using any %…% operator still counts as a read of its name, so a project’s own operator is never reported as unused.

<, <=, >, >=, ==, 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. A complex operand compares under == and != only, so 1i == 0 is a logical and 1i < 2 is a type error. raw operands are not supported. 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 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. ry’s records, tuples and tags compare only for equality, structurally, as their equality describes.

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[].

Logical negation coerces its operand exactly as a scalar condition 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.
  • 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.

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[].

An I64 endpoint is an error, because : builds an R vector from R numbers. ry reports it once: the sequence is Unknown, so sum(1:n) reports nothing more, and a for loop over it counts in I64 as it would over List.range(from, to). An unannotated other endpoint is an I64 too, so function(m, n: I64) for (i in m:n) ... infers m: I64.

error[type-mismatch] `:` builds an R vector from R numbers, and this value is a ry `I64`. Write `List.range(from, to)`, which gives a `List<I64>`

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. The NULL of an unannotated parameter’s default and of a variable the body computes is the placeholder that function calls drop, so it is dropped here too: rows[1:.after] on .after = NULL is clean when the code sets .after before it builds the sequence.

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.

Beside an R number, an unannotated operand, as in 1:n, is required to be a scalar integer or double, and the result is double[], because the endpoint may turn out to be a double. Like any inferred scalar, that requirement records a use, not a length, so a caller may pass a numeric vector such as the integer[] of which(), whose first element R takes. A c() call of two or more arguments is reported at the call, because it is known to be too long.

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]. An empty list adds no element, so c(list(), f) is list[fn] and c(list(), list()) is the empty list. 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].

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 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). 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.
  • zeallot’s c(a, b) %<-% value gives each name the type of its position. For a tuple or record value that is the item’s type, so after c(lo, hi) %<-% list(1, 2) both are double. For a list[T] it is T, and for a vector it is the element type. A nested c(...) destructures its position the same way, . skips a position, and ...rest takes the remaining items. When a tuple or record has a different number of items than the pattern has names and the pattern has no ...rest, the assignment is an error, because zeallot stops at run time.

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.

Both operands are scalar 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.

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.

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. == and != compare two formulas by their text, as R deparses them first, so formula(model) == ~1 is logical.

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 describes.

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. An element x[i] of such a variable, passed as an argument, drops the variable’s placeholder NULL too, since an element can be NULL only through the vector. As an endpoint of : it keeps the NULL, because a test such as length(range) < 3 admits the empty vector.

A call of an unannotated helper, written directly as the argument, makes the same claim about length but keeps its NULL, because a test can narrow only a variable. With format_maybe returning its character[] argument when no values follow and sprintf(fmt, ...) otherwise, gsub(format_maybe("$%s", name), "value", x) is clean. An unannotated function passed by name as a callback drops the NULL an if without else adds to its return, so vapply(rows, render_row, character(1L), type = "row") checks when render_row returns a string for every type the code passes.

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 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.

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.

rlang’s splice !!!x passes each element of x as an argument, so it forwards an unknown number of arguments the same way. Each element is checked against the rest parameter’s element type: for a list[T] or a vector that is T, and for a tuple or record every item. So join(!!!parts) on fn(...: character) with parts: list[double] reports expected `character`, found `double` at the splice. The argument types as that element, never Unknown.

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 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. A function that takes a ry value, such as List.map, calls its callback directly, so a string there is an error: List.map([1, 2], "toupper") is reported, with the hint to pass toupper itself. 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, and beside a local list named prod, apply(m, 1, prod) calls base’s prod. A local that holds a string is the function’s name, and is checked as that name. 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(), or rlang’s enquo(), enquo0(), enexpr() or ensym(), is code the callee captures, not a value, so it is not typed in the caller’s frame. An exclusion by name, -"value", passed to a library function no stub types is captured code too, because R rejects it as a value, and so is code that reads a variable holding its own name (.x <- ".x" before scales::math_format(2^.x)), a placeholder such code splices into an expression. In the data-mask arguments of a verb a stub marks @masked, tidyselect reads -"value" as a column exclusion, so dplyr::select(data, -"value") and tidyr::pivot_longer(data, cols = -"row") report nothing. Base with(data, -"value") evaluates the negation and is reported. 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.

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.

A standard-library stub may declare several signatures for one name, forming an ordered overload set (authoring stubs 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, so a wrapper’s parameter usually stays open on the set’s Any fallback. Strict mode reports a call that resolves to such a fallback. When only one candidate fits, it is selected and whatever it determines stands.
  • A wrapper over a numeric set is the exception. When the Any fallback is the only candidate that leaves a parameter open, and every other candidate narrows it to a number (logical, integer, double or complex, scalar or vector), the call needs a number whichever candidate a caller picks, so the parameter takes the arithmetic bound. function(x) abs(x) infers <T: arithmetic> fn(x: T) -> T, and calling it with a string or NULL is an error, as abs is in R. A class with an arithmetic method (Ops.<class>, Arith.<class> or an operator method) satisfies the bound, as it does for an operator, and so does a data frame. A set that also accepts other values imposes nothing: max takes character, cumsum takes NULL and sweep takes any matrix, so function(x) max(x) stays <T> fn(x: T) -> Any.
  • 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 same holds beside arguments whose types the call narrows: vapply(seq_along(x), g, template) with template unknown is Unknown, whatever g’s parameter narrows to. An if whose branch ends in such an undecided call is Unknown as a whole, rather than the join of the other branch with nothing.
  • The whole-number literal rule 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 the candidates that got furthest into the argument list all reject the same argument for the same reason, including all wanting a function where the argument is not one.
  • 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 keeps the stub’s signature. A base arithmetic operator folds as the operator types its operands, so Reduce(`/`, 1:3) is integer | double (a one-element x comes back unchanged). A function whose return is not known, such as c, gives that return: Reduce(c, 1:3) is Any, since R’s result is the whole vector. With right = TRUE the fold hands the element first and the accumulator second, as R does, so Reduce(max, 1:3, right = TRUE) is integer, and any other function is checked against fn(T, U) -> U: Reduce(function(x, acc) acc + nchar(x), c("a", "bb"), 0, right = TRUE) is double.
  • Reduce(..., accumulate = TRUE) is every accumulator in turn. R unlists them when each has length one, so an accumulator that is an atomic scalar gives a vector of the type c() makes of them: Reduce(`+`, 1:3, accumulate = TRUE) is integer[], and with an init of 0 it is double[]. An atomic vector accumulator may have another length, so Reduce(function(acc, x) acc + x, list(c(1, 2), c(3, 4)), accumulate = TRUE) is double[] | list[double[]], and any other accumulator gives Unknown. simplify = FALSE keeps the list (list[integer]). right, accumulate and simplify must be logical, and an accumulate that is not a literal gives both results joined.
  • 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, 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.

Elementwise base functions, such as sqrt, exp, log, round, nchar, toupper and is.na, declare one signature whose result describes a single element, and the call’s result takes the shape of the argument:

xs <- c(1.5, 2, 3)
roots <- sqrt(xs) # double[]
one <- sqrt(4) # double
kept <- sqrt(c(a = 1, b = 4)) # double[named]
grown <- exp(-matrix(1:4, 2)) # matrix
widths <- nchar(c("a", "bb")) # integer[]
#: fn(x: double[]) -> double[]
scaled <- function(x) sqrt(x) / 2 # checks

A matrix records no element type, so it lifts only a double result: is.finite(m) stays logical, which a condition accepts. A union argument lifts member by member, so log(if (flag) 2 else xs) is double | double[]. sapply(columns, toupper) over elements whose shape is unknown is no vector of strings, since each element may be a whole column that sapply stacks into a matrix, so the call keeps sapply’s general result. An argument whose shape is not yet known keeps the scalar result, so an unannotated wrap <- function(x) sqrt(x) infers <T> fn(x: T) -> double; annotate the wrapper to give it a vector result. array has no type of its own, and array() is Any.

An if without else takes a scalar condition. 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.

An if ... else takes a scalar condition 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.
  • 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.
  • Two ry values of the same shape join part by part, because ry’s values are immutable and so covariant: if (c) [:A] else [:B] is List<:A | :B>, if (c) (t = :A, n = 1i64) else (t = :B, n = 2i64) is Record{n: I64, t: :A | :B}, and if (c) :Some([:A]) else :Some([:B]) is :Some(List<:A | :B>). A loop’s accumulator joins the same way, so acc <- [:A] followed by for (x in xs) acc <- List.append(acc, :B) leaves acc a List<:A | :B>. Only tags widen: a part that differs in anything else, such as [1i64] beside [1.5f64], leaves the union of both values (List<I64> | List<F64>).
  • 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 open in variables of their own, such as two parameters, give their union, because a caller chooses the two values separately. function(value, fallback) if (is.null(value)) fallback else value is <T, U> fn(value: T | NULL, [fallback]: U) -> U | T, so x %||% list() and default %||% FALSE are both fine. The parameters of a function passed as a call argument are the exception: the callee supplies them, so its signature decides how they relate, and two open branches over them are tied. In Reduce(function(best, x) if (x > best) x else best, xs, 0) the callback returns the accumulator’s type. A callback that returns the union of two such open types still fits a callee that wants one of them, and the other ties to it, so with bind_pair returning either of its arguments, Reduce(function(x, y) bind_pair(x, y), parts) is accepted.
  • An Unknown branch makes the whole conditional Unknown, so if (flag) 1L else df$count is Unknown. The exception is a branch whose Unknown comes from a recursive call the checker is still working out: it joins as the other branch, which is how fact converges.
  • An if or a match 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.

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.

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. The false branch also drops NULL from the field itself, in each record that names it exactly, so after if (is.null(cfg$limit)) return("") a later cfg$limit reads character where the field is declared character | NULL, until the code writes cfg or that field, directly or from a closure with <<-. A nominal type’s field narrows the same way while the value keeps its type: after if (is.null(node$left)) stop() on a Tree, node$left reads Tree and node is still a Tree.
  • 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. length(x) == 1 also reads each vector member of the union as its scalar on the true edge (the false edge of != 1), so a character | character[] value passes to a character parameter inside if (length(new_row) == 1).
  • !cond swaps the two branches.

Combined with a diverging branch, the surviving edge’s refinement persists after the if, which is the idiomatic early-exit guard:

f <- function(x: integer | NULL) -> integer {
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 abstract nominal, is kept on both edges.

  • inherits(x, "simpleError") with a class R never gives an unclassed value drops x’s atomic, NULL and function members on the true edge, since only a value with a class attribute passes. So after res <- tryCatch(download.file(url, path), error = function(e) e), if (inherits(res, "simpleError")) stop(res$message) reads the condition’s field. A class such as "integer", "numeric" or "list" narrows nothing, because R reports it for unclassed values too. The false edge keeps every member, since an object may lack the class, except for "error" and "condition", which drop a condition member there: in tryCatch(f(), error = function(e) e) the handler’s value is a condition, so if (!inherits(res, "error")) res + 1 reads the expression’s value. Every condition has the one type condition, so a warning = function(w) w handler’s value is dropped by an "error" test too, and res + 1 after it is not reported although R fails there.

  • 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 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 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, or one field of it, narrows: a parameter, a function local, or a top-level variable assigned by an earlier statement. is.null(f(x)), is.null(x$a$b) and is.null(x[["a"]]) do not narrow. When such a value reaches a place that rejects only its NULL member, the mismatch says to assign it to a variable and test that:

    expected `character`, found `character | NULL`. A test such as `!is.null()` narrows only a
    variable or one of its fields, so to rule out `NULL` here, assign this value to a variable and
    test that
  • 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.

  • A closure may run after the rest of its frame, so it reads an enclosing variable as it stands where the closure is defined, joined with every later write the closure can still see when it runs, in the frame or in another closure. After if (is.null(x)) return(""); get <- function() x; x <- NULL, the call get() is character | NULL, and the same holds for a narrowed field (get <- function() cfg$limit followed by cfg$limit <- NULL). When the closure runs decides which writes it sees:

    The closure Sees writes up to
    called inline, (function() x)() the call
    passed to a function that calls it before returning (lapply, vapply and the rest of the apply family, do.call, tryCatch) the call
    bound with get <- function() x and only called its last call
    called inside a loop the end of that loop
    read in any other way: returned, stored, passed to another function the end of the frame

    So out <- get(); x <- NULL; out keeps out a character, and a write on the other branch of an if is never seen. A later R literal with the same default type as the read changes nothing, a literal with another default joins (x <- 1L; get <- function() x; x <- 2.5 makes get() integer | double), and the closure’s own <<- writes are joined as described under the assignment operator.

  • 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.

  • A callee whose body ends in a chain of such tests of one formal, with NULL only as the last else, answers NULL for an object of no class it handles. With chain_count <- function(x) if (is.chain(x)) 1 else if (is.chains(x)) length(x) else NULL, a call whose argument may carry a class (any type but an atomic vector, NULL or a function) returns without NULL, so 1:chain_count(x) checks for an unannotated x, while 1:chain_count("a") is reported.

  • identical(f, g) with f a local and g a function narrows f to g’s type on the true edge, and a generic g is instantiated afresh at each call, so after format_name <- identity as a default, if (identical(format_name, identity)) format_name(name + 1) calls identity with a number although an earlier call passed a string.

  • identical(x$field, "literal"), with a string, logical or numeric literal, rules NULL out of x on the true edge, because a NULL x has no field equal to the literal. So with info a record or NULL, if (identical(info$type, "venv")) use(info$path) passes info$path as the record’s field.

  • A local written under a test of another local remembers both values. After if (case == "a") x <- "s" with x a number before it, a later test of case that implies case == "a" sees x as the string, and one that rules it out sees the number: if (case == "b") x + 1 checks. The tests compare the local with literals through ==, != and %in%, a bare local (read as == TRUE), and ! of these. R coerces before it compares ("1" == 1 holds), so only literals of one kind are told apart by their values, and a string with a backslash is told apart from none. A write to either local ends it, and so does a write in a loop or through <<-. A test reads within the tests of the same local that enclose it, so inside if (case %in% c("a", "b", "c")), the writes under if (case %in% c("a", "b")) and if (case == "c") together leave no path that skips both: a local each makes a number is a number after them.

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. A library function declared only as Any, such as graphics’ rect, forces nothing either, because no declaration says what it reads.
  • 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. In R the callee sees the argument as missing, and a declared default does not fill it in: 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, because reading it would stop. A caller that omits such an optional formal sees the type of the callee’s default. When the callee writes the value on its missing() path, that is the value R reaches, so inverse <- function(m) pseudoinverse(m) over pseudoinverse <- function(m, tol) fast_svd(m, tol) returns tol as double. A declared default describes only a call that fails. As for a formal’s own missing() test, the order of the test and the reads is not checked.
  • Passing the formal bare to a function read from a field or a list element, as in dist$quantile(p, parms) or handlers[[1]](p, parms), does not force it, because the checker cannot see what that function reads.
  • Using the formal bare as one position of a matrix-style index, as in x$data[i, j] or x$data[i, j] <- value, does not force it, because [ reads a missing argument as an empty index and selects the whole dimension. A one-position x[i] and x[[i]] still force it, since x[i] types as one element and [[ has no empty index.
  • 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(). Forwarding a formal into the formal the generic dispatches on (its first, or the one named by UseMethod’s second argument) is different: UseMethod evaluates a supplied argument there to read its class, so after f <- function(fit) persistence(fit), the call f() is reported as leaving out fit.
  • 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 only where the nested function certainly runs, and only on every path through its body: when it is called inline, as in (function() x)(), when it is bound to a local and called through that local, and when the outer function returns it, because a factory’s closure is made to be called. A function passed to a call forces nothing, because lapply() over an empty vector never calls it, so function(items, x) lapply(items, function(item) c(x, item)) may be called without x. A nested function’s own parameter or assignment of the name shadows the formal.
  • 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.

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.

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(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(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 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, 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 (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, and a NULL or empty-list member adds no item type, because it runs the body zero times: for (f in if (a) list(g)) f() binds f as g’s type, not NULL.
  • 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 abstract 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 break leaves the loop with the state it saw and a next starts the next iteration with it, so a write that one cuts off from the end of the body still counts. A nested loop over the same name writes the outer loop’s variable, so the outer variable’s type after the loop includes the inner loop’s elements. 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.

foreach(g = groups) %do% body from the foreach package is a loop too. Each named argument of foreach() that does not start with a dot is an iterator, and the body sees it bound to the element type of its value, by the rules of for above. An iterator object such as icount() binds an Unknown iterator. foreach(i = xs) %:% when(i > 0) %:% foreach(j = ys) %do% body nests the stages, and a later stage and the body read every earlier stage’s iterators.

%do% runs the body in the calling frame, as a for loop does, so a write there is visible after the loop and each iterator is left at its element type joined with NULL. A parallel backend (%dopar%, doRNG’s %dorng%) runs the body in an environment of its own, so its writes do not reach the caller.

The result follows each stage’s .combine, innermost stage first:

foreach() options Result for a body of type T
no .combine list[T]
.combine = c (or "c") and T an atomic scalar or vector the vector of T’s element
any other .combine, .init or .final Any

So foreach(g = groups, .combine = c) %do% sum(g) with groups: list[integer[]] is integer[].

A while loop takes a scalar condition, which is re-evaluated before every iteration, so reads in the condition see the loop’s joined state. The loop evaluates to NULL.

A repeat loop has no condition and is left only through a break, so after the loop a variable holds the union of the types it had at each break. In repeat { s <- "a"; if (done) break; s <- 1L }, s is character afterwards. 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.

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.

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. The exception is the body of a top-level if (FALSE), which holds example code R never runs: its assignments bind local scratch names that no other item sees and that are never reported unused, <<- included, while its calls are still checked.

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. A slot that only some paths write resolves outward on the others, so the read takes both types.
  • 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.

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.

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:

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 abstract 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.
  • An unannotated parameter whose default is a string, number or logical literal, as in function(r, cor = "cor"), holds no function unless the caller passes one, so the lookup skips it and cor(r, r) calls stats::cor.
  • 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.

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).
  • 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 of an own pkg::name read is checked against what the installed package will export: the export() and exportMethods() names in NAMESPACE, and, when DESCRIPTION sets LazyData: true, the datasets under data/ (every object of an .rda file, and the stem of a .csv, .tab or .txt file). Without LazyData, :: cannot reach a dataset, which only data() loads. The read is checked against NAMESPACE, not against what the sources bind, because a package exports names its sources never bind (re-exports, S4 generics, datasets) and binds internals R refuses to read with ::. A name the package defines but does not export warns that the read fails once the package is installed, and suggests exporting it or writing pkg:::name. Any other name warns “not exported”, with the nearest export as a suggestion when there is one. The check is off when the package has no NAMESPACE, when NAMESPACE has an exportPattern(), and when a lazy-loading package’s data/ holds an .R file, because each makes the export set unknowable. pkg:::name is never checked.
  • 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. When two namespaces declare the same name, a bare reference takes the declaration that loads last, but pkg::name always takes pkg‘s own: with rugarch imported, sigma(fit) is rugarch’s and stats::sigma(fit) is stats’. A name only another namespace declares, such as a re-export, takes that declaration. A name that only the namespace’s export manifest 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.
  • A read that is the whole expression of try(), or of a tryCatch() with an error or condition handler, is a feature probe, so a missing name is not reported there: try(parallel::splitList, silent = TRUE) asks whether the running R has it, and so does a call of the read, try(pkg::f(x)). A read anywhere else in the expression is ordinary code and is checked.
  • R’s own manifests list the Windows-only exports of base, utils and grDevices on every platform, so utils::readRegistry and grDevices::win.metafile validate on Linux and macOS, where code reaches them behind a platform test.
  • A conditional namespace, 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)

Section titled “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 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.

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). 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). 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.

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 list(A, B) becomes list[A | B | V], because the write may replace any item or add one.
  • A write at a literal position of a tuple-like x, x[[2]] <- v, sets that item’s type, and a write at the position just past the last item appends one, so after d <- list(3L); d[[2]] <- list(x = 1, y = 2), d[[2]]$y is a double.
  • 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 NULL x is the empty vector, so out <- c(); out[i] <- paste0("row", i) makes out a character[]. 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. When the last top-level write of f in its file is body(f) <- v (or base::body(f) <- v), the earlier f <- make(g) builds a template whose code never runs as written, so a function argument such as g is not held to what that code would do with it. formals(f) <- v keeps the body, so it makes no template. When formals(f) <- v, formals(f)[["x"]] <- v or formals(f)$x <- v is that last write, f takes ...: Any in place of its written parameters and keeps the result its body computes, because the new parameter list is computed: after formals(glm_control) <- c(formals(glm_control), list(compDev = TRUE)), glm_control(compDev = FALSE) checks.
  • names(x) <- c("a", "b") with literal names, as many as x has items, turns a list of known items into a record with those fields and renames a record’s fields. Computed names leave a list whose fields are not tracked, so x$a may read any item. Other replacement calls, such as 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), so guard the read with is.null before a use that needs a V.

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, because R raises object 'x' not found on that path. Inside a function, R reads a binding of the same name outside the function on that path instead (in an enclosing function, the package, or base R), so the read is reported only when no such binding exists, and otherwise types as the union of the local writes and that binding: after if (ok) limit <- 5L, a function reads limit as integer | character when the package binds limit <- "all". A function outside does not join: a local variable that shares a function’s name, such as if (trace) t2 <- proc.time() in a package that also defines a function t2, is a different thing that happens to have the same name, so the read types as the local writes alone. A path that skips every write and reaches the function is reported with the same finding, which names the function. 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, and neither does a block after a statement that cannot fall through, so a definition written after stop() never binds and a later read of it is maybe-undefined.
  • A read that no write can reach does not resolve to the variable at all (see the shadowing rule under 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. Two kinds of item are exceptions. An item with a #: annotation keeps its declared signature, so even when its body violates the annotation, every call site is still checked against it. An item whose every error is a value that does not fit a fixed type, an annotated binding’s (x: integer <- "a") or a ry record field’s (point$x <- "a"), keeps its type too, because the binding takes that fixed type whatever the value. After point$x <- "a", a later point[["w"]] is still reported.

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, and neither is a column update such as f[, y := v] or setnames(f, ...), which changes the table in place.

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, including a name first written after the on.exit call (on.exit(close(con)) before con <- file(path) is neither unused nor maybe undefined). The standard rollback guard is therefore clean:

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:

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

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:

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.

An assign whose name is computed, as in for (name in ls(env)) assign(name, env[[name]]), and a list2env(values, environment()) may bind any name in the running function’s frame. From that call on, a read in the function of a name that no visible binding holds is not reported and types as Unknown, and so is a read of a package function’s name such as layout$panels, which may now be a local. A called name keeps its function lookup, a read before the call is reported as usual, and a call that writes into another environment (envir = env for a parameter env) changes nothing.

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, @alias and @opaque 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.

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, @alias and @opaque 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, @alias and @opaque declarations are file-local, like a script’s.

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 stub declaration.

A called name is not a column reference, because R looks a called name up as a function and a column is a vector. So inside every mask except with() and within(), an unresolved called name is reported like any other: mutate(d, b = scale_it(a)) reports scale_it when nothing defines it. with() and within() evaluate in any list or environment, which may hold functions, so their called names stay quiet. The names a mask provides without an import also stay quiet: data.table’s .(), J(), :=, let() and patterns(), and tidyselect’s selection helpers (where(), starts_with(), everything() and the rest), which tidyselect makes available in every selection.

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.

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:

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.

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

price_of <- function(prices: DataFrame{id: integer[], price: double[]}) -> double[] 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 or a base data.frame with known columns is written data.table{...} or data.frame{...} 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:

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

A list literal’s column takes the R type of its items: [1, 2] is an I64 list, so it makes an integer column, as [1L, 2L] does, and [1.5, 2] makes a double column. An I64 value too large for R’s integer turns the column into a double column when the code runs, which the type does not show.

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.

A List of tags without a payload is a tag column, and its type is the tag union: DataFrame(kind = [:Bond, :Cash]) is a DataFrame{kind: :Bond | :Cash}, and a column declared kind: :Bond | :Cash accepts only such a list. The frame stores the column as the character vector of the tag names, so a read from R code (df$kind, df[["kind"]], or the column’s name inside a data.table query) is a character[]. A tag compares with an expression by name (Expr.col("kind") == :Bond), and Expr.is_in takes a List of tags. A character[] value never fills a tag column, because its strings are not checked against the union. A tag with a payload has no column type.

Each verb of the DataFrame API 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); 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:

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:

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.

A frame whose columns are unknown also passes wherever a frame type that lists columns is expected, so outside strict mode as.DataFrame(frame) on a plain data.frame satisfies any DataFrame{...}. In strict mode that is an error at each return, argument and annotated binding where it happens, naming the variable the frame was converted from:

alias Rows = DataFrame{a: character, n: double}
load <- function(frame: data.frame) -> Rows {
as.DataFrame(frame)
}
x strict mode: the columns of `frame` are unknown, so nothing checks them against the columns this type lists. Give `frame` a type that lists its columns, as in `frame: data.frame{a: TYPE}`

With frame: data.frame{a: character, n: double}, a call passing a frame of other columns is a type error at the call.

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, and those calls compile to native code like the rest of the function:

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.

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:

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). 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:

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:

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

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:

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:

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:

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.

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:

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:

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:

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[]}

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:

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:

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:

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:

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.

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:

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

Section titled “Reading files and data.table’s functions”

data.table, 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.

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

Section titled “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, its bare names behave exactly like those of any package the stubs do not describe. A qualified call still reads its declarations, because :: loads a package without attaching it, so data.table::fifelse(test, 1, 2) is double[] in a script that never declares data.table. A declaration that names a type an inactive namespace defines, such as as.data.table’s data.table result, or PerformanceAnalytics::Return.calculate’s xts while xts is inactive, or that carries @masked, @opaque or @elementwise, needs the namespace active and is Unknown through :: until then.

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.

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.

  • 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.

  • A base generic that a stub types by its default method, such as str or print, gives Unknown when the package registers its own method for it (S3method(str, Logger)) and the first argument may carry a class: anything but an atomic vector, NULL or a function, or any parameter of the enclosing function, since a parameter’s type says nothing about its class attribute. The registered method decides the result, not the stub.

  • 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 as types, so new(...) is Any, and a call to a generic made by setGeneric gives Any, like a call to an S3 generic.

  • A named argument of new("Class", ...) must be one of the class’s slots, as R requires. The slots come from setClass’s representation(...) and slots = arguments, together with every class it contains, in the same file or anywhere in the package:

    setClass("Shape", representation("VIRTUAL", name = "character"))
    setClass("Circle", contains = "Shape", slots = list(radius = "numeric"))
    new("Circle", name = "unit", radius = 1) # fine
    new("Circle", radius = 1, colour = "red")
    # error[type-mismatch]: class `Circle` has no slot `colour`. Its slots are `name`, `radius`

    The check is skipped when a class on the chain is defined twice, has a computed slot list or parent, extends a class the project does not define (such as numeric or another package’s class), or has its own initialize method, which may take any argument.

  • x@slot reads an S4 slot and types as Unknown, and is a strict-mode origin, except on an Any subject, whose slots are Any like its $ fields. 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 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. 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

Section titled “Declaring a checked type for your own classes”

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

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

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 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, and it escalates unresolved references to errors. It also holds each function written in ry types to running natively.

Strict mode reports an Unknown once, where it enters: at the construct, read or call the checker could not type. A value computed from it, such as the result of a function that returns another function’s Unknown result, is not reported again. A call to a function that no stub declares is such an entry point, whether the function comes from base R, as R.home() and .Call(...) do, or from another package. #: @if-unknown TYPE on the binding that receives the result accepts it, and a stub line declaring the function removes the finding everywhere.

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 silenced, and points at the stub that would make it checkable. Without that, a clean run after library(unknownpkg) would look the same as a run that checked nothing.

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.

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

# 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.

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, alias or opaque 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. A call of a function declared pure only for pure callbacks, such as lapply, also needs the function it is passed to be pure: a function literal whose body has no effect, or the name of a pure function.

squares <- vapply(1:3, function(i) i * i, numeric(1))
widths <- lapply(list("a", "bb"), nchar)
printed <- lapply(1:3, print)
x strict mode: `lapply` calls `print` here, which is not declared pure, so it runs every time the
package loads. A file in `R/` may only define things at its top level: move the call into a
function, `.onLoad`, or the script `ry run` starts
--[R/main.R:3:24]

Inside local(), assignments and loops touch only the local environment and are allowed. A name bound there to a function literal may be called when the call has no effect: neither the defaults it evaluates nor the body, read with the bindings in place at the call, so rebinding a name the body calls after the function is defined counts. A call to a name bound inside that local() to anything else, including through a loop, a destructuring or a replacement such as body(f) <- ..., is an effect. 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.

A function is pure when calling it has no effect beyond returning a value, whatever its arguments. Purity is declared, and the declaration is trusted: ry does not check the body. The one exception is a function bound inside local(), whose body ry reads, because no other file can call it. 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(...), or with name : @pure(FUN) fn(...) when it is pure only for a pure function passed as FUN. @pure above anything but a top-level binding declares nothing and carries an annotation warning. 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.

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.

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:

describe <- function(x) cat("a value\n")
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. An R6 method, a function inside a list(...) passed to R6Class, is the exception: R6Class gives it no types, so it is judged like any other definition. 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.

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 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.

The one exception is a checked annotation over a value whose own type is Unknown. Such an annotation checks nothing, because Unknown satisfies every type, so it is reported in place of the origins it covers, and @if-unknown is the way to accept the value unchecked:

total <- function(df: data.frame) -> double {
#: double[]
amount <- as.numeric(df$amount) # covered: `as.numeric` returns `double[]`
#: double[]
prices <- df$price # strict: the annotation checks nothing
#: @if-unknown double[]
costs <- df$cost # accepted unchecked
sum(amount) + sum(prices) + sum(costs)
}

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:

label_width <- function(label: Str) -> I64 {
width <- nchar(label)
Num.from_r(width)
}
print(label_width("native"))
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), and so is a signature that is only the name of a type alias, which the preflight writes out as the function type it names.

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 function, a table function 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 one of these:

  • a ry value that shares R’s representation: an F64, Bool or Str, or a list of them;
  • Num.to_r(x) or List.to_r(x) written directly as the argument;
  • an R literal, such as 42L, NA, NA_real_ or 2i, which R evaluates itself;
  • a variable from outside the function that the function never assigns, such as a global. R reads it when the call runs, so the call sees the binding as it is then;
  • a call of a base R function, or a %op% operator of base R such as %in%, whose own arguments are only such literals, variables and calls, as in Expr.col("day") >= as.Date(start). R evaluates it lazily, when the outer call reads the argument, as it would without ry. A function that looks at the frame it is called from cannot stand there: get, assign, environment, parent.frame, sys.call, match.call, do.call, with, subset, stop, warning and the like. Neither can another package’s function, which may look at that frame as glue::glue does to find the variables it interpolates, nor an index such as month.name[1L].

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) or Expr.col("price") > limit; they may also be table values and nested table calls (Tables in typed code). This function is native:

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"))
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.

A native function reads a global that holds an F64, an I64, a Bool, a Str, a List of one of them, or a table value. The compiled code reads the binding each time it runs, so a call after the global is rebound sees the new value:

rate: F64 <- 0.25
taxed <- function(amount: F64) -> F64 amount * (1 + rate)
print(taxed(100))
rate <- 0.5
print(taxed(100))
1 file checked, no problems

The second call prints 150. A global that R code rebinds to a value of another type, as assign("rate", "high") does without a finding, stops the compiled code with an error that names the global and both types. With ry run --aot, a function that reads a global the script has not bound yet compiles at its first call instead of before the script starts.

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, and ry check --fix wraps the call in it. It makes no change when the call’s value is assigned to a variable that a later conversion reads, as width in the first example, or that an R call reads as a number or a list, which would then need Num.to_r or List.to_r. There the conversion moves by hand.

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:

report <- function(label: Str, amount: F64) -> NULL {
cat(label, format(amount, nsmall = 2), "\n")
NULL
}
report("total", 12.5)
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

ry check --fix --unsafe-fixes makes that rewrite. It is unsafe because the outer function may read the argument late, more than once or not at all, and computed first the inner call runs once, before the statement. It computes the inner call, converted, into a new variable on a line of its own just before the statement, above any #: lines of the statement, and passes the variable. The variable is value, or value2 and on when the function already uses that name:

report <- function(label: Str, amount: F64) -> NULL {
value <- Str.from_r(format(amount, nsmall = 2))
cat(label, value, "\n")
NULL
}
report("total", 12.5)
1 file checked, no problems

The rewrite runs the inner call before the statement, which is the one order native code can run. So --fix moves a call only where the statement runs it exactly once: never out of a branch, a loop, the condition of a while, the right side of && or ||, a function literal without braces, or the arguments of an R function that may evaluate them late, more than once or not at all, such as tryCatch, switch, ifelse, quote or a with... or suppress... function. The condition of an if runs first and once, so a call there moves before the if.

A variable that holds an R value, outside an R call’s arguments. A native function reads its own parameters and variables. A global that holds an R value may stand directly as an argument of an R call, which reads it, but anywhere else it is converted once, outside, and passed in:

#: character
unit <- Sys.getenv("UNIT")
label <- function(amount: F64) -> Str {
Str.concat(Num.to_str(amount), Str.from_r(unit))
}
print(label(2.5))
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:

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))
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.

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

ry check --fix wraps a column read in List.from_r where it is read, under the same condition as an R call’s result.

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 outside the arguments of an R call. 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:

count_up <- function(limit: I64) -> I64 {
total <- 0
step <- function(amount: I64) -> NULL {
total <<- total + amount
NULL
}
step(limit)
total
}
print(count_up(2))
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 function literal used as a value other than an argument, a function that a function returns, a call of a variable that holds a function define the function inside the native function, or pass it straight to the function that calls it
a recursive call that passes a function literal or local function that calls a function parameter, as in nest(n - 1, \(k) f(k) + 1) a loop, or pass the function on as it is and what the wrapper adds as a parameter of its own
an R function passed by name, as in List.map(xs, sqrt) the standard library function (Num.sqrt), or a function literal
a standard library function without native code, such as List.for_each_try 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 standard library function with named arguments (Num.is_approx_eq takes them) pass every argument by position
a call of a function parameter with named arguments pass every argument by position
a call that leaves out a parameter whose default is more than constants, operators, ry literals, the standard library’s constants and calls, and parameters or local variables the body does not set (the warning is on the default) compute the value in the body
missing(x) a default, such as a tag that marks the parameter missing
a call of a base R function that looks at the frame it is called from, such as assign, get, parent.frame or sys.call a function with an R type in its signature
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 that a branch or a loop defines again after an earlier definition, or one called after the branch or loop that defines it define it once at the top
a name read before the function sets it, as in acc <- acc + i in a loop that sets acc nowhere else, or after branches that set it to values of different types set it before the branch or loop, with one type
a name bound before a branch, a loop (its while condition included) or the right operand of && or || that takes a value of another type inside it, and branches that set a name to different types a new name for the new value
the value of an if without else an else branch that gives a value of the same type
xs[], and xs[i] with a fractional position such as xs[1.5] xs itself, or a whole-number position
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 of an open or generic type, an if or a match gives assign the expression to a variable, and apply the operator to the variable
a Dict whose keys are not I64, F64 or Str, or whose values hold something other than numbers, strings, Bools, lists, records, tuples and tags convert the keys to I64 or Str, and keep such values in a List whose positions the dictionary stores
a Set whose elements are not I64 or Str convert the elements to I64 or Str, or keep them in a List
a match guard that assigns a variable, a pattern with NA, NaN or a complex number, and a pattern other than a name or _ on a value that is not a number, a string, a logical, a List, a tag, a record or a tuple compute the value before the match, and bind the value to a name
a read of a global that holds a record, a tuple, a tag, a Dict or a Set, or of a variable of an enclosing boundary function pass the value in as a parameter
a function whose paths disagree about showing its value: one ends in an assignment, a loop or another expression whose value R returns invisibly, and another ends in a visible value or a return end every path the same way, for example with the value itself

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 name that a branch, a match arm or a loop body sets is read natively after it, and so is a name a loop body reads before a later statement of the body sets it, as last in for (x in xs) { if (x > 1) gap <- x - last; last <- x }, unless the read is inside a local function or a function literal, which runs in the interpreter. A call that reaches the read on a path that left the name unset stops there, and the interpreter runs the call again from the start, replaying its R calls as above, where R reads the name from outside the function or fails with object 'found' not found. This holds for native functions called from native code too.

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

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 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.

A file with syntax errors is still analyzed, under one rule: a broken region reports its syntax error and nothing else, strict mode included, 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.
  • 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.

Most gaps are silent, because a value the checker cannot type is Unknown and its checks are skipped. Strict mode reports most of the places they occur.

Not checked:

  • Base data frame columns from anything but data.frame(). Everything read out of a bare data.frame (from read.csv, merge and the like) is Unknown, so df$whatever passes even if the column does not exist. A data.frame{...} and a DataFrame type their 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 %op% operator that quotes an operand with substitute(), as magrittr’s %>% does, and any %op% operator defined inside a function.

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 vector of statically unknown length at a scalar parameter. p[file.exists(p)] returned through a function and passed to a stub’s scalar character parameter is reported, although the program guarantees one element. No type records the length.
  • A later top-level write in a package. A closure in a package reads a top-level name as its definition, so a later top-level x$a <- v is not seen there. Reads at top level and in a script see the write.