6.3 SEXPs

R RUNTIMESTATUS: STABLELEVEL: INTERMEDIATEREVIEWED: 2026-11-18

6.3.1 Motivation

The R runtime must represent all values in a single, uniform structure. C code inside R and in CRAN packages must read and modify those values at runtime. That looks like a choice between committing to a fixed memory layout and paying for a translation layer at every boundary. R took a third option: one uniform structure internally, and an opaque pointer plus accessor functions on the way out. In R 4.6.1 the representation is private to R, and that is why R can still change it.

6.3.2 The problem

Consider a Python list and a Rust vector. Both hold values. Both need bookkeeping: type information, length, garbage collection metadata. Yet Python and Rust use different memory layouts. Code written for one is fragile or broken on the other. R faced this in the 1990s and defined one C struct for its own use. Extensions get a typedef and a set of functions. For a long time the installed header also offered a way past them: a package that defined USE_RINTERNALS got macros that read the struct directly. Since R 4.2.0 that switch has no effect on package code.

That bought R a great deal of compatibility, and the source of it is easy to misstate. More than five thousand CRAN packages contain compiled code (5,569 of 25,474 had NeedsCompilation set to yes in tools::CRAN_package_db() on 2026-10-21). In R 4.6.1 those packages compile against symbol names and signatures, not against a layout, because the installed header no longer shows one. The SEXP layout is a private implementation detail. What belongs to the ABI is the accessor surface in front of it.

6.3.3 Mental model

A SEXP is a pointer. It points to a SEXPREC, which is a single family of structs unified by a common header. Think of it like an envelope: the front of the envelope (the header) tells you what is inside. The back of the envelope varies. Some SEXPRECs hold a list node. Others hold a vector of numbers. The header must work for all cases. R’s own code reads it directly. Package code never sees it, and asks through a function instead.

Every value in R is a SEXP. Integers, doubles, strings, functions, environments, unevaluated expressions: all are SEXPs. This unity means the evaluator can treat every value the same way, and only the byte-code engine’s stack and binding cells hold unboxed scalars as an optimization. It also means that bookkeeping code (garbage collection, reference counting, attribute storage) can be identical for all values.

6.3.4 Mechanism

The header layout

Every SEXPREC starts with a header. Its first part is sxpinfo, a set of bit fields packed into one 64-bit word since R 3.5.0. Three pointers follow: attrib for the attributes, and two links (gengc_next_node and gengc_prev_node) that thread the object onto the garbage collector’s lists. On a 64-bit build the header is four words.

The first field of sxpinfo is the type tag (SEXPTYPE). It occupies 5 bits, and R 4.6.1 uses 24 type codes between 0 and 25. Common types include:

  • REALSXP: a vector of doubles.
  • INTSXP: a vector of integers.
  • LGLSXP: a vector of logical (boolean) values.
  • CPLXSXP: a vector of complex numbers.
  • RAWSXP: a vector of bytes.
  • STRSXP: a vector of strings (which are themselves SEXPs).
  • VECSXP: a generic vector (list in R parlance).
  • CLOSXP: an R-level function (a closure).
  • BUILTINSXP: a primitive function written in C that receives evaluated arguments. SPECIALSXP is the variant that receives them unevaluated.
  • ENVSXP: an environment (a frame of name-to-value bindings plus a parent).
  • SYMSXP: a symbol (an interned string used as a name).
  • CHARSXP: a single string, immutable and deduplicated.
  • LANGSXP: a language object (a function call not yet evaluated).
  • PROMSXP: a promise (an unevaluated expression paired with an environment).
  • LISTSXP: a pairlist (a cons-cell like structure, older style list).

The garbage collector keeps its own bits in the same word. The mark bit records whether the current garbage collection has reached this object. One gcgen bit, read together with the mark bit, says which of two old generations the object belongs to, and three gccls bits record its size class. An object in an old generation is collected less often.

