4.2 Source Text, Tokens, and Parsing

INTERPRETERSTATUS: DEVELOPINGLEVEL: INTERMEDIATEREVIEWED: 2026-11-18

Parsing is the first stage of execution. It turns source text into a tree an evaluator can walk. Most mainstream languages hide this tree inside the compiler. R exposes it, as Lisp does, and that is what makes computing on the language possible.

4.2.1 Motivation

Source code is text. Interpreters cannot directly execute text. The interpreter needs a structured representation that separates operations from their arguments, applies rules about operator precedence, and detects syntax errors before evaluation starts.

Parsing happens once per expression or function definition, however many times the code later runs. Its cost is usually small next to the time spent in evaluation and runtime services.

4.2.2 Mental model

Getting from text to a result takes three phases:

  1. Lexing: breaking text into tokens
  2. Parsing: building a tree that respects grammar and precedence
  3. Evaluation: walking the tree to compute results

The lexer answers: where is the boundary between one token and the next?

The parser answers: how do these tokens fit together? Which operators bind first? Where do the function calls nest?

The lexer’s output is a stream of tokens, and the parser’s output is an AST: an abstract syntax tree. Evaluation does not see text anymore. It only sees the tree.

4.2.3 Lexing

A lexer converts source text into a stream of tokens. Each token is a pair: a type and a value. The type identifies what the token represents. The value holds any data it carries.

An identifier such as x is one token. A keyword such as if is one token. An operator such as + is one token. A number such as 42 or 3.14 is one token. Whitespace and comments disappear. They delimit tokens but do not become tokens themselves. R’s newline is the exception: it can end an expression, so R’s lexer passes it to the parser as a token, except inside parentheses and brackets and where the expression must continue, such as after a binary operator.

The lexer scans left to right, reading one character at a time. When it sees a letter, it consumes letters and digits until it hits a non-alphanumeric character, then emits an identifier token. When it sees a digit, it consumes digits and a decimal point (if present), then emits a number token.

Ambiguity can arise. In <-, is that one token (assignment operator) or two (less-than, minus)? Lexers settle this with the longest-match rule: take the longest run of characters that forms a valid token. R’s lexer, in src/main/gram.y, does it by peeking at the character after <. That is why x<-1 assigns 1 to x, and comparing x with minus one needs a space: x < -1.

4.2.4 A worked example: lexing one expression

Consider 1 + 2. The lexer reads:

Position 0: '1'     -> emit NUMBER(1)
Position 1: ' '     -> skip whitespace
Position 2: '+'     -> emit OPERATOR(+)
Position 3: ' '     -> skip whitespace
Position 4: '2'     -> emit NUMBER(2)
End of input

Result: a token stream [NUMBER(1), OPERATOR(+), NUMBER(2)].

For x <- 10, the lexer reads:

Position 0: 'x'     -> consume letters -> emit IDENTIFIER(x)
Position 1: ' '     -> skip whitespace
Position 2: '<'     -> look ahead one char
Position 3: '-'     -> two-char token? yes
                    -> emit OPERATOR(<-)
Position 4: ' '     -> skip whitespace
Position 5: '1'     -> consume digits -> emit NUMBER(10)
End of input

Result: [IDENTIFIER(x), OPERATOR(<-), NUMBER(10)].

The lexer’s job is complete. It has converted text into a sequence of typed tokens.

4.2.5 Grammar and precedence

The parser takes a token stream and builds a tree. It uses a grammar to decide which structures are legal. The grammar says: a call is a function followed by arguments in parentheses. In R’s grammar an assignment is any expression, then <-, then an expression (the rule expr LEFT_ASSIGN expr in gram.y), which is how names(x) <- y parses. Bison generates GNU R’s parser from that file, and the %left and %right lines at its top set each operator’s precedence and associativity.

Some operators are left-associative. a + b + c means (a + b) + c. Some are right-associative. a <- b <- c means a <- (b <- c). Some bind tighter than others. Multiplication comes before addition.

These precedence rules are applied at parse time, not at evaluation time. The tree reflects the intended order. Evaluation later does not need to know about precedence. It only reads the tree shape.

A parse error occurs when the token stream does not match the grammar. 1 + is a syntax error because + expects a right operand that never arrives. f( is an error because the opening parenthesis is never closed. The parser detects these and reports them before evaluation starts: parse(text = "1 +") fails with “unexpected end of input”. At the console, R treats the same line as incomplete and waits for more.

4.2.6 ASTs as output

The output of parsing is an abstract syntax tree. Each node in the tree is one operation or constant. Nodes have children for their operands.

For a + b * c, the parser produces a tree where multiplication nests below the addition node:

    +
   / \
  a   *
     / \
    b   c

Multiplication binds tighter than addition, so b * c nests below +. Because of the tree structure, evaluation finishes * before + can add.

Many languages keep this tree private: the compiler builds it, uses it, and throws it away. R does not.

4.2.7 R’s unusual parser

R is different. When you write quote(a + b * c), you get back the AST itself as a value:

e <- quote(a + b * c)
typeof(e)    # "language"
e[[1]]       # `+`     the function
e[[2]]       # a       first argument
e[[3]]       # b * c   second argument (itself a call)

The tree is built from ordinary R objects. It is data. You can store it, inspect it, and modify it. You can pass it to eval() to execute it later. This one design choice enables metaprogramming: writing code that generates or transforms other code.

GNU R’s parser produces LANGSXP objects (language SEXPs) for calls, SYMSXP for symbols, and atomic values for constants. These are ordinary R objects. The same tree that represents an unevaluated call can be inspected, modified, and re-executed.

Python’s ast module can hand back a tree too, but CPython compiles that tree to bytecode and runs the bytecode. R keeps the tree: body(f) returns a function’s body as a language object even after the byte compiler has compiled it, and the tree-walker can evaluate that same object.

4.2.8 Failure modes

A common mistake is treating quote(expr) and expr as equivalent. They are not. quote(expr) returns a data structure. expr evaluates the structure and returns a result.

e <- quote(1 + 2)       # e is the AST
1 + 2                   # evaluates to 3

eval(e)                 # evaluates the AST, also 3

The tree is not limited to code you quote. body(f) and formals(f) return the parts of a function you call, and inside a function, substitute(arg) returns the unevaluated expression the caller passed and sys.call() returns the call itself.

The parser accepts more than many readers expect. f(x, y = , z) parses, with an empty argument for y, which is what makes x[1, ] legal. f(x y) does not: the parser stops with “unexpected symbol” before any code runs.

4.2.9 R’s parser

How R Executes Code covers R’s parser in detail. It explains what types of objects the parser produces, how it handles the three node kinds, and how deparse() reverses the process.

The next step is evaluation. An interpreter walks this tree. That is the subject of the following pages.

Where this appears

Where to go next

Back to top