Skip to contents

mir_compile() takes an R function written in a small numeric subset of R and returns a function with the same arguments that runs compiled code. It returns exactly what the R function returns, or an error: never a different answer.

Usage

mir_compile(f, tier = NULL)

Arguments

f

A function.

tier

"native" or "interp"; by default zumir_tier().

Value

A function of class zumir_compiled, with f's arguments.

Details

The subset is scalar doubles, double vectors indexed in loops, conditions and a table of maths. In detail:

  • Arguments are doubles without attributes. One that is indexed (x[i]), passed to length() or to seq_along() is a vector; any other must have length one when called. Arguments are never assigned to, have no defaults, and there is no ....

  • Locals are double or logical scalars, for loop counters, and double vectors made by one y <- numeric(size) at the top of the body, before any loop or branch, changed only by y[i] <- value. size may use constants, arguments, length() of arguments and arithmetic. Every local is assigned on every path before it is read.

  • {, <-, =, if/else, while, for over seq_len(n), seq_along(x) and a:b, break, next, return().

  • + - * / ^ %% %/%, unary -, comparisons, !, &&, ||; exp, log, log1p, expm1, sqrt, abs, floor, ceiling, trunc, sin, cos, tan; two-argument min and max; length, is.na, is.nan, is.finite, as.double.

  • The result is a double scalar or a vector local, never an empty block ({}, which is NULL in R). Each construct takes the arguments R accepts; any other count is a compile error.

Every argument the body reads, on any path, is evaluated before the compiled code runs, since types are inferred over the whole body. An argument R would never evaluate (in a branch not taken) is evaluated, its side effects happen, and a value outside the subset is an error where R might not have looked at it.

Where matching R exactly would not be cheap, the compiled function errors instead: an index out of range, NA or not a whole number; a seq_len() or a:b bound that is NA or not whole; integer overflow; an argument that is not a double, has attributes, or is a scalar of another length. Names must mean base R's functions in environment(f). Loops can be interrupted, as R's can. Code outside the subset is a compile error naming the construct.

Where an NA and a NaN meet in one operation, R leaves open which comes out (see NA), and so does mir_compile(): the answer can differ between R, the two tiers and builds, and is.nan() of such a value can take a different branch. is.na() is TRUE either way.

The article vignette("mir-compile", package = "zumir") lists the subset in full, every place it errors where R would answer, and why.

See also

Other compilers: cfunction(), mir_function()

Examples

ss <- mir_compile(function(x) {
  s <- 0
  for (i in seq_along(x)) s <- s + x[i] * x[i]
  s
})
ss(c(1, 2, 3))
#> [1] 14