The named field is 16 bits wide. Despite the name, R 4.x keeps a reference count there: the number of bindings, list slots and other objects that point at the value, raised and lowered as those references come and go. Before R 4.0.0 the same field held NAMED, a counter that almost never went back down. R reads the field to decide whether to copy before modifying. A value with a count of at most one can be changed in place. A value with more must be duplicated first, because another reference would see the change.

The remaining flag bits say whether the object is a numeric vector of length one (scalar), has a class attribute (obj), or is an ALTREP object (alt). There are debug and trace bits, and 16 general-purpose gp bits that each type uses its own way: encodings for a CHARSXP, the PRSEEN flag for a promise, locking bits for bindings and environments.

header: the sxpinfo word, then the attrib pointer type tag SEXPTYPE, 5 bits gc mark generation bits NAMED reference count flags attrib pointer to attributes body body: one of two shapes car cdr tag pairlist node: three pointers length, truelength aligned data payload vector node: two length fields, then the elements

Every R value is a SEXPREC: the sxpinfo word and an attributes pointer (two collector links follow them, not drawn), then one of two body shapes. The type tag says which, except that an ALTREP vector uses the pointer shape. The GC and reference-count fields are the bookkeeping that mutates even when code only reads the object.

The body: two shapes

A SEXPREC is, with two exceptions, either a three-pointer node or a vector. A primitive keeps one integer offset in the node, and an ALTREP vector uses the three-pointer node for its two data slots and its class. This branching determines the rest of the layout.

Pairlist nodes have three pointers: car (the head element), cdr (the tail, pointing to another node), and tag (an optional name for the element). This structure mirrors Lisp cons cells. Argument lists, calls, and attribute lists are pairlists. Closures, environments, promises, and symbols reuse the same three-pointer slot under their own field names: formals, body, and environment for a closure, or frame, enclosure, and hash table for an environment. A list made by list() is not a pairlist. It is a VECSXP, a vector of pointers.

Vector nodes have two size fields, length and truelength, followed by a payload of aligned data. A REALSXP vector holds a C double array. An INTSXP vector holds an int array. A STRSXP vector holds an array of SEXP pointers, each pointing to a CHARSXP string. The layout is uniform: length, then data, then optional padding for alignment.

Attributes do not live in the body. They are a separate pairlist on the heap, one cell per attribute, with the attribute name in the tag and the value in the car. The attrib pointer in the header points to that pairlist. Most vectors have no attributes, so attrib is R_NilValue. Vectors with a class, dim, or dimnames have a non-NULL attrib pointer.

Mapping the C accessors to the header

Inside R’s own sources, TYPEOF, ATTRIB and CAR/CDR are direct reads from the header and body. These are C, not functions you can call from an R prompt.

C’s TYPEOF(x) extracts the type bits and returns the SEXPTYPE code as an int: 14 for a REALSXP, 13 for an INTSXP. R’s typeof(x) is the one that gives you a string, and it is a different function at a different level.

ATTRIB(x) follows the attrib pointer and returns the pairlist of attributes (or NULL).

CAR(x) extracts the car field from a pairlist node. CDR(x) extracts the cdr field. CAAR(x) is a shorthand for CAR(CAR(x)). They do no type check, and inside R each one is little more than a load at a known offset. A package calling TYPEOF gets the function declared in Rinternals.h instead, which is the same answer through one indirection.

SETCAR and SETCDR modify car and cdr in place. They do not allocate, copy, or trigger garbage collection. They do update the reference counts of the old and new values and run the generational collector’s write barrier, so even a pointer store writes GC bookkeeping in more than one header.

6.3.5 Internal mechanics

Concurrency and the header bits

Here lies the core constraint for threading R.

Every SEXPREC header embeds bookkeeping that changes even when R code only reads an object. A collection sets the mark bit and rewrites the list links of every object it reaches. Binding a value to a name, or forcing it as a promise’s value, raises its reference count. Some ALTREP objects materialize their data the first time C code asks for a data pointer. Read-only sharing of SEXPs across threads is therefore not safe as R stands.

