flowchart TD
src(["source text"]) -->|parser| ast(["AST"])
ast --> eval["AST walker"]
ast --> comp["bytecode compiler"] --> code(["bytecode"]) --> vm["bytecode VM"]
eval --> result(["same result"])
vm --> result
subgraph rt["shared runtime"]
envs["environments"]
heap[("heap")]
end
eval --- rt
vm --- rt
6.1 How R Executes Code
R does not compile your script to machine code. The session reads source text, converts it to a tree of ordinary R objects, and walks that tree to compute values. Since R 3.4.0 a compiler also translates most functions into bytecode for a small virtual machine. GNU R is therefore a hybrid: a tree-walking interpreter with a bytecode VM at its side. This page follows one line of code through the full path.
6.1.1 Motivation
Every project in this corpus modifies, replaces, or schedules around the machinery on this page, and each of them starts from a description of the eval loop. The map here covers the parser, the AST, the evaluator, function calls, and the bytecode compiler. Later pages each take one station of it. For the difference between an interpreter, a runtime, and a compiler as terms, see interpreter vs runtime vs compiler.
6.1.2 Mental model
Hold three stages in your head:
- The parser turns text into a tree. The tree is built from normal R objects that you can inspect from R itself.
evalwalks that tree with three rules. Constants evaluate to themselves. Symbols become lookups in an environment. Calls apply a function to arguments.- A compiler turns functions into bytecode. A second engine, the bytecode VM, runs those flat instructions faster than a tree walk.
The unusual part is stage 1. In most languages the parse tree is a private compiler structure. In R the tree is a first-class value. You can store it, subset it, rewrite it, and evaluate it later. This one design choice powers substitute(), formulas, and every non-standard evaluation idiom in the language. It also means the evaluator is a plain recursive function over data you can print.
6.1.3 Mechanism
The parser produces language objects
When you type y <- 1 + 2 * x, the parser runs nothing. It builds a tree called the abstract syntax tree (AST). quote() hands you that tree without evaluation:
e <- quote(1 + 2 * x)
typeof(e) # "language"
class(e) # "call"The object e is data. You can index it like a list:
e[[1]] # `+` the function position
e[[2]] # 1 the first argument
e[[3]] # 2 * x the second argument, itself a callLook at where 2 * x sits. The parser applied operator precedence. The * operator binds tighter than +, so the * call nests inside the + call. Precedence exists only at parse time. After the tree exists, evaluation order comes from tree shape alone.
The trip is reversible. deparse(e) reconstructs the text "1 + 2 * x" from the tree. parse(text = ...) goes the other way and returns a vector of such trees, one per top-level expression. Function bodies are stored the same way:
f <- function(x) x^2 + 1
body(f) # x^2 + 1
class(body(f)) # "call"A function does not remember your source text as text. It carries the tree. A source reference attribute can keep the original text for display. The evaluator reads it only to track where in the source it is, for error messages and the debugger, and it never changes what the code computes.
Three node kinds
The whole AST is built from three kinds of node:
- Calls. A call is a pairlist of type
LANGSXP. The first element is the function, or a symbol that names it. The rest are arguments. Every node is a SEXP, a pointer to the one C structure behind all R objects. - Symbols. A symbol (
SYMSXP) is an interned name such asxor+. Two mentions ofxanywhere in the session point at the same symbol object. - Constants. Literals such as
1,"a", andTRUEsit in the tree as themselves.
There are no special statement nodes. Assignment, if, for, braces, and parentheses are all calls:
as.list(quote(y <- 1)) # `<-`, y, 1
quote(if (a > 1) b else c)[[1]] # `if`Operators are functions with unusual names. The backtick form makes this visible:
`+`(1, 2) # 3
sapply(1:3, `+`, 10) # 11 12 131 + 2 and `+`(1, 2) parse to the same tree.
eval walks the tree
eval lives in src/main/eval.c as one recursive C function. Its core is three rules that mirror the three node kinds:
- A constant evaluates to itself. No work happens.
- A symbol triggers a lookup. The interpreter searches the current environment, then its enclosure, then up the chain through the global environment and attached packages to base. If nothing matches, R raises
object 'x' not found. - A call first resolves its function position, then applies that function to the arguments. The apply step recurses back into
evalfor each argument that needs a value.
Environments do double duty. They store variables and they define scope. The same structure answers “what is x” and “where do I look next”.
You can drive the walker by hand, because both of its inputs are ordinary values. eval() takes a tree and an environment:
e <- quote(x * 10)
env <- new.env()
assign("x", 4, envir = env)
eval(e, env) # 40The same tree against a different environment gives a different answer. That pair, expression plus environment, is the whole unit of execution in R. The promise is exactly this pair, frozen for later.
The compiled path shares everything except the walk. Both engines allocate results on the same heap and read the same environment chain:
Two engines, one runtime: the AST walker and the bytecode VM read the same environments, allocate on the same heap, and must agree on every result.
6.1.4 A simple example
Here is the full tree for y <- 1 + 2 * x:
flowchart TD assign(["call: <-"]) --> y(["symbol: y"]) assign --> plus(["call: +"]) plus --> one(["constant: 1"]) plus --> times(["call: *"]) times --> two(["constant: 2"]) times --> x(["symbol: x"])
The AST for y <- 1 + 2 * x. Precedence lives in the shape: the * call nests below the + call, so it evaluates first.
Assume x is bound to 10 in the current environment. Evaluation proceeds depth-first, left to right:
evalreceives the<-call. Assignment is a special function (see below). It does not evaluateyas a value. It keepsyas the name to bind.evalrecurses into the right side, the+call.+is a builtin, so both arguments must become values first, left to right.1is a constant. It evaluates to itself.2 * xis a call.2evaluates to itself.xis a symbol, and lookup in the current environment finds10. The*builtin returns20.+receives1and20and returns21.<-binds the symbolyto21in the current environment. It returns21invisibly.
In this expression the interpreter never looks ahead and never reorders. Every value appears exactly when the walk reaches its node, because + and * are builtins and take evaluated arguments.
6.1.5 Internal mechanics
Three kinds of functions
typeof() reveals that R has three function representations:
typeof(function(x) x) # "closure"
typeof(sum) # "builtin"
typeof(quote) # "special"A closure is an R-level function. It holds a formal argument list, a body (an AST), and a captured environment. When eval applies a closure, it creates a fresh environment whose enclosure is that captured environment. It binds the arguments there and evaluates the body inside it. Lexical scope follows from that: a free name in the body resolves in the environment where the closure was created.
Builtins and specials are primitives written in C. They differ in argument handling. A builtin such as sum or * receives arguments that are already evaluated. A special such as quote, if, for, or <- receives the raw ASTs and decides itself what to evaluate. quote must see the unevaluated tree, so it cannot be an ordinary closure that evaluates its argument, and R implements it as a special.
Each closure call pushes a context, an RCNTXT struct on the C side. Contexts power sys.call(), traceback(), on.exit(), and non-local returns:
f <- function(x) sys.call()
f(1 + 2) # f(1 + 2): the unevaluated call that invoked fThe context keeps the call object for as long as the function runs, so the code stays available as data during execution.
Specials also carry the strangest mechanic in the evaluator: complex assignment. x[1] <- 2 cannot be a plain call, because x[1] is not a name. The evaluator rewrites it into a chain of real calls on a hidden variable named *tmp*:
x <- c(1, 2, 3)
# what x[1] <- 2 expands into
`*tmp*` <- x
x <- `[<-`(`*tmp*`, 1, value = 2)
rm(`*tmp*`)The R Language Definition documents this expansion in its section on subset assignment. The copy-on-modify page covers when such an assignment copies the vector and when it writes in place.
Argument matching
Before a closure body runs, R matches supplied arguments to formal parameters in three passes. It tries exact name first, then unambiguous partial name, then position.
f <- function(alpha, beta) alpha - beta
f(beta = 1, 10) # 9: exact name first, then position
f(b = 1, 10) # 9: partial matching on the prefix "b"This matching runs on every call. It is convenient at the prompt and a real cost in hot loops.
Arguments become promises
Matched closure arguments do not evaluate at the call site. Each one wraps into a promise (the byte-code compiler skips the promise for a constant argument). The promise holds the argument expression plus the environment where it must later evaluate. The promise forces on first use inside the body and caches its value.
f <- function(x) 10
f(stop("boom")) # 10: the argument never evaluatesBuiltins skip promises entirely and evaluate their arguments immediately at the call site. The promises page covers forcing order, substitute(), and the traps that lazy evaluation sets for parallel code.
The bytecode compiler
A tree walk pays a tax at every node. The evaluator must re-inspect each node type, re-dispatch on it, and recurse on every execution of the same code. The compiler package, written by Luke Tierney and shipped since R 2.13.0, removes that tax. It translates a closure body into bytecode: a flat instruction sequence for a stack-based virtual machine.
R 3.4.0 turned on just-in-time (JIT) compilation by default, at level 3: larger closures compile before their first use, some small ones before their second, and top-level loops compile before they run. R 3.5.0 made byte-compilation the default for all packages at install time.
You can look at the output:
f <- function(x) x + 1
cf <- compiler::cmpfun(f)
compiler::disassemble(cf)
# list(.Code, list(GETVAR.OP, 1L, LDCONST.OP, 2L, ADD.OP, 0L, RETURN.OP), ...)
# output abbreviated: version header and constant pool removedRead it as a recipe for an operand stack. GETVAR.OP pushes the value of x. LDCONST.OP pushes 1. ADD.OP pops both, adds, and pushes the sum. RETURN.OP hands the top of the stack back to the caller. The VM that runs this, bcEval in src/main/eval.c, is a large loop over instructions instead of a recursion over tree nodes.
The compiler also optimizes. It constant-folds and inlines arithmetic and comparison operators. It compiles control flow such as if and for into jumps. Scalar loop-heavy code gains the most. Vectorized code gains little, because its time was already inside C.
Not everything goes through the VM. Most top-level expressions run through the AST walker (top-level loops are the exception at JIT level 3), and so does any closure that the compiler declined or has not reached yet. R is therefore a permanent hybrid, and the two engines must agree exactly on semantics: promises, dispatch, and error behavior. compiler::enableJIT(0) turns the JIT off for the session, and results must not change.
GNU R 4.x runs both engines in one thread of one process. The AST walker handles most top-level code and uncompiled closures. The bytecode VM handles compiled closures. Both mutate the same interpreter-global state.
Where the time goes
Three costs keep showing up in profiles of interpreted R, and the bytecode VM removes only part of them. The stock tools show them. Rprof() samples the call stack and shows where CPU time went (elapsed time on Windows). tracemem() reports when a vector was copied. Rprofmem() logs large allocations, and bench::mark() from the bench package reports the memory each run allocated. Point these at a hot loop before you blame the loop body. The expensive part is often the machinery around it.
Environment lookup. Every symbol resolution walks a chain of environment frames. Local frames are small, but a miss escalates to the global environment and the attached package path. The runtime keeps fast paths. Base package bindings sit in a slot on the symbol object itself (SYMVALUE). A base lookup is then one pointer read. The bytecode VM adds a cache of binding cells for variables in the current frame, and for a base builtin it inlines, the compiler emits an instruction (GETBUILTIN.OP) that fetches the primitive straight from the symbol and skips the environment walk.
Dispatch. S3 dispatch constructs generic.class method names from the class attribute and searches for them through environments. This happens on every call to a generic. Arithmetic builtins must first check both operands for classes and attributes before they touch the numbers. Objects pay this tax even when no method exists.
Allocation. R values are immutable in the common case, so x + 1 must allocate a fresh vector for its result. R does reuse a temporary that nothing else refers to: in (x + 1) * 2 the product overwrites the vector that x + 1 just made, and Rprofmem() on a million-element x records one result-sized allocation for the whole expression, not two. Every closure call still allocates an environment, and every closure argument allocates a promise, except a constant argument in compiled code. All of it becomes work for the garbage collector, so GC pauses show up in code that never mentioned memory.
The bytecode VM removes tree-walk overhead. It does not remove environment lookup, dispatch, or allocation. Those costs live in the runtime itself, not in the encoding of the code.
6.1.6 Relevance to my work
Everything on this page fits in a short chain: parse, walk, look up, apply, or run bytecode. Each project in this corpus takes hold of that chain at a different link. The reasons R resists parallel execution start here too, in the shared state both engines mutate. See why R is difficult to parallelize.
threaded-r patches this machinery in place. eval, bcEval, the context stack, and the symbol table all touch process-global C state. Every fast path above is also a sharing hazard. SYMVALUE is a single global slot per symbol. The JIT keeps global counters and caches.
The threaded-r census found 1,574 mutable globals in upstream GNU R. All 35 per-thread globals now live in R_ThreadState, and R_InterpreterState had 556 members after patch 0127 (2026-08-22). A hashed base environment per interpreter, measured as one option, cost 1.3 to 1.9 percent on a single-threaded microbenchmark built as the worst case (the measurement). threaded-r then chose a smaller change: each interpreter has its own symbol table, and only 38 symbols that packages reach through exported globals keep their bindings in a per-interpreter record.
rrs reimplements the pipeline instead of patching it: its own parser, its own AST, and an evaluator that had about 185 builtins at its P19 phase and has grown well past that since. Differential tests check it against pinned GNU R 4.6.1, so GNU R’s behavior, the three eval rules above included, is its specification. Each rrs interpreter owns its heap, GC, symbol table, and string cache. The sharing hazards above do not exist there by construction.
sunlight changes nothing on this page. It accepts one eval loop per process as a fact and schedules whole processes. A template R process preloads packages and forks the workers. The loop still matters there, because fork interacts with the heap that both engines share. The project measured this: the first collection in a forked child writes to the header of every reachable object, which privatizes most of the pages the child shared with the template.
Further reading
- R Core Team. R Language Definition, chapters “Evaluation of expressions” and “Computing on the language”. https://cran.r-project.org/doc/manuals/r-release/R-lang.html
- R Core Team. R Internals, section 1 on R internal structures. https://cran.r-project.org/doc/manuals/r-release/R-ints.html
- Luke Tierney. A Byte Code Compiler for R. https://homepage.divms.uiowa.edu/~luke/R/compiler/compiler.pdf
- GNU R source,
src/main/eval.c. BothevalandbcEvallive here. https://github.com/r-devel/r-svn/blob/master/src/main/eval.c
Where this appears
- threaded-r Patches this exact machinery so multiple interpreters can live in one process.
- r-in-rust (rrs) Reimplements the parser, the AST, and the evaluator described here from scratch.
- sunlight Treats this single-threaded eval loop as opaque and schedules whole processes around it.