Parser theory

The parser in src/bootstrap/intercalc.sh is a hand-written recursive-descent routine called parse_expr. It handles every expression the grammar allows, produces an abstract syntax tree stored in parallel arrays, and does so in roughly 190 lines. This chapter explains why recursive descent is the right tool for INTERCAL, what "LL(1)" means in our context, and how the parser's shape reflects the grammar.

Context-free grammars, in one paragraph

A context-free grammar is a set of production rules. Each rule has a non-terminal on the left and a sequence of terminals and non-terminals on the right. A parser's job is to take a stream of terminals (tokens from the lexer) and decide whether the stream can be derived from the grammar's start symbol, and if so, how. Context-free languages are strictly more powerful than regular languages: a grammar can nest things, which regular expressions cannot.

The parser construction literature distinguishes many classes of context-free grammars: LL(k), LR(k), LALR(1), SLR, and so on. The class determines which parsing algorithms can handle a given grammar and in what time. The short version: LL(1) grammars are the simplest to parse by hand; LR(1) grammars are more permissive but require tables; LALR(1) is a practical compromise used by yacc and bison.

INTERCAL's grammar class

The expression grammar of INTERCAL, as specified in appendix-grammar.md, is LL(1). That means:

  • At every decision point in the grammar, a one-token lookahead is enough to determine which production to apply.
  • There is no left recursion.
  • There is no ambiguity.