This is how R is built, not a bug. If one thread runs a collection while another thread reads the same SEXP, the collector writes the header word the reader is loading. That is a data race in the formal sense, and under the C memory model (or Rust’s) the result is undefined behavior.

Existing single-threaded R code does not see this problem. The garbage collector and evaluator never run concurrently. Adding concurrency means choosing between four strategies: (1) protect every header read-write with a lock. (2) redesign the bookkeeping to use atomic operations. (3) accept that some SEXP state is not thread-safe and document where. Or (4) redesign the value representation to avoid embedded bookkeeping.

threaded-r takes a different route for each kind of object. A small set of builtin constants lives in an immortal arena, where each object keeps its mark bit set for the life of the process and sits on no generation list, so no collector writes to it. For everything else, the apartment model gives each thread a private interpreter, and no SEXP is accessed from more than one interpreter at a time. Interpreters exchange values through channels (R_ChannelCreate and its siblings), which carry byte buffers, not SEXPs.

GNU R and threaded-r both confine garbage collection and reference counting to the one thread that owns an interpreter. threaded-r allocates a fixed set of builtin constants in an immortal arena: R_NilValue, NA_STRING, R_BlankString, marker symbols such as R_UnboundValue and R_MissingArg, and the empty environment. No collector frees them or writes their mark bits and list links, which is what lets interpreters in one process share them. R itself still writes a few fields on some of them (radix sort borrows a CHARSXP’s TRUELENGTH as scratch space), so the arena cannot be sealed read-only.

ALTREP: alternative representations

Not all SEXPs store their data directly in the body. An ALTREP object (alternative representation) defers the layout of its data and computes it on demand.

An ALTREP vector can represent a range of integers (1:1e6) without allocating a million-element array. The alt bit in the header records that it is an ALTREP object, and the node’s tag field points at its ALTREP class, which says which kind it is. When user code reads element 500000, R calls the class’s element method, which computes the value. The vector appears to have a million integers, but only constant memory is used.

Base R uses the same idea for deferred strings: as.character(1:1e6) returns a vector that turns each number into text only when that element is needed. Packages can define their own classes. vroom, for example, uses ALTREP to read the columns of a file lazily. These representations save memory and defer work without copying data.

Materialization is where threads come in. When C code asks a compact sequence for its data pointer (through INTEGER() or DATAPTR()), the class allocates the full array, fills it, and stores it inside the object, so later reads use the expanded copy. That is a write caused by a read. If two threads hold the same ALTREP vector and one of them triggers it, the other sees the object change underneath it. ALTREP pays off in sequential R and causes trouble in concurrent R for that reason.

6.3.6 The hard part

The SEXPREC layout has two sources of fragility, and people usually name only one of them. The first is the accessor surface. Thousands of compiled packages call INTEGER, TYPEOF and VECTOR_ELT, and changing those names, signatures or meanings would break their source code. The layout behind them can change, at a price. R widened sxpinfo to 64 bits in 3.5.0 to make room for ALTREP, and the NEWS for that release told users to reinstall every package that uses compiled code. Reinstalling recompiled them from unchanged source: the accessors kept the source working, and only the old binaries were lost. R 4.0.0 also asked for every package to be reinstalled, though its NEWS gives no layout reason for that and expects the switch to reference counting to have almost no impact on packages that follow supported practice. Since R 4.2.0 USE_RINTERNALS has no effect on package code, so a package can no longer compile the layout in.

Second, the embedded bookkeeping (mark bits, reference counts, ALTREP materialization) changes as R runs. Sharing it between threads requires either locks or atomic operations, and both cost performance. Removing it means redesigning the garbage collector and reference counting, which is a large change to the core of R.

6.3.7 SEXP as de facto ABI

The SEXP is also what R’s published C API hands out.

