16 Expressions

16.1 Introduction

To compute on the language, we first need to understand its structure. That requires some new vocabulary, some new tools, and some new ways of thinking about R code. The first thing you’ll need to understand is the distinction between an operation and its result. Take the following code, which takes a variable x, multiplies it by 10, and saves the result to a new variable called y. It doesn’t work because we haven’t defined a variable called x:

It would be nice if we could capture the intent of the code, without executing it. In other words, how can we separate our description of the action from the action itself? One way is to use rlang::expr():

expr() returns an expression, an object that captures the structure of the code without evaluating it (i.e. running it). If you have an expression, you can evaluate it with base::eval():

The focus of this chapter is the data structures that underlie expresssions. Mastering this knowledge will allow you to inspect and modify captured code. We’ll come back to expr() in Section ??, and to eval() in Section 18.2.



Make sure you’ve read the metaprogramming overview in Chapter ?? to get a broad overview of the motivation and the basic vocabulary. You’ll also need the rlang package to capture and compute on expressions, and the lobstr package to visualise them.

16.2 Abstract syntax trees

Expressions are also called abstract syntax trees (ASTs) because the structure of code is hierarchical and can be naturally represented as a tree. Understanding this tree structure is crucial for inspecting and modifying expressions (i.e. metaprogramming).

16.2.1 Drawing

So we’ll start by introducing some conventions for drawing ASTs, starting with a simple call that shows the main components: f(x, "y", 1). I’ll draw trees in two ways:

Both approaches share conventions as much as possible:

  • The leaves of the tree are either symbols, like f and x, or constants, like 1 or "y". Symbols are drawn in purple and have rounded corners. Constants have black borders and square corners. Strings and symbols are easily confused, so strings are always surrounded in quotes.

  • The branches of the tree are function calls, represended by call objects and drawn as orange squares. The first child (f) is the function that gets called; the second and subsequent children (x, "y", and 1) are the arguments to that function.

The above example only contained one function call, making for a very shallow tree. Most expressions will contain considerably more calls, creating trees with multiple levels of hierarchy. For example, consider f(g(1, 2), h(3, 4, i())):

You can read the hand-drawn diagrams from left-to-right (ignoring vertical position), and the lobstr-drawn diagrams from top-to-bottom (ignoring horizontal position). The depth within the tree is determined by the nesting of function calls. This also determines evaluation order, as evaluation generally proceeds from deepest-to-shallowest (but this is not guaranteed because of lazy evaluation, Section 5.5). Also note the appearance of i(), a function call with no arguments; it’s a branch with a single (symbol) leaf.

16.2.2 Non-code components

You might have wondered why these are abstract syntax trees. They are abstract because they only capture important structural details of the code, not whitespace or comments:

There’s one important situtation where whitespace does affect the AST:

16.2.3 Infix calls

Every call in R can be written in tree form, even if it doesn’t look like it at first glance. Take y <- x * 10 again: what are the functions that are being called? It is not as easy to spot as f(x, 1) because this expression contains two infix calls: <- and *.

However, as discussed in Section 5.8.1, any call can be rewritten in prefix form. That means that these two lines of code are equivalent:

And they both have this AST54:

There really is no difference between the ASTs, and if you generate an expression with prefix calls, R will still print them in infix form:

The order in which infix operators are applied is governed by a set of rules called operator precedence. In Section 16.4.1 we’ll use lobstr::ast() to explore R’s rules.

16.2.4 Exercises

  1. Reconstruct the code represented by the trees below:

    #> █─f 
    #> └─█─g 
    #>   └─█─h
    #> █─`+` 
    #> ├─█─`+` 
    #> │ ├─1 
    #> │ └─2 
    #> └─3
    #> █─`*` 
    #> ├─█─`(` 
    #> │ └─█─`+` 
    #> │   ├─x 
    #> │   └─y 
    #> └─z
  2. Draw the following trees by hand then check your answers with lobstr::ast().

  3. How are function factories (Chapter 9) show in the AST? What makes the ASTs of the expressions below special?

  4. What’s happening with the ASTs below? (Hint: carefully read ?"^")

  5. What is special about the AST below? (Hint: re-read Section 5.2.2)

  6. What does the call tree of an if statement with multiple else if conditions look like? Why?

16.3 Expressions

