A rule states what must hold for a value of a struct, an enum variant, or
a table row: an R expression over its fields, captured unevaluated,
compiled when the type is declared, and evaluated in Rust each time a
value is built or a field it reads is replaced. rule(lo < hi) is a
complete rule; message states the requirement for the user, and id
gives the rule a stable name by which code and tests refer to it.
Arguments
- invariant
Expression: What must hold.
- when
Optional expression: The condition under which the rule applies.
- message
Optional character: What holds, stated for the user, such as
"lo is below hi."; without it, a violation shows the invariant.- id
Optional character: The rule's ID, an R8 name such as
"LO_HI", unique among its type's rules, which a violation andproblems$rulereport. In a list of rules, the name of a rule is its ID:list(order = rule(lo <= hi)).
One field
A bound, a set of allowed values, a pattern, or a length on one field is
an argument of the field's type, checked before any rule:
type_double(min = 0), type_integer(values = 1:3),
type_character(pattern = "^[A-Z]"), vec(type_double(), min_length = 1).
A rule on one field states what those arguments do not: k %% 2 == 0,
abs(x) <= 1, nchar(name) <= 20.
Several fields
A rule reads any fields by name, and nested fields with $:
lo < hi, lo + hi <= 1, kernel$gamma <= 10.
when limits a rule to the values for which a condition holds:
when = is_variant(kernel, "Rbf").
Optional fields
A rule holds when a field it reads is absent, so a rule over an
option() field applies once the field is present. is.null(x) tests
presence and is not a read: is.null(a) || !is.null(b) requires b
whenever a is present.
Rows
A rule of a new_table_type() or a type_table() reads the cells of one row by the
names of the columns; the cell of a factor is its label. A rule also chooses the
rows of a table (r8filter()), and then mean(), sum(), median(), min(),
max(), n(), and count() read whole columns, as in calc(). pmin() and
pmax() are of the cells of a row.
Missing values
A comparison with a missing cell or with NaN is missing, and so is an operation
with one, except is.na(); FALSE && NA is false and TRUE || NA is true, as in
R. x %in% c(1, 2) is missing where x is, where R gives FALSE. A check fails where the rule is false, and a filter keeps the rows where it is
true.
Vectors
all(x, <condition>) and any(x, <condition>) test a condition on each
element of the vector x, with .x the element: all(values, .x > 0).
A violation of an invariant that is an all() reports each failing
element's path. length(), sum(), mean(), min(), max(),
non_decreasing(), and non_increasing() read a whole vector, without
copying it. Paired elements of two vectors are columns of a
type_table(), whose rules apply to each row.
Constants
A bare name in a rule is always a field. val(expr) is the value of the
R expression expr, evaluated once when rule() runs: cost <= val(max_cost).
col(expr) is the field or column whose name the R expression expr gives:
col(m) > 0 with m <- "auc" is auc > 0. The arguments of val() and col()
are R; every other bare name is a field or a column. NA is the missing
constant, as a value of if; a comparison with NA is an error that names
is.na().
Operators and functions
Comparisons (==, !=, <, <=, >, >=), arithmetic (+, -,
*, /, %%, ^), logical operators (&&, ||, !; & and | are the
same as && and ||), %in%, if, is.na(), is.null(), is_variant(),
length(), nchar(), nrow(), ncol(), dim(), levels(),
abs(), sqrt(), log(), exp(), floor(), ceiling(), round(), min(),
max(), pmin(), pmax(), sum(), mean(), median(), n(), count(),
all(), any(), subset(), non_decreasing(), non_increasing(),
paste0(), c() of constants, NA, val(), and col(). na.rm = TRUE in
sum(), mean(), median(), min(), max(), and count() leaves out the
missing cells of a table's column.
Rules follow the strict semantics of R8's rule language, which is the
same in every host: == is strict equality, so an integer never equals a
string; strings do not order; a string compared with a date or a date-time is
one, "2020-01-31" or "2020-01-31T12:00:00Z"; a division by zero, sqrt() of
a negative number, log() of a number that is not positive, and a negative
number to a power that is not a whole number are errors; sum() is the exact
sum, rounded once, and mean() that sum over the count; and
== on a double computed by arithmetic, sum(), or mean() is a declaration
error, since rounding makes it inexact: abs(sum(p) - 1) <= 1e-9 states the
tolerance.
Rules of rules
A rule is a value. !, &, and | make a rule of others, !adult & woman,
without an ID and a message.
Package code
R CMD check takes a bare name in a function for a variable that nothing binds.
A function of a package quotes the condition, rule(quote(age >= val(cutoff))),
which is the same rule.
Words that differ from R
The dialect is R syntax with its own meanings; these words differ from the R functions of the same name, or exist in rules only:
| Word | In a rule |
is_variant(x, "V") | The variant of the enum field x is V; R tests a value with r8is_variant(). |
all(x, cond), any(x, cond) | cond holds for every or some element .x of x. |
subset(x, y) | Every element of the vector x is an element of y. |
non_decreasing(x), non_increasing(x) | The vector x is in order. |
&, \| | The same as && and \|\|. |
== | Strict equality: values of different types are never equal. |
val(expr) | The value of the R expression expr, a constant. |
col(expr) | The field or column whose name the R expression expr gives; col() is the column that r8map() maps. |
n(), count(cond) | The rows of a table or of a group, and those where cond is true. |
Violations
A violation is an r8_value_error that shows the rule's ID and message,
when it has them, the path, the rule in R, and the values it read: the scalar fields, the
length or dimensions of larger fields, computed operands such as
sum(p), and the failing elements .x of an all(). A field declared
field(..., sensitive = TRUE) shows as <sensitive>, and
options(r8.show_values = FALSE) shows no values. The condition's field
problems is a data frame of the problems: code, path, rule,
message, rule_index (the rule's position among its type's rules), and
the list column diagnosis.
Examples
op <- options(r8.namespace = "demo")
max_cost <- 100
Kernel <- new_enum(
"Kernel",
variants = list(
Linear = variant(),
Rbf = variant(fields = list(gamma = type_double(exclusive_min = 0)))
)
)
Model <- new_struct(
"Model",
fields = list(
cost = type_double(min = 0),
kernel = Kernel,
lo = type_double(),
hi = type_double(),
weights = vec(type_double(min = 0))
),
rules = list(
rule(lo < hi),
rule(cost <= val(max_cost), message = "cost is at most max_cost."),
rule(abs(sum(weights) - 1) <= 1e-9, message = "weights sum to 1.", id = "WEIGHTS"),
rule(kernel$gamma <= 10, when = is_variant(kernel, "Rbf"), message = "gamma is at most 10.")
)
)#> Warning: The declaration of `demo::Model` leaves `demo::LinearModel` stale: it extends an earlier declaration. Declare it again, parent before child.Model(cost = 1, kernel = Kernel@Linear, lo = 0, hi = 1, weights = c(0.5, 0.5))#> <demo::Model>
#> cost: 1
#> kernel: <demo::Kernel@Linear>
#> lo: 0
#> hi: 1
#> weights: double[2] 0.5 0.5try(Model(cost = 1, kernel = Kernel@Linear, lo = 2, hi = 1, weights = 1))#> Error : Invalid `demo::Model`: 1 problem
#> - Rule: lo < hi; found lo = 2, hi = 1. [rule_violation]options(op)