When you write a CRAN package in C, you include R.h and Rinternals.h. These headers provide a typedef for SEXP and a set of accessor function declarations. Your code compiles to function calls, not direct memory accesses. When the user runs your package, it links against the R runtime. The accessor functions resolve to R’s implementation. If R changes the internal layout of SEXP, the package’s source still compiles and works, because only R’s own accessor code knows the layout. The opacity of the SEXP pointer is the mechanism that lets R evolve.

R’s internal representation has changed. In R 3.5.0 the sxpinfo header widened from 32 bits to 64 bits, adding the ALTREP bit and the 16-bit named field that R 4.0.0 later used for its reference count. Packages written against the accessors needed a reinstall, not a rewrite. Code that defined USE_RINTERNALS and touched struct fields directly was the code a layout change could break at the source level, and since R 4.2.0 package code cannot do that.

This boundary is one reason no alternative R implementation has displaced GNU R. Five earlier projects (Renjin, FastR, Rho, pqR, and Riposte) built R interpreters in other languages or with different internal designs. Renjin runs on the JVM, FastR on GraalVM’s Truffle framework, and Riposte was written from scratch in C++, while Rho and pqR started from GNU R’s own source. FastR shipped for years as an experimental GraalVM component and Renjin has commercial deployments, but neither displaced GNU R for general use. Packages with compiled code are a commonly cited reason: an R implementation that cannot run them loses the users whose work depends on them.

6.3.8 Other systems

Other languages have faced the same problem and made different choices.

CPython publishes its object header. PyObject_HEAD is in the public headers, so extensions compile its layout in. That is the commitment R now avoids. CPython pays for it by breaking binary compatibility between minor versions for extensions that use the full API, and it offers a smaller limited API with a stable ABI (PEP 384) to extensions that want one binary across versions.

Rust does not export a stable C ABI for its standard library. Rust programs link their Rust dependencies statically by default, and Rust code rarely exports data structures for C consumption. When Rust code does expose data to C, the layout is explicit and version-controlled, but there is no ecosystem of compiled Rust libraries like CRAN.

The JVM has the Java Native Interface (JNI), which provides accessor functions instead of a fixed memory layout. Java objects are not directly accessible from C. C code calls JNI functions to read fields. This adds overhead but decouples Java’s internal representation from the C API. JVM implementations can change the layout of Java objects freely. The tradeoff is performance and complexity at the boundary.

R 4.6.1 is closer to the JNI end than to the CPython end. Its accessors are ordinary function calls, which costs a little speed at the boundary and buys the same decoupling: the representation can move because a conforming package never learned where anything sits. R used that freedom in 3.5.0, widening sxpinfo to 64 bits for ALTREP, and packages needed a reinstall, not a rewrite.

Where R does differ from JNI is the payload. REAL(x) returns a real double* into the vector’s own storage, so numeric code runs at full speed. That pointer, not the header, is the hard constraint on changing how vectors are stored.

6.3.9 r-in-rust

The r-in-rust (rrs) project builds an R interpreter from scratch in Rust, with its own value representation and no SEXPREC anywhere in it.

In rrs every R value is an Obj in a heap that belongs to one interpreter, and code refers to it by a handle, a small integer index into that heap, not by a pointer. An Obj holds a kind (a Rust enum with one variant per R type, so a double vector holds its doubles and a list holds handles), a handle to its attribute pairlist, a mark flag for the collector, and a small reference counter for copy-on-modify. An environment frame starts as a short inline array and grows into a hash map. There is no SEXPREC and no C struct layout anywhere in it.

The bookkeeping has not gone away. The interpreter’s mark-sweep collector still writes the mark flag, and the evaluator still updates the counter. What changed is reach. Each heap belongs to one interpreter, so those writes never race with another thread, and because no interpreter data structure is visible to a package, the representation stays free to change.

I used to write that the cost was incompatibility, and that a C FFI mapping onto a fake SEXPREC layout was a future design question. That turned out to be the wrong prediction, and the reason it was wrong is the subject of this page.

