6.8 Promises and Lazy Evaluation

R RUNTIMESTATUS: STABLELEVEL: INTERMEDIATEREVIEWED: 2026-11-15
Before this page Environments, Closures

Start with the canonical example:

f <- function(x) 10
f(stop("boom"))   # 10: the argument is never evaluated

This call returns 10. The stop("boom") never runs. R did not evaluate the argument, because the body of f never reads x. R wraps each argument of a closure call in a promise: a deferred computation that runs at first use, or never. R promises share only a name with JavaScript promises. They have no connection to async programming, callbacks, or futures. An R promise is a small record inside the interpreter, and nothing about it is concurrent.

6.8.1 Motivation

R inherited lazy argument evaluation from S. The design buys three things.

First, unused arguments cost nothing. A function with ten optional arguments does not compute ten values on every call. The example above is the extreme case: an argument that errors is harmless while unread.

Second, default arguments can reference other arguments. The default for y can be written as x * 2, and it resolves against the live bindings of the call. Eager evaluation cannot express this without a sentinel-and-branch idiom.

Third, an argument arrives with its unevaluated expression still attached. Functions can inspect that expression instead of its value. This is the foundation of non-standard evaluation, covered below, and it is why subset() and dplyr verbs can mention column names as bare identifiers. Formulas reach the same effect another way: ~ is a primitive that leaves its operands unevaluated and returns a copy of its call, tagged with a class and an environment.

6.8.2 Mental model

Think of a promise as a sealed envelope. The envelope holds two things: the expression the caller wrote, and a reference to the environment where that expression must be evaluated. The envelope also has an empty result slot. The first time anyone reads the argument, the interpreter opens the envelope, evaluates the expression in the recorded environment, and writes the result into the slot. Every later read returns the stored result. The envelope opens at most once on the success path. That is the whole mechanism: expression, environment, and a write-once value slot.

The analogy ends there. In the runtime a promise is an ordinary heap object, and the “opening” is a mutation of that object. The mutation is what makes promises interesting for concurrency, which I return to below.

6.8.3 Mechanism

When R calls a closure, the evaluation loop does not evaluate the supplied arguments. For each argument it allocates a promise. The promise records the argument expression as written at the call site, plus the caller’s environment. The interpreter then binds each parameter name to its promise in the new execution environment and starts the body.

When the body reads a parameter for the first time, the interpreter sees a promise instead of a plain value. It forces the promise: it evaluates the stored expression in the stored environment, caches the result in the value slot, and returns it. Later reads skip evaluation and return the cache.

stateDiagram-v2
  created: created (expr + env)
  forcing: forcing (expr runs)
  cached: value cached
  interrupted: interrupted (value unbound)
  [*] --> created: closure call
  created --> forcing: first read
  forcing --> cached: success (write once)
  forcing --> interrupted: error
  interrupted --> forcing: next read, with a warning
  cached --> cached: later reads return cache

The promise lifecycle: creation at call time, one forced evaluation, a cached value, and an error edge that marks the promise interrupted, so the next read runs the expression again.

The observable surface: force(), missing(), substitute()

Three base functions expose promise behavior to R code.

force(x) evaluates to x and nothing more. Its only effect is to force the promise now instead of later. Function factories use it to pin an argument value before they return a closure:

adder <- function(n) {
  force(n)              # force now, while n still means what the caller meant
  function(x) x + n
}

Without the force, the inner function captures an unforced promise. If the binding behind that promise changes before the first call, the closure sees the changed value. force removes the hazard. It converts “whatever n evaluates to later” into “what n is now”.

missing(x) reports whether the caller supplied x at all. It inspects the promise machinery without a force. A function can branch on missing(x) and never pay for the argument it did not need.

substitute(x) returns the expression stored in the promise, unevaluated. Applied to a parameter, it retrieves what the caller literally wrote:

show_expr <- function(x) substitute(x)
show_expr(a + b)   # the language object a + b, not a value

substitute does not force the promise. Expression and value are independent readouts of the same record.

Default arguments that reference other arguments

Supplied arguments and default arguments get different environments. A supplied argument’s promise points at the caller’s environment, because the caller wrote the expression. A default argument’s promise points at the function’s own execution environment, because the author wrote the expression in terms of the other parameters:

