# Language tour

ry is a type checker and a fast runtime for R, written in Rust. This page shows every feature once,
code first and with real output, in the order you meet them: the commands, checking and typing R
code, ry's own data types, strict mode, and the tooling around them. Each section links to its
rules, and the page is also served as Markdown at [`/ry.md`](/ry.md).

## Commands

```sh
ry check [PATHS]        # report problems; exit status 1 if there are any
ry check --fix          # apply safe fixes (--unsafe-fixes for the rest)
ry fmt [PATHS]          # format in place (--check only lists unformatted files)
ry run [FILE]           # run a script on ry's runtime, or open its console
ry R [FILE]             # run on the GNU R installed on your machine
ry load -e EXPR         # load the package in this directory and evaluate EXPR
ry test                 # testthat tests against the loaded package
ry document             # roxygen2 against the loaded package
ry migrate data-table   # rewrite data.table code as DataFrame code
ry server               # the language server, which your editor starts
```

Checking, formatting and the editor never run R. [Installation](/installation.md) has the binaries,
and [CLI](/reference/cli.md) lists every flag.

## Configuration

One `ry.toml` at the project root configures everything, and every key is optional:

```toml
[check]
typing = false               # report type errors
strict = false               # also reject values whose type is unknown
inline-annotations = true    # false warns at every inline annotation
object-systems = true        # false makes S4, R6 and Reference Classes an error
exclude = []                 # gitignore-style patterns

[lint]
single-quotes = "warn"       # every lint takes "off", "warn" or "error"

[format]
indent-width = 2
```

A `# typing: strict` comment overrides the project for one file, and `# ry: allow(code)` silences
one finding. [Configuration](/reference/configuration.md) lists every key.

## Checking plain R

Without any configuration, ry resolves every name by R's scoping rules and runs its lints:

```r
if (x == NA) print("missing")
```

```text
unresolved

  ! I could not resolve `x` in this package, its imports, or builtins.

equals-na

  ! Comparing with NA always gives NA, whatever the other side holds. Use is.na() to test for missing values
```

ry reads a project the way R does: `R/` is one package namespace, scripts follow their `source()`
calls, and `.Rmd` and `.qmd` chunks form one script. Data-masking calls such as dplyr verbs and
`with()` are understood. [Diagnostic codes](/reference/diagnostic-codes.md) lists every lint.

## Inferred types

With `typing = true`, types are inferred from use, so unannotated code is checked:

```r
half <- function(x) x / 2
half("4")
```

```text
type-mismatch

  x expected a numeric value (`integer` or `double`), found `character`
```

## Annotations

An annotation pins a contract. Each one has a comment spelling, which keeps the file plain R for
every other tool, and an inline spelling, which is shorter. ry's runtime checks both at the
function's boundary:

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

gross_price <- function(price: double, rate: double) -> double price * (1 + rate)
```

GNU R cannot parse the inline spelling, so such a file runs through `ry run`, or through `ry R`,
which erases the annotations. When a comment and an inline annotation disagree, ry uses the inline
one and warns. [The guide](/guide.md#annotate) shows both side by side.

## Types

```text
integer, double, character, logical    # exactly one element
integer[], double[named]               # a vector of any length, optionally named
list{name: character, retries: integer}  # a list with fixed fields
list[integer]                          # a list of any length
character | NULL                       # a union; is.null() narrows it
fn(x: double) -> double                # a function
<T: numeric> fn(x: T) -> T             # a generic function
Any                                    # a deliberate opt-out
Unknown                                # what ry could not infer

I64, F64, Bool, Str                    # ry's own scalars, never NA
Record{x: F64, y: F64}                 # a record
Tuple{I64, Str}                        # a tuple
List<F64>                              # a list of one item type
:Open | :Closed(code: I64)             # a union of tags
Result<I64, :InvalidNumStr>            # :Ok(I64) or :Err(:InvalidNumStr)
Dict<Str, I64>                         # also Set<T>
```

A field that does not exist is an error, and `is.null()` narrows a union:

```r
label <- function(config: list{name: character, retries: integer} | NULL) -> character {
  if (is.null(config)) return("default")
  config$nmae
}
```

```text
type-mismatch

  x field `nmae` does not exist in `list{name: character, retries: integer}`. Did you mean `name`?
```

A `double` accepts an `integer` or `logical`, but a number never passes for a `character`. Where
inference gives up, `#: @if-unknown TYPE` fills in a type the checker could not find, and
`#: @trust TYPE` overrides the one it found. The [type system](/reference/type-system.md) has every
rule.

## Records, tuples and lists

Records, tuples, lists, tags and `DataFrame` are ry's own data types, and code that uses them runs
only on ry's runtime. A record has named fields and value semantics, a tuple has positions, and a `List` holds items of one type with no `NA`, no names
and no recycling:

```r
point <- (x = 1, y = 2)
point$x
#> [1] 1
(..point, y = 5)
#> (x = 1, y = 5)
(1L, "a")
#> (1L, "a")
xs <- [1.5, 2, 3]
List.map(xs, function(x) x * 2)
#> [3, 4, 6]
```

A one-field record needs a trailing comma, as in `(x = 1,)`. Passing a record to an R function is an
error until you convert it with `as.list()`.

