Skip to main content

5  Rules

A field type’s constraints limit one value at a time. A rule states what must hold beyond them: an R expression over the fields, which R8 compiles when the type is declared and evaluates in Rust each time a value is built or a field that the rule reads is replaced.

5.1 A rule

rule() takes the expression that must hold. message states the requirement for the user, and id names the rule for code. rule(lo <= hi) is a complete rule:

Interval <- new_struct(
  "Interval",
  description = "The numbers from lo to hi.",
  fields = list(lo = type_double(), hi = type_double()),
  rules = rule(lo <= hi, message = "lo is at most hi.", id = "ORDER")
)
unit <- Interval(lo = 0, hi = 1)

A violation shows the message, the expression, and the values it read:

Interval(lo = 2, hi = 1)
Error:
! Invalid `demo::Interval`: 1 problem
- Rule ORDER: lo is at most hi. [rule_violation]
  lo <= hi; found lo = 2, hi = 1

A replaced field is checked against the rules that read it:

unit$lo <- 3
Error:
! Invalid `demo::Interval` from `x$lo <- value`: 1 problem
- Rule ORDER: lo is at most hi. [rule_violation]
  lo <= hi; found lo = 3, hi = 1

Fields replaced together are checked once, after all of them, so a rule between two fields holds for the result:

unit[c("lo", "hi")] <- list(3, 5)
unit
<demo::Interval>
  lo: 3
  hi: 5

Rules run once the fields themselves are valid, so an expression reads values of the declared types. Several rules are given as a list.

5.2 One field

A rule on one field states what its type’s constraints do not. Here the probabilities are in increasing order:

Quantiles <- new_struct(
  "Quantiles",
  fields = list(
    probs = vec(type_double(exclusive_min = 0, exclusive_max = 1), min_length = 1L)
  ),
  rules = rule(non_decreasing(probs))
)
Quantiles(probs = c(0.9, 0.1))
Error:
! Invalid `demo::Quantiles`: 1 problem
- Rule: non_decreasing(probs); found length(probs) = 2. [rule_violation]

5.3 Absent fields

A rule holds when a field it reads is absent. This one applies once patience is given:

EarlyStopping <- new_struct(
  "EarlyStopping",
  fields = list(
    n_trees = type_integer(min = 1L),
    patience = option(type_integer(min = 1L))
  ),
  rules = rule(patience < n_trees, message = "patience is less than n_trees.")
)
EarlyStopping(n_trees = 100L)
<demo::EarlyStopping>
  n_trees: 100
  patience: NULL
EarlyStopping(n_trees = 100L, patience = 200L)
Error:
! Invalid `demo::EarlyStopping`: 1 problem
- Rule: patience is less than n_trees. [rule_violation]
  patience < n_trees; found patience = 200, n_trees = 100

is.null(x) tests presence and is not a read, so is.null(a) || !is.null(b) requires b whenever a is present.

An absent field, a missing cell, and a comparison with NaN are missing. Conditions combine as in R, in either order: FALSE && NA is false and TRUE || NA is true. A rule fails where it is false.

5.4 Conditions

when limits a rule to the values for which a condition holds. $ reads a field of a field, and is_variant(x, "Variant") tests an enum’s variant:

Search <- new_struct(
  "Search",
  fields = list(
    subsample = type_double(exclusive_min = 0, max = 1),
    resampler = Resampler
  ),
  rules = list(
    rule(
      subsample == 1,
      when = is_variant(resampler, "Bootstrap"),
      message = "subsample is 1 with bootstrap resampling.",
      id = "BOOTSTRAP_SUBSAMPLE"
    ),
    rule(
      resampler$n_resamples <= 20,
      when = is_variant(resampler, "KFold"),
      message = "k-fold cross-validation uses at most 20 folds.",
      id = "KFOLD_MAX"
    )
  )
)
Search(subsample = 0.8, resampler = cv)
<demo::Search>
  subsample: 0.8
  resampler: <demo::Resampler@KFold>
    n_resamples: 10
    seed: 2026