g <- function(x, y = x * 2) x + y
g(5)   # 15: the default y forces x, then multiplies

When the body reads y, the promise for y evaluates x * 2 inside g’s frame. That evaluation reads x, which forces the promise for x first. Forces chain naturally. The chain can also form a cycle:

h <- function(x = y, y = x) x + y
h()
# Error in h() :
#   promise already under evaluation: recursive default argument reference or earlier problems?

The interpreter detects the cycle with a flag on the promise, described under internal mechanics.

6.8.4 A simple example

Return to the opening call and follow it through the machinery:

sequenceDiagram
  participant c as caller
  participant e as eval loop
  participant p as promise for x
  c->>e: f(stop("boom"))
  e->>p: create: expr = stop("boom"), env = caller
  e->>e: evaluate body of f, which is 10
  Note over p: never read, never forced
  e-->>c: 10

The call f(stop("boom")) builds a promise but the body never reads x, so stop("boom") never runs.

The promise for x is created, bound, and then ignored. When f returns, the promise becomes garbage, and the garbage collector reclaims it. The stop("boom") call it held was never evaluated, so no error ever happened.

6.8.5 Internal mechanics

A promise is a SEXP with type PROMSXP. Beyond the standard header it holds three pointers, with accessor macros in the R sources:

  • PRCODE: the code to run. Usually the unevaluated expression, a language object; byte code when the caller is compiled; the constant itself for a constant argument in interpreted code.
  • PRENV: the environment for evaluation.
  • PRVALUE: the cached value, initially the sentinel R_UnboundValue.

In the AST evaluator the force operation is forcePromise in src/main/eval.c; byte-compiled code forces a promise whose code is byte code with the same steps, inline in its bytecode loop. The force checks PRVALUE. If the slot holds the sentinel, it evaluates PRCODE in PRENV, writes the result into PRVALUE, and then sets PRENV to R_NilValue. The last step matters for memory: once the value exists, the promise no longer needs the environment. The cleared pointer lets the collector reclaim the caller’s frame.

A small flag, PRSEEN, guards against reentry. forcePromise sets it on entry. If a force finds the flag already set, the promise is under evaluation further up the stack, and R raises the recursive-reference error shown above. If a force is interrupted by an error or a user interrupt, the error unwind walks the pending promises and marks each one as interrupted. A later read of such a promise forces it again, with a warning about a restarted evaluation. The value slot is still unbound, so the retry is a plain re-run of the expression. R treats the retry as abnormal and warns about it, but code that catches an error can rely on it: code inside tryCatch can fail on one force and succeed on the next. In R 4.6.1 a function that catches the error from its first read of x and then reads x again gets the second evaluation’s value, along with the warning “restarting interrupted promise evaluation”.

Promises are not limited to arguments. delayedAssign() creates one directly and binds it to a name. Lazy loading of package code and data uses the same mechanism: a package binding starts as a promise whose expression fetches the object from the package database on first use.

6.8.6 Non-standard evaluation

Non-standard evaluation (NSE) is the practice of computing on the expression an argument carries instead of, or in addition to, its value. The two primitives are substitute, which extracts the expression from the promise, and eval, which evaluates an expression in a chosen environment. A minimal subset clone shows the pattern:

subset2 <- function(df, cond) {
  expr <- substitute(cond)                 # the expression, e.g. mpg > 30
  keep <- eval(expr, df, parent.frame())   # data frame first, caller after
  df[keep, , drop = FALSE]
}
subset2(mtcars, mpg > 30)

The caller writes mpg > 30 with mpg as a bare name. substitute recovers that expression from the promise before any force. eval then evaluates it with the data frame as the primary scope and the caller’s environment behind it. Column names resolve against the data. Everything else, like a threshold variable the caller defined, resolves in the caller’s frame.

Both halves of the promise record are essential here. The expression half gives the interface its syntax: bare column names and quoted verbs. The environment half gives it correct scoping for the names that are not columns. dplyr, ggplot2, and data.table all stand on this mechanism. rlang’s quosures and base helpers such as bquote are refinements of the same promise readout. An eager language with no expression capture cannot offer these interfaces without macros or string parsing.

NSE also explains a common surprise: a function that uses substitute on its argument behaves differently when the argument arrives through a wrapper. The wrapper’s promise carries the wrapper’s expression, not the original one. The expression readout is one level deep, by design.