## Tags and `match`

A tag is a name with an optional payload, and an alias names a union of tags. `match` must handle
every case:

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

area <- function(s: Shape) -> double {
  match (s) {
    :Circle(radius = r) => pi * r^2
    :Rect(width = w, height = h) => w * h
  }
}
area(:Rect(width = 2, height = 3))
```

```text
[1] 6
```

A missing case is a `non-exhaustive-match` error. Patterns are `_`, a name, a literal, a tag,
`(p, q)`, `(x = p, ..)`, `[first, ..rest]`, `p as name`, `p | q` and `p if (cond)`.

## Errors as values

Functions that can fail return `:Ok(value)` or `:Err(reason)`, and `try` returns an `:Err` from the
enclosing function early:

```r
List.first([])
#> :Err(:ListWasEmpty)
parse_sum <- function(a: Str, b: Str) -> Result<I64, :InvalidNumStr> {
  x <- try Str.to_i64(a)
  y <- try Str.to_i64(b)
  :Ok(x + y)
}
parse_sum("1", "2")
#> :Ok(3i64)
parse_sum("1", "two")
#> :Err(:InvalidNumStr)
Result.with_default(parse_sum("1", "two"), 0)
#> 0i64
```

`I64`, `F64`, `Bool` and `Str` are ry's own scalars, which never hold `NA`. The standard library has
seven modules, `Result`, `List`, `Str`, `Num`, `Bool`, `Dict` and `Set`, called by qualified names.
[Standard library](/reference/standard-library.md) lists every function, and
[Typed ry](/reference/language.md) tours the part of ry written only in these types.

## Nominal types

A `type` is distinct from every other type, even one with the same shape, and `@Name(value)`
creates a value of it:

```r
type Celsius = Record{degrees: double}
type Fahrenheit = Record{degrees: double}

boiling <- function(t: Celsius) -> logical t$degrees >= 100
boiling(@Celsius((degrees = 120,)))
```

```text
[1] TRUE
```

Passing a `Fahrenheit` to `boiling` is a type error. An `alias`, as for `Shape` above, is only a
name for a structure.

## DataFrame

ry's typed table runs on the Polars engine. The checker follows every column through every step, so
a misspelled column is an error before the query runs:

```r
sales <- DataFrame(region = ["eu", "us", "eu"], units = [3L, 5L, 2L], price = [1.5, 2, 3])
sales |>
  DataFrame.with_columns(revenue = Expr.col("units") * Expr.col("price")) |>
  DataFrame.group_by("region") |>
  GroupBy.agg(total = Expr.col("revenue") |> Expr.sum())
#>    region total
#>    <char> <num>
#> 1:     eu  10.5
#> 2:     us  10.0
```

Existing data.table code runs unchanged, on data.table's own R and C code.
[DataFrames](/reference/dataframes.md) has the API.

## Strict mode

`strict = true` makes every value without a known type an error, so a clean run means every value
is typed:

```r
total <- function(df) sum(df$amount)
```

```text
strict

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

`ry check --annotate` writes the inferred types into the file. Under strict mode, `ry run` and
`ry load` refuse code with a strict-mode error, and a typed function compiles to native code before
its first call. `ry run --aot` compiles every typed function of the script before the script
starts. Typed ry is strict: a typed function's call of another typed function computes every
argument before the call, while an argument written in R code stays lazy. A function whose signature
is written entirely in ry types runs natively, and strict mode says where one would not: an R value
used outside a conversion such as `Num.from_r` is an error with the code `native`, and a construct
the native compiler does not compile yet, such as `try` or a list pattern, is a warning with the
code `interpreted`. A function with an R type in its signature is where R values and ry values
meet, and it is not judged.
[Strict mode](/reference/type-system.md#strict-mode) lists what it reports.

## Loading packages

`ry run` inside a package opens a console that reloads exactly the definitions you changed before
each command. On a package of about 300,000 lines, a cold load takes under 2 s against about 10 s for
`devtools::load_all()`, and a reload after an edit takes under 100 ms against about 9 s. In RStudio,
`source(pipe("ry load --r-entry"))` in `~/.Rprofile` gives you the same fast `load_all()`.
[Package loading](/reference/package-loading.md) has the details.

## Editor

`ry server` gives any LSP editor diagnostics as you type, hover with inferred types, completion,
go to definition, references, rename, inlay hints, quick fixes and refactorings. The VS Code
extension adds a debugger, a console, a data viewer and a plot panel.
[Installation](/installation.md#editors) sets each editor up.

## Performance and status

ry's runtime is faster than GNU R on each of its benchmark suites taken as a whole, and on most
programs in them. The margin is widest on scalar loops and narrowest on call-heavy code and
package test suites. A few allocation-heavy programs, such as fannkuch-redux and building binary
trees, run at GNU R's speed or slower. Typed code in strict mode is faster again.
[Benchmarks](/benchmarks.md) has the numbers.

ry is in beta. The checker, language server, formatter and loader are ready for daily use, and
diagnostic codes, `ry.toml` keys and the JSON output are stable. ry's runtime is incomplete: a
script that needs something it lacks stops with an error that names it, and `ry R` runs plain and
inline-annotated R on GNU R instead.