Collectively, the data structures present in the AST are called expressions. More precisely, an expression is any member of the set of base types created by parsing code: constant scalars, symbols, call objects. These are the data structures used to represented captured code form expr(), and so is_expression(expr(...)) is always true55. In the subsequent sections, we’ll come back to define each of these types precisely, and show you how to create, inspect, and modify them.

There are couple of data structures that we’ll come back to later. Pairlists are used in one place, but behave identially to lists; we’ll discuss them in Section 16.6.1. There also a special symbol used to represent missing arguments, we’ll come back to that in Section 16.6.2.

NB: In base R documentation “expression” is used to mean two things. As well as the definition above, expression is also used to refer to the type of object returned by expression() and parse(), which are basically lists of expressions as defined above. In this book I’ll call these expression vectors, and I’ll come back to them in Section 16.6.3.

16.3.1 Constants

Constants are the simplest component of the AST, and use data structures that you learned about in Chapter ??. More precisely, a constant is either NULL or a length-1 atomic vector56 like TRUE, 1L, 2.5 or "x". You can test for a constant with rlang::is_syntactic_literal().

57 See Section (scalars) for the conventions for creating these scalars.

Constants are “self-quoting” in the sense that the expression used to represent a constant is the constant itself:

16.3.2 Symbols

A symbol represents the name of an object like x, mtcars, or mean. In base R, symbol and name are used interchangeably (i.e. is.name() is identical to is.symbol()), but in this book I used symbol consistently because “name” has many other non-technical meanings. You can test for a symbol with is.symbol().

You can create a symbol in two ways: by capturing code that references an object with expr(), or turning a string into a symbol with sym():

You can turn a symbol back into a string with as.character() or as_string(). as_string() has the advantage of clearly signalling that you’ll get a character vector of length 1.

You can recognise a symbol because it’s printed without quotes, and str() tells you that it’s a symbol:

The symbol type is not vectorised, i.e. a symbol is always length 1. If you want multiple symbols, you’ll need to put them in a list, using (e.g.) rlang::syms().

16.3.3 Calls

A call object represents a captured function call. Call objects are vectors: the first component is name of the function to call (usually repesented as a symbol), and the remaining elements are the arguments for that call. Call objects create branches in the AST, because calls can be nested inside other calls.

You can identify a call object when printed because it looks just like a function call. Unfortunately typeof() and str() print “language”58 for call objects, but is_call() returns TRUE: Subsetting

Calls generally behave like lists, i.e. you can use standard subsetting tools. The first element of the call object the function to call, which is a usually a symbol[^symbol-exception]:

The primary exception[^function-factories] to this rule occurs when you use :: to call a function in a specific package. In that case the first element will be another call:

[^function-factories] This is a general example of calls to a function factory, a function that returns a function, the topic of Chapter 9.

The remainder of the elements are the arguments:

You can extract individual arguments with [[ or $ (if named):

You can determine the number of arguments in call object by subtracting 1 from the length:

Extracting specific arguments from calls is challenging because of R’s flexible rules for argument matching: it could potentially be in any location, with the full name, with an abbreviated name, or with no name. To work around this problem, you can use rlang::call_standardise() which standardises all arguments to use the full name:

(Note that if the function uses ... it’s not possible to standardise all arguments.)

Calls can be modified in the same way as lists: Function position

The first element of the call object is the function position. This contains the function that will be called when the object is evaluated, and is usually a symbol59:

Note that while R allows you to surround the name of the function with quotes, the parser still converts this to a symbol:

However, sometimes the function doesn’t exist in the current environment and you need to do some computation to retrieve it. For example, the function is in another package, is a method of an R6 object, or it’s created by a function factory. In this case, the function position will be occupied by another call: Constructing

You can construct a call object from its components by using rlang::call2(). The first argument is the name of function to call (either as a string, a symbol, or another call). The remaining arguments will be passed along to the call:

Note that infix calls created in this way still print as usual.

Using call2() to create complex expressions is a bit clunky. You’ll learn another technique in Chapter 17.

16.3.4 Vocabulary

str typeof
Scalar constant logi/int/num/chr logical/integer/double/character
Symbol symbol symbol
Call object language language
Pairlist Dotted pair list pairlist
Expression vector expression() expression
base rlang
Scalar constant is_syntactic_literal()
Symbol is.symbol() is_symbol()
Call object is.call() is_call()
Pairlist is.pairlist() is_pairlist()
Expression vector is.expression()

16.3.5 Exercises

  1. Which two of the six types of atomic vector can’t appear in an expression? Why? Why can’t you create an expression that contains an atomic vector of length greater than one?

  2. What happens when you subset a call object to remove the first element? e.g. expr(read.csv("foo.csv", header = TRUE))[-1]. Why?

  3. Describe the differences between the following call objects.

  4. rlang::call_standardise() doesn’t work so well for the following calls. Why? What makes mean() special?

  5. Why does this code not make sense?

  6. Construct the expression if(x > 1) "a" else "b" using multiple calls to call2(). How does the code structure reflect the structure of the AST?

16.4 Parsing and grammar

We’ve talked a lot about expressions and the AST, but not how expressions are created from code that you type. The process by which a computer language takes a string like (like "x + y") and constructs an expression is called parsing, and it is governed by a set of rules known as a grammar. In this section, we’ll use lobstr::ast() to explore some of the details of R’s grammar, and then see how you can transform back and forth between expressions and strings.

16.4.1 Operator precedence

Infix functions introduce ambiguity in a way that prefix functions do not60. The parser has to resolve two sources of ambiguity when parsing infix operators. First, what does 1 + 2 * 3 yield? Do you get 9 (i.e. (1 + 2) * 3), or 7 (i.e. 1 + (2 * 3))? In other words, which of the two possible parse trees below does R use?

Programming languages use conventions called operator precedence to resolve this ambiguity. We can use ast() to see what R does:

Predicting the precedence of arithmetic operations is usually easy because it’s drilled into you in school and is consistent across the vast majority of programming languages. Predicting the precedence of other operators is harder. There’s one particularly surprising case in R: ! has a much lower precedence (i.e. it binds less tightly) than you might expect. This allows you to write useful operations like:

R has over 30 infix operators divided into 18 precedence groups. While the details are described in ?Syntax, very few people have memorised the complete ordering. Indeed, if there’s any confusion, use parentheses!

Note the appearance of the parentheses in the AST as a call to the ( function.

16.4.2 Associativity

Another source of ambiguity is introduced by repeated usage of the same infix function. For example, is 1 + 2 + 3 equivalent to (1 + 2) + 3 or to 1 + (2 + 3)? This normally doesn’t matter because x + (y + z) == (x + y) + z, i.e. addition is associative, but is needed because some S3 classes define + in a non-associative way. For example, ggplot2 overloads + to build up a complex plot from simple pieces; this is non-associative because earlier layers are drawn underneath later layers (i.e. geom_point() + geom_smooth() does not yield the same plot as geom_smooth() + geom_point()).

In R, most operators are left-associative, i.e. the operations on the left are evaluated first:

There are two exceptions: exponentiation and assignment.

16.4.3 Parsing and deparsing

Most of the time you type code into the console, and R takes care of turning the characters you’ve typed into an AST. But occasionally you have code stored in a string, and you want to parse it yourself. You can do so using rlang::parse_expr():

parse_expr() always returns a single expression. If you have multiple expression separated by ; or \n, you’ll need to use rlang::parse_exprs(). It returns a list of expressions:

If you find yourself working with strings containing code very frequently, you should reconsider your process. Read the Chapter 17 and consider if you can instead more safely generate expressions using quasiquotation.

The base equivalent to parse_exprs() is parse(). It is a little harder to use because it’s specialised for parsing R code stored in files. You need supply your string to the text argument. It returns an expression vector, discussed in Section ??, which I recommend turning into a list:

The inverse of parsing is deparsing: given an expression, you want the string that would generate it. This happens automatically when you print an expression, and you can get the string yourself with rlang::expr_text():

Parsing and deparsing are not perfectly symmetric because parsing generates an abstract syntax tree. This means we lose backticks around ordinary names, comments, and whitespace:

Be careful when using the base R equivalent, deparse(): it returns a character vector with one element for each line. Whenever you use it, remember that the length of the output might be greater than one, and plan accordingly.

16.4.4 Exercises

  1. R uses parentheses in two slightly different ways as illustrated by these two calls:

    Compare and contrast the two uses by referencing the AST.

  2. = can also be used in two ways. Construct a simple example that shows both uses.

  3. Does -2^2 yield 4 or -4? Why?

  4. What does !1 + !1 return? Why?

  5. Why does x1 <- x2 <- x3 <- 0 work? Describe the two reasons.

  6. Compare the ASTs of x + y %+% z and x ^ y %+% z. What have you learned about the precedence of custom infix functions?

  7. What happens if you call parse_expr() with a string that generates multiple expressions? e.g. parse_expr("x + 1; y + 1")

  8. What happens if you attempt to parse an invalid expression? e.g. "a +" or "f())".

  9. deparse() produces vectors when the input is long. For example, the following call produces a vector of length two:

    What does expr_text() do instead?

  10. pairwise.t.test() assumes that deparse() always returns a length one character vector. Can you construct an input that violates this expectation? What happens?

16.5 Walking the AST with recursive functions

To conclude the chapter I’m going to pull together everything that you’ve learned about ASTs and use that knowledge to solve more complicated problems. The inspiration comes from the base codetools package, which provides two interesting functions:

  • findGlobals() locates all global variables used by a function. This can be useful if you want to check that your function doesn’t inadvertently rely on variables defined in their parent environment.

  • checkUsage() checks for a range of common problems including unused local variables, unused parameters, and the use of partial argument matching.

Getting all of the details of these functions correct is fiddly, so we won’t fully develop the ideas. Instead we’ll focus on the big underlying idea: recursion on the AST. Recursive functions are a natural fit to tree-like data structures because a recursive function is made up of two parts that correspond to the two parts of the tree:

  • The recursive case handles the nodes in the tree. Typically, you’ll do something to each child of node, usually calling the recursive function again, and then combine the results back together again. For expressions, you’ll need to handle calls and pairlists (function arguments).

  • The base case handles the leaves of the tree. The base cases ensure that the function eventually terminates, by solving the simplest cases directly. For expressions, you need to handle symbols and constants in the base case.

To make this pattern easier to see, we’ll need two helper functions. First we define expr_type() which will return “constant” for constant, “symbol” for symbols, “call”, for calls, “pairlist” for pairlists, and the “type” of anything else:

We’ll couple this with a wrapper around the switch function:

With these two functions in hand, the basic template for any function that walks the AST is as follows:

Typically, solving the base case is easy, so we’ll do that first, then check the results. The recursive cases are a little more tricky. Typically you’ll think about the structure of final output and then find the correct purrr function to produce it. To that end, make sure you’re familiar with Functionals before continuing.

16.5.1 Finding F and T

We’ll start simple with a function that determines whether a function uses the logical abbreviations T and F: it will return TRUE if it finds a logical abbreviation, and FALSE otherwise. Using T and F is generally considered to be poor coding practice, and is something that R CMD check will warn about.

Let’s first compare the AST for T vs. TRUE:

TRUE is parsed as a logical vector of length one, while T is parsed as a name. This tells us how to write our base cases for the recursive function: a constant is never a logical abbreviation, and a symbol is an abbreviation if it’s “F” or “T”:

I’ve written logical_abbr_rec() function assuming that the input will be an expression as this will make the recursive operation simpler. However, when writing a recursive function it’s common to write a wrapper that provides defaults or makes the function a little easier to use. Here we’ll typically make a wrapper that quotes its input (we’ll learn more about that in the next chapter), so we don’t need to use expr() every time.

Next we need to implement the recursive cases. Here it’s simple because we want to do the same thing for calls and for pairlists: recursively apply the function to each subcomponent, and return TRUE if any subcomponent contains a logical abbreviation. This is made easy by purrr::some(), which iterates over a list and returns TRUE if the predicate function is true for any element.

16.5.2 Finding all variables created by assignment

logical_abbr() is very simple: it only returns a single TRUE or FALSE. The next task, listing all variables created by assignment, is a little more complicated. We’ll start simply, and then make the function progressively more rigorous.

We start by looking at the AST for assignment:

Assignment is a call object where the first element is the symbol <-, the second is the name of variable, and the third is the value to be assigned.

Next, we need to decide what data structure we’re going to use for the results. Here I think it will be easiest if we return a character vector. If we return symbols, we’ll need to use a list() and that makes things a little more complicated.

With that in hand we can start by implementing the base cases and providing a helpful wrapper around the recursive function. The base cases here are really simple!

Next we implement the recursive cases. This is made easier by a function that should exist in purrr, but currently doesn’t. flat_map_chr() expects .f to return a character vector of arbitrary length, and flattens all results into a single character vector.

The recursive case for pairlists is simple: we iterate over every element of the pairlist (i.e. each function argument) and combine the results. The case for calls is a little bit more complex - if this is a call to <- then we should return the second element of the call:

Now we need to make our function more robust by coming up with examples intended to break it. What happens when we assign to the same variable multiple times?

It’s easiest to fix this at the level of the wrapper function:

What happens if we have nested calls to <-? Currently we only return the first. That’s because when <- occurs we immediately terminate recursion.

Instead we need to take a more rigorous approach. I think it’s best to keep the recursive function focused on the tree structure, so I’m going to extract out find_assign_call() into a separate function.

While the complete version of this function is quite complicated, it’s important to remember we wrote it by working our way up by writing simple component parts.

16.5.3 Exercises

  1. logical_abbr() returns TRUE for T(1, 2, 3). How could you modify logical_abbr_rec() so that it ignores function calls that use T or F?

  2. logical_abbr() works with expressions. It currently fails when you give it a function. Why not? How could you modify logical_abbr() to make it work? What components of a function will you need to recurse over?

  3. Modify find assignment to also detect assignment using replacement functions, i.e. names(x) <- y.

  4. Write a function that extracts all calls to a specified function.

16.6 Specialised data structures

There are two data structures and one special symbol that we need to cover for the sake of completeness. They are not usually important in practice.

16.6.1 Pairlists

Pairlists are a remnant of R’s past and have been replaced by lists almost everywhere. The only place you are likely to see pairlists in R61 is when working with calls to the “function” function, as the formal arguments to a function are stored in a pairlist:

Fortunately, whenever you encounter a pairlist, you can treat it just like a regular list:

Behind the scenes pairlists are implemented using a different data structure, a linked list instead of an array. That makes subsetting a pairlist much slower than subsetting a list, but this has little practical impact.

16.6.2 Missing arguments

There’s one special symbol that needs a little extra discussion: the empty symbol, which is used to represent missing arguments (not missing values!). You only need to care about the missing symbol if you’re programmatically creating functions with missing arguments; we’ll come back to that in Section 17.4.3. You can make an empty symbol with missing_arg() (or expr()):

An empty symbol doesn’t print anything, so check if you have one with rlang::is_missing():

And you’ll find them in the wild in function formals:

The empty symbol has a peculiar property: if you bind it to a variable, then access that variable, you will get an error:

This is the same error you get when referring to a missing argument inside a function, and indeed this is the magic that powers missing arguments.

If you need to preserve the missingness of a variable, rlang::maybe_missing() is often helpful. It allows you to refer to a potentially missing variable without triggering the error.

16.6.3 Expression vectors

Finally, we need to briefly discuss the expression vector. Expression vectors are produced by only two base functions: expression() and parse():

Like calls and pairlists, expression vectors behave like a list:

Conceptually, an expression vector is just a list of expressions. The only difference is that calling eval() on an expression evaluates each individual expression. I don’t believe this advantage merits introducing a new data structure, so instead of expression vectors I just use lists of expressions.

  1. For more complex code, you can also use RStudio’s tree viewer which doesn’t obey quite the same graphical conventions, but allows you to interactively explore the AST. Try it out with View(expr(f(x, "y", 1))).

  2. The names of non-prefix functions are non-syntactic so I show them with `, as in Section 2.2.1.

  3. It is possible to insert any other base type into an expression, but this is unusual and only needed in rare circumstances. We’ll come back to the idea in Section 17.4.7.

  4. Technically, the R language does not possess scalars, and everything that looks like a scalar is actually a vector of length one. This however, is mainly a theoretical distinction, and blurring the distinction between scalar and length-1 vector is unlikely to harm your code.

  5. Technically, the R language does not possess scalars, and everything that looks like a scalar is actually a vector of length one. This however, is mainly a theoretical distinction, and blurring the distinction between scalar and length-1 vector is unlikely to harm your code.

  6. Avoid is.language() which returns TRUE for symbols, calls, and expression vectors.

  7. Peculiarly, it can also be a number, as in the expression 3(). But this call will always fail to evaluate because a number is not a function.

  8. This ambiguity dooes not arise without infix operators, which can be considered an advantage of purely prefix and postfix languages. It’s interesting to compare a simple arithmetic operation in Lisp (prefix) and Forth (postfix). In Lisp you’d write (* (+ 1 2) 3)); this avoids ambiguity by requiring parentheses everywhere. In Forth, you’d write 1 2 + 3 *; this doesn’t require any parentheses, but does require more thought when reading.

  9. If you’re working in C, you’ll encounter pairlists more often. For example, call objects are also implemented using pairlists.