rrs now includes an R C API surface in its repository, as a separate set of crates. The headers a package includes present R’s function-accessor flavor, which keeps SEXP fully opaque, as R 4.6.1’s own headers do. A conforming package finds everything it needs, and there is no struct layout to reach into. CRAN mime compiles from its own source tarball, installs into R’s layout, loads through library(), and its routine answers. Rcpp builds against those opaque headers and links. install.packages reaches CRAN, resolves, verifies, compiles and installs. In the census of 2026-08-18, 28 of the 30 most downloaded compiled packages installed and all 28 loaded.

Read that last sentence next to the claim this chapter used to make. If packages really did compile SEXPREC field offsets into their binaries, none of it would be possible: a runtime with no SEXPREC could not satisfy them at any price. They compile calls to an accessor, and a call is a thing another implementation can answer.

The remaining gap is not the C API. Neither failure in that set points at a C routine: the ledger suspects a file-system flake behind the StanHeaders failure, and rstan needs StanHeaders. The larger job left is base R coverage, which is the interpreter’s own work and not a boundary problem.

6.3.10 Relevance to my work

For threaded-r the constraint is the semantics the accessors promise, not the layout. threaded-r already refuses a package compiled for stock R (its ABI tag goes through R’s own R_INTERNALS_UUID check), so every compiled package is rebuilt against the fork, and the layout can change under any package that went through the accessors. Any concurrency strategy has to keep INTEGER(x) meaning what it has always meant, for C code that was written years ago and never revised. This is why threaded-r uses the apartment model. Each interpreter is a container for its SEXPs. No SEXP is accessed from more than one interpreter. It is safer to isolate ownership than to defend every header bit mutation with a lock.

The immortal arena is a direct consequence of SEXP bookkeeping: if the collector and the reference counter wrote to the builtin constants, those constants could not be shared. In the arena each object’s mark bit stays set permanently, which is how the collector knows to skip it, and its reference count is pinned at the maximum, so R never treats it as safe to modify in place.

For r-in-rust the SEXPREC layout is irrelevant, and it turned out the cost was not compatibility. rrs uses its own representation and still answers compiled packages, because it presents the same accessor headers. The open question was never whether to support native packages; it was how much of base R has to exist before they can run.

6.3.11 Mechanics summary: object graph

Here is what the object graph looks like for a simple case: a numeric vector with a name attribute.

flowchart TD
    var["variable x"]
    sexp["SEXPREC: REALSXP<br/>reference count 1"]
    data["data: [1.5, 2.5]"]
    attrs["attribute pairlist cell"]
    tag["TAG: symbol names"]
    val["CAR: STRSXP<br/>holding the names"]
    nil["CDR: NULL<br/>(no more attributes)"]

    var -->|points to| sexp
    sexp -->|attrib| attrs
    sexp -->|payload| data
    attrs --> tag
    attrs --> val
    attrs --> nil

An R object: the SEXPREC header records type and attribute location. The data payload holds numeric values. Attributes form a pairlist of names and values.

The variable x binds to a SEXP of type REALSXP. Its vector fields record length 2, and the reference count in its header is 1, for the one binding. The attrib pointer leads to a one-cell pairlist: the tag holds the symbol names, the car holds the attribute value (a string vector), and the cdr is R_NilValue, which ends the list. The payload holds the numeric data 1.5 and 2.5. In R 4.6.1, x <- c(a = 1.5, b = 2.5) followed by .Internal(inspect(x)) prints this structure, with REF(1) on the vector.

Every REALSXP looks like this inside R. A conforming package never sees it: one that wants the numbers calls REAL(x) and gets a double* to the payload, and one that wants the length calls LENGTH(x). So the picture above describes R’s implementation and promises nothing to packages. The field widths are those of R 4.6.1, and an R release can change them.

Further reading

Where this appears

Where to go next

Back to top