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.
Arguments
- f
A function.
- tier
"native"or"interp"; by defaultzumir_tier().
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 tolength()or toseq_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,
forloop counters, and double vectors made by oney <- numeric(size)at the top of the body, before any loop or branch, changed only byy[i] <- value.sizemay use constants, arguments,length()of arguments and arithmetic. Every local is assigned on every path before it is read.{,<-,=,if/else,while,foroverseq_len(n),seq_along(x)anda:b,break,next,return().+ - * / ^ %% %/%, unary-, comparisons,!,&&,||;exp,log,log1p,expm1,sqrt,abs,floor,ceiling,trunc,sin,cos,tan; two-argumentminandmax;length,is.na,is.nan,is.finite,as.double.The result is a double scalar or a vector local, never an empty block (
{}, which isNULLin 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()