6.8.7 Tradeoffs

Laziness has two recurring costs, one in space and time, one in debuggability.

The first cost is allocation. Every closure call allocates one PROMSXP per supplied argument, and one more for each default argument the caller left out, whether the body reads it or not. These are heap objects with headers, traced by the garbage collector like any other SEXP. Code that makes millions of small calls pays for millions of short-lived promises. Compiled code skips the promise for a constant argument such as 2 or TRUE, but an argument that is a symbol or a call still gets one.

The second cost is distance between cause and effect. A promise separates the site that constructs an expression from the site that evaluates it. When the expression errors, the error surfaces at the force, which can sit several frames away from the call that supplied the bad argument:

inner <- function(x) x + 1
outer <- function(y) inner(y)
outer(log("text"))
# Error in log("text") : non-numeric argument to mathematical function
# traceback() shows 2: inner(y) above 1: outer(log("text")):
# the error surfaced inside inner(), where the promise was forced

The traceback points into inner, where the force happened, and the reader must walk back to outer’s caller to find the origin. The same separation means a promise can observe state changes that happened between call and force. If a binding the expression references mutates in the gap, the forced value reflects the mutation. The force() idiom in function factories exists to close exactly that gap.

6.8.8 The hard part

Everything above assumed one thread of execution, which is the world GNU R was built for. The promise design leans on that assumption harder than most parts of the runtime.

A force is a mutation of shared state. It writes PRVALUE, clears PRENV, and updates flags in place. Two threads that force the same promise concurrently can both find the value slot unbound, both evaluate the expression, and both write results. The expression’s side effects run twice, and the racing writes are a data race on the promise fields.

R expressions perform arbitrary side effects: they write files, mutate environments, advance the random number generator. A promise that runs twice is observably wrong, not merely slow.

The textbook remedy is a once-only latch: an atomic state field where one thread wins the transition to “evaluated” and all others wait. Rust’s std::sync::Once and Java’s class initialization follow this shape: a panic inside call_once poisons the Once, so every later call_once on it panics, and a class whose static initializer throws stays unusable. For R promises that shape does not fit, because of the retry edge established above. Rust’s OnceLock comes closer, since a panicking initializer leaves the cell empty and a later caller may try again.

In GNU R, an errored force leaves PRVALUE unbound, and a later read forces the promise again, with a warning. Code that catches the error from one force and then reads the argument again relies on this. A concurrent promise that keeps this behavior must let a failed force run again, so a simple once-only latch, which permits exactly one transition ever, cannot represent “errored, retry allowed” and is ruled out.

A correct concurrent promise needs at least three states (unforced, in flight, cached) plus a rule for what other threads do while a force is in flight, plus a path back to unforced on error. That is a small state machine guarded by an atomic or a mutex, with policy questions attached: does a second thread block, steal the evaluation, or fail? Every answer changes observable semantics for side effects and errors.

6.8.9 Relevance to my work

threaded-r sidesteps the concurrent force by construction. Its apartment model runs multiple isolated interpreters in one process, and each interpreter has one owner thread. Promises are created, forced, and cached by that owner. No second thread can reach the promise, so the single-thread assumptions above continue to hold inside each apartment. The cost is a rule, not a lock: the design must keep promises from leaking across interpreters, which is one of the reasons R values do not cross apartment boundaries by reference.

r-in-rust faces the same semantics from the other side. Its interpreter is differential-tested against pinned GNU R 4.6.1, so its promises must match GNU R behavior exactly: write-once caching on success, expression and environment readable before the force, and retry after an errored force. Each rrs interpreter owns its heap outright, so the concurrency question does not arise inside one interpreter there either.

6.8.10 Open questions

Must promises ever be evaluated concurrently, or can the runtime pin every promise to its owner interpreter for its whole lifetime? Pinning keeps the current single-thread force semantics and needs no synchronization. But any future feature that ships an unforced promise to another interpreter, for example a lazy argument to a parallel map, forces the question of who evaluates, in which environment, and what a retry means across threads.

Further reading

Where this appears

  • threaded-r A promise force is a write to shared interpreter state, so it must stay on one owner thread.
  • r-in-rust (rrs) The Rust evaluator must reproduce write-once caching and retry-after-error semantics exactly.

Where to go next

Back to top