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.
Commands
Section titled “Commands”ry check [PATHS] # report problems; exit status 1 if there are anyry 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 consolery R [FILE] # run on the GNU R installed on your machinery load -e EXPR # load the package in this directory and evaluate EXPRry test # testthat tests against the loaded packagery document # roxygen2 against the loaded packagery migrate data-table # rewrite data.table code as DataFrame codery server # the language server, which your editor startsChecking, formatting and the editor never run R. Installation has the binaries, and CLI lists every flag.
Configuration
Section titled “Configuration”One ry.toml at the project root configures everything, and every key is optional:
[check]typing = false # report type errorsstrict = false # also reject values whose type is unknowninline-annotations = true # false warns at every inline annotationobject-systems = true # false makes S4, R6 and Reference Classes an errorexclude = [] # gitignore-style patterns
[lint]single-quotes = "warn" # every lint takes "off", "warn" or "error"
[format]indent-width = 2A # typing: strict comment overrides the project for one file, and # ry: allow(code) silences
one finding. Configuration lists every key.
Checking plain R
Section titled “Checking plain R”Without any configuration, ry resolves every name by R’s scoping rules and runs its lints:
if (x == NA) print("missing")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 valuesry 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 lists every lint.
Inferred types
Section titled “Inferred types”With typing = true, types are inferred from use, so unannotated code is checked:
half <- function(x) x / 2half("4")type-mismatch
x expected a numeric value (`integer` or `double`), found `character`Annotations
Section titled “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:
#: fn(price: double, rate: double) -> doublenet_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 shows both side by side.
integer, double, character, logical # exactly one elementinteger[], double[named] # a vector of any length, optionally namedlist{name: character, retries: integer} # a list with fixed fieldslist[integer] # a list of any lengthcharacter | NULL # a union; is.null() narrows itfn(x: double) -> double # a function<T: numeric> fn(x: T) -> T # a generic functionAny # a deliberate opt-outUnknown # what ry could not infer
I64, F64, Bool, Str # ry's own scalars, never NARecord{x: F64, y: F64} # a recordTuple{I64, Str} # a tupleList<F64> # a list of one item type:Open | :Closed(code: I64) # a union of tagsResult<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:
label <- function(config: list{name: character, retries: integer} | NULL) -> character { if (is.null(config)) return("default") config$nmae}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 has every
rule.
Records, tuples and lists
Section titled “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:
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
Section titled “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:
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))[1] 6A 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
Section titled “Errors as values”Functions that can fail return :Ok(value) or :Err(reason), and try returns an :Err from the
enclosing function early:
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)#> 0i64I64, 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 lists every function, and
Typed ry tours the part of ry written only in these types.
Nominal types
Section titled “Nominal types”A type is distinct from every other type, even one with the same shape, and @Name(value)
creates a value of it:
type Celsius = Record{degrees: double}type Fahrenheit = Record{degrees: double}
boiling <- function(t: Celsius) -> logical t$degrees >= 100boiling(@Celsius((degrees = 120,)))[1] TRUEPassing a Fahrenheit to boiling is a type error. An alias, as for Shape above, is only a
name for a structure.
DataFrame
Section titled “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:
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.0Existing data.table code runs unchanged, on data.table’s own R and C code. DataFrames has the API.
Strict mode
Section titled “Strict mode”strict = true makes every value without a known type an error, so a clean run means every value
is typed:
total <- function(df) sum(df$amount)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 lists what it reports.
Loading packages
Section titled “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 has the details.
Editor
Section titled “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 sets each editor up.
Performance and status
Section titled “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 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.