Search(subsample = 0.8, resampler = Resampler@Bootstrap())
Error:
! Invalid `demo::Search`: 1 problem
- Rule BOOTSTRAP_SUBSAMPLE: subsample is 1 with bootstrap resampling. [rule_violation]
  subsample == 1, when is_variant(resampler, "Bootstrap"); found subsample = 0.8

5.5 Vectors

all(x, condition) and any(x, condition) test a condition on each element of x, with .x the element. Resamples holds the training cases that a resampler drew. Its rule has one all() for the resamples and one for the cases of each:

Resamples <- new_struct(
  "Resamples",
  description = "The training cases of each resample.",
  fields = list(
    resampler = Resampler,
    n_cases = type_integer(min = 1L),
    train = vec(vec(type_integer(min = 1L)), min_length = 1L)
  ),
  rules = rule(
    all(train, all(.x, .x <= n_cases)),
    message = "A training case is at most n_cases.",
    id = "IN_RANGE"
  )
)

An error names each element that fails:

Resamples(resampler = cv, n_cases = 3L, train = list(c(1L, 2L), c(2L, 4L)))
Error:
! Invalid `demo::Resamples`: 1 problem
- Rule IN_RANGE: A training case is at most n_cases. [rule_violation at train[[2]]]
  all(train, all(.x, .x <= n_cases)); found length(train) = 2, n_cases = 3, length(.x) = 2 at train[[2]]

length(), sum(), mean(), min(), max(), non_decreasing(), and non_increasing() read a whole vector in place, without copying it:

ClassWeights <- new_struct(
  "ClassWeights",
  fields = list(weights = vec(type_double())),
  rules = list(
    rule(all(weights, .x > 0), message = "Each weight is positive.", id = "POSITIVE"),
    rule(abs(sum(weights) - 1) <= 1e-9, message = "The weights sum to 1.", id = "SUM_TO_1")
  )
)
ClassWeights(weights = c(0.6, -0.1, 0.4))
Error:
! Invalid `demo::ClassWeights`: 2 problems
- Rule POSITIVE: Each weight is positive. [rule_violation at weights[[2]]]
  all(weights, .x > 0); found length(weights) = 3, .x = -0.1 at weights[[2]]
- Rule SUM_TO_1: The weights sum to 1. [rule_violation]
  abs(sum(weights) - 1) <= 1e-09; found length(weights) = 3, abs(sum(weights) - 1) = 0.09999999999999998

R’s one-argument all(weights > 0) is an error that writes the two-argument form:

rule(all(weights > 0))
Error:
! `all()` in a rule takes a vector and a condition on each of its elements, `.x`: write `all(weights, .x > 0)`.

Two vectors compared element by element are columns of a type_table(), whose rules apply to each row.

5.6 Rows

A rule of a table reads the cells of one row by the names of its columns, and is evaluated by column. The same rule chooses the rows of a table (Rows and columns):

taller <- rule(sitting < standing)
Heights <- new_table_type(
  "Heights",
  columns = list(
    sitting = type_double(min = 0),
    standing = type_double(min = 0)
  ),
  rules = taller
)
Heights(sitting = c(88, 91), standing = c(170, 19))
Error:
! Invalid `demo::Heights`: 1 problem
- Rule: sitting < standing; found sitting = 91, standing = 19. [rule_violation at sitting[[2]]]
r8filter(Raven(sitting = c(88, 91), standing = c(170, 19)), !taller)
<raven table> 1 row ⨉ 2 columns
   sitting  standing
    double    double
1       91        19

5.7 Constants

A bare name in a rule is a field. val(expr) is the value of the R expression expr, evaluated once, when rule() runs: a number, a logical, a string, a Date, or a POSIXct.

max_trees <- 5000L

Forest <- new_struct(
  "Forest",
  fields = list(n_trees = type_integer(min = 1L)),
  rules = rule(n_trees <= val(max_trees))
)
Forest(n_trees = 6000L)
Error:
! Invalid `demo::Forest`: 1 problem
- Rule: n_trees <= 5000L; found n_trees = 6000. [rule_violation]

In a package, it is the value at installation. A name that is not a field reports the nearest field and the val() form:

Forest <- new_struct(
  "Forest",
  fields = list(n_trees = type_integer(min = 1L)),
  rules = rule(n_tres <= max_trees)
)
Error:
! Declaration of `demo::Forest` failed:
- `n_tres` is not a field in scope; the nearest field is `n_trees`; if `n_tres` is an R variable, write `val(n_tres)` [rule_field at /rules/0/invariant/<=/0/var]
  in `n_tres <= max_trees`
- `max_trees` is not a field in scope; if `max_trees` is an R variable, write `val(max_trees)` [rule_field at /rules/0/invariant/<=/1/var]
  in `n_tres <= max_trees`

5.8 Operators and functions

Kind In a rule
Comparison ==, !=, <, <=, >, >=
Arithmetic +, -, *, /, %%, abs(), sqrt(), log(), exp(), floor(), ceiling(), round(), pmin(), pmax()
Logical &&, \|\|, ! (& and \| are the same as && and \|\|), if
Membership %in%, subset(), c() of constants
Presence and variants is.na(), is.null(), is_variant()
Size length(), nchar(), nrow(), ncol(), dim(), levels()
Vectors all(), any(), sum(), mean(), min(), max(), non_decreasing(), non_increasing()
Strings paste0()
Constants from R val()

Rules evaluate in R8’s rule language, whose semantics are the same in every host:

  • == is strict equality: a number never equals a string.
  • Strings do not order, since R orders strings by locale.
  • A string compared with a date or a date-time is one: day >= "2020-01-31".
  • A division by zero, sqrt() of a negative number, and log() of a number that is not positive are errors. An operand that decides absorbs one: x != 0 && 1 / x > 2.
  • sum() is the exact sum, rounded once, and mean() that sum over the count, the same in every host; the last digits can differ from R’s.
  • == and != on a double computed by arithmetic, sum(), or mean() are a declaration error, since rounding makes the result inexact; a tolerance states the comparison:
Split <- new_struct(
  "Split",
  fields = list(train = type_double(), test = type_double()),
  rules = rule(train + test == 1)
)
Error:
! Declaration of `demo::Split` failed:
- `===` compares a double computed by arithmetic, which rounding makes inexact; compare the difference with a tolerance, as in `abs(a - b) <= 1e-9` [rule_float_equality at /rules/0/invariant/===/0]
  in `train + test`

5.9 Messages and IDs

A rule without a message shows its expression, which is often clear enough: rule(patience < n_trees). A message serves a rule whose expression does not read as its requirement, such as "The weights sum to 1." for abs(sum(weights) - 1) <= 1e-9.

An ID gives a rule a stable name, unique within the type, so that code and tests refer to the rule when its expression changes. An ID is written in capitals, such as "SUM_TO_1". A rule without one is reported by its position.

5.10 Violations in code

A violation is an r8_value_error. The condition’s field problems is a data frame with a row for each problem, so code compares data rather than wording:

violation <- tryCatch(
  ClassWeights(weights = c(0.6, -0.1, 0.4)),
  error = identity
)
violation$problems[, c("code", "path", "rule")]
            code       path     rule
1 rule_violation /weights/1 POSITIVE
2 rule_violation            SUM_TO_1

It also holds each path in R syntax (where), the position of a rule (rule_index), the nearest allowed value or field name (suggestion), and a hint for a common mistake (hint).

A field declared field(type, sensitive = TRUE) shows as <sensitive>, and options(r8.show_values = FALSE) shows no values in messages or in problems.

© 2026 E.D. Gennatas