The statement-level grammar is similarly LL(1): the first token after the verb determines the statement type unambiguously (., :, ,, ; → ASSIGN; ( → NEXT; RESUME → RESUME; etc.).

This is not an accident. The language specification deliberately avoids operator precedence, all grouping is explicit, and the statement verbs are all reserved words with unique first tokens. These design choices make the language uniquely suited to hand-written recursive descent.

Why recursive descent

Three reasons we did not use a parser generator:

  • Transparency. Every production in our grammar corresponds to a function in intercalc.sh. Reading parse_expr and seeing parse_primary called for each operand is the same mental operation as reading the grammar. A table-driven LR parser generated by yacc obscures this correspondence.
  • Size. Our grammar has ~15 productions. Setting up a generator's build pipeline, learning the generator's grammar meta-language, and debugging the generated tables would cost more than writing the parser by hand has.
  • Flexibility. Recursive descent lets us mix parsing and codegen freely if we ever want to. We currently do not, the parser produces a tree, and codegen walks the tree, but the option is there.

Almost every production compiler has a hand-written parser for at least some part of the language. The C++ front-end of Clang is a hand-written recursive-descent parser. GCC's C, C++, and Java parsers are all hand-written recursive descent. The Rust compiler's rustc_parse is hand-written recursive descent with limited backtracking. Even where the language grammar is technically LALR-tractable, the implementers usually choose hand-written code for the same reasons we did: better error messages, tighter coupling to the rest of the front end, less generated code to debug. Parser generators remain useful at very large grammar sizes (think: SQL dialects) and in environments where formal verification of parser correctness is a priority.

The shape of parse_expr

The function signature (in zsh terms):

parse_expr(context)
  returns: parse_result = index of root node in the expression-tree arrays
  on failure: parse_result = -1, and a runtime error is queued

The context argument tracks which grouping character is next expected: sparks ' must contain rabbit-ears " directly, and vice versa. Same-in-same nesting (a spark immediately inside another spark) is rejected at parse time with ICL017I, with a diagnostic that names the violation and the statement number it occurred in.

Internally, parse_expr is structured around the grammar:

parse_expr(ctx):
  left = parse_primary(ctx)
  while next token is $ or ~:
    op = consume token
    right = parse_primary(ctx)
    left = new binary node (op, left, right)
  return left

parse_primary(ctx):
  if next token is '#':
    return parse_constant()
  if next token is a prefix (. : , ;):
    return parse_variable_or_array_ref()
  if next token is a unary op (& V ?):
    return parse_unary()
  if next token is a grouping char (' or "):
    return parse_grouped(ctx)

Each call is a single dispatch based on the next token. No backtracking, no table lookups. The recursion depth is at most the expression's nesting depth, which for any realistic INTERCAL program is a handful.

One-token lookahead

Every decision in the parser is made by peeking at the next token (one token of lookahead). This is what "LL(1)" means. The parser never consumes a token, decides that was wrong, and rewinds.

The practical implication: the grammar cannot contain two productions with the same first terminal. Our grammar satisfies this: every production starts with a unique terminal, because the language's punctuation is unambiguous.

If a future extension needed multi-token lookahead, if, for example, we added a construct whose interpretation depended on two tokens ahead, we would have to either refactor the grammar or move to LL(2) or LL(k). The current parser architecture supports arbitrary lookahead by peeking further ahead in the token stream, but we have not needed it.

Why no left recursion

Recursive-descent parsers fail on left-recursive grammars. A rule like expr ::= expr '+' term causes infinite recursion: the parser calls expr, which immediately calls expr again, and so on.

Our grammar is naturally free of left recursion. The expr ::= primary { binary_op primary } form uses iteration (the {...} repetition) rather than recursion for the left-to-right sequence of operands. This is the standard technique for eliminating left recursion from a grammar.

Precedence, associativity, and the choice to have neither

INTERCAL has no operator precedence. a $ b ~ c must be grouped explicitly: either 'a $ b' ~ c or a $ 'b ~ c'. The two mean different things, and the programmer is responsible for saying which.

This sidesteps one of the most error-prone parts of traditional compiler construction: resolving precedence and associativity. For a C-like language, the parser has to know that * binds tighter than +, that - is left-associative, that unary - has different precedence than binary -, and so on. A large part of the Dragon Book is devoted to how parser generators handle these cases.

Our grammar handles them by not having them. Every operator has the same precedence (all binary operators bind left-to-right, trivially), and all grouping is explicit. The parser is correspondingly simpler: a single production for expr handles every operator identically.

The tradeoff is ergonomic. An INTERCAL programmer pays for the simplicity by writing more quote marks. The language design embraces this trade, it is part of INTERCAL's charm.

The expression tree as parallel arrays

Our parser stores the AST in six parallel arrays:

expr_type[i]    node type: NODE_CONST, NODE_VAR, NODE_MINGLE, NODE_SELECT,
                 NODE_UNARY_AND, NODE_UNARY_OR, NODE_UNARY_XOR, NODE_ARRAY_REF
expr_val[i]     constant value or variable number
expr_left[i]    left child index (for binary ops)
expr_right[i]   right child index (for binary ops)
expr_child[i]   single child index (for unary ops)
expr_width[i]   16 or 32, the node's result width

A new node is allocated by incrementing expr_next_id and writing into slot expr_next_id - 1. The parser returns slot indices rather than pointers, because zsh has no pointers.

The parallel-array layout is deliberately portable to INTERCAL. When stage3.i grows a parser, its ASTs will live in INTERCAL arrays with the same layout. This is the kind of design decision that becomes obvious in retrospect: use the most restrictive target's data model as the common denominator.

Parsing and error recovery

Our parser does no error recovery. If an expression is malformed, the parser abandons the statement and, in most cases, the resulting code fires ICL017I or ICL000I at runtime. A production compiler for a non-esoteric language would instrument error recovery to continue parsing after a syntax error, skip tokens until a synchronising point, then resume, so that a single syntax error produces a single error message rather than a cascade.

For INTERCAL this effort is not justified. Every test program is syntactically valid; the real parser bugs have been in how we interpret valid input, not in how we handle invalid input. A human writing an INTERCAL program who gets one error at a time learns faster.

Parsing in stage3.i

The pure-INTERCAL parser will follow the same recursive-descent pattern, with INTERCAL's constraints:

  • No function calls other than NEXT / RESUME. Recursion is expressed by pushing return addresses onto the NEXT stack and popping them after the parse completes.
  • No local variables. Parser state lives in global scalar variables, saved and restored across recursive calls using STASH and RETRIEVE.
  • No dictionaries or associative arrays. Token-type lookup is a chain of conditionals or a table in an array.

Writing a recursive-descent parser in INTERCAL is a serious exercise in discipline. The stash-retrieve protocol for preserving parser state across recursion is the only mechanism INTERCAL offers for local variables. The parser logic itself is not complicated; the book-keeping is.

Parser generators and modern alternatives

If we ever decided to replace our hand-written parser, the options span a wider design space than Bison alone:

  • Flex + Bison / Yacc. The classical Unix pair. Produces LALR(1) parsers. Widely available, well-tested, C-only output. Half a century of compiler infrastructure rests on these tools.

  • ANTLR. A modern LL(k) generator with semantic predicates and multiple output languages (Java, C#, Python, C++, etc.). More readable generated code than Bison, at the cost of being heavier-weight and a Java dependency.

  • Parser combinator libraries. Higher-order functions composed into parsers, written directly in the host language. Examples: Haskell's Parsec / Megaparsec, F#'s FParsec, JavaScript's Chevrotain, Rust's nom and chumsky. Each parse rule is a first-class value, giving the compositionality of a grammar specification with the introspectability of normal code. Closest in spirit to hand-written recursive descent.

  • Packrat parsers and PEGs. Bryan Ford's 2002 ICFP paper (Packrat Parsing: Simple, Powerful, Lazy, Linear Time) introduced parsing expression grammars (PEGs) as an alternative to context-free grammars. PEGs differ from CFGs in two important ways: alternation is ordered (the first matching alternative wins, removing ambiguity by construction) and they freely allow lookahead and negation. Packrat parsing implements PEGs with linear-time guarantees via memoisation, every (rule, position) pair is computed at most once. Modern packrat-style tools include peg, pest (Rust), and Lark's Earley mode.

  • Earley parsers. General-purpose parsers that handle any context-free grammar, including ambiguous ones, in O(n³) worst case but linear time on most practical grammars. Used in NLP and in places where the grammar is not yet stable. Good safety property: if you write an ambiguous grammar by accident, an Earley parser will tell you, where an LALR generator would silently shift-reduce.

The trade-off space:

ApproachGrammar classPerformanceBest for
Hand-written recursive descentLL(1) typicallyFast, simpleSmall to medium grammars, error-message quality matters
Bison/yaccLALR(1)FastLarge grammars where the LALR(1) restriction is acceptable
ANTLRLL(*)FastCross-language code generation
Parser combinatorsLL(k), backtrackingVariableDSLs embedded in a host language
Packrat / PEGPEGO(n) memoisedGrammars with natural ordered alternatives
EarleyAny CFGO(n³) worst caseAmbiguous or evolving grammars

For an INTERCAL-sized grammar, hand-written recursive descent is clearly correct. Parser combinators would be the closest-to-our-implementation alternative if we ever wanted to express the grammar more declaratively. PEG and packrat would be overkill but would handle the spark/rabbit-ears alternation slightly more elegantly through ordered alternation.

We are not contemplating any of these. The hand-written parser is short and matches the grammar exactly. The exercise of imagining what a generator would look like is more useful than the migration would be.

Exercises

  1. Write out the grammar from appendix-grammar.md as a list of productions. For each production, identify the terminal or non-terminal that can appear as the first symbol of a derivation (the FIRST set). Confirm that no two alternatives of the same non-terminal have overlapping FIRST sets.
  2. Extend the grammar to add a fourth binary operator @ for some hypothetical new operation. Does the parser need to change? If so, what specifically?
  3. Construct an expression that would force the parser to recurse five levels deep. How does this differ from what an LR parser would do on the same expression?
  4. Our parser has no error recovery. Describe two common parsing errors (e.g. unbalanced sparks, a variable prefix with no number) and what error message you would want the parser to produce. Sketch the code change that would produce it.
  5. The parallel-array layout of the AST is portable to INTERCAL. What does it sacrifice compared to a linked-structure AST a typical language implementation would use?

Next reading