Skip to main content

04 - Top-Down Parsers: LL(1), Recursive Descent

Compute FIRST and FOLLOW with a program, build the LL(1) table, write two parsers and check them on 97,656 strings against an oracle.

What do you think about this article?

04 - Top-Down Parsers: LL(1), Recursive Descent
Formal Languages & Compilersfedericocalo.dev

At a Glance

Compute FIRST and FOLLOW with a program, build the LL(1) table, write two parsers and check them on 97,656 strings against an oracle.

You have a grammar and you want a program that tells you whether a string belongs to it, reading the tokens once, from left to right, without ever going back. An LL(1) parser does exactly that: at every choice between two productions it looks at a single token and decides. When the grammar allows it, the parser is simple, fast and gives precise errors; when it does not, the reason is always one of two (left recursion or common prefixes) and you fix it by rewriting the grammar.

You need the context-free grammars (derivation, tree, ambiguity) of the previous article in the series; the idea of a finite-state automaton comes from regular expressions and from DFAs and NFAs. All the code is Python 3 with no external libraries: the listings were run twice with the same output, on Python 3.14, on 2026-11-13.

What LL(1) means

The name reads like this: the first L says the input is read from the left (left to right), the second L that the derivation being rebuilt is the leftmost one, the 1 that one token of lookahead is enough to decide. The parser starts from the start symbol and expands it, so it works from the top down: that is why it is called top-down.

An everyday example: the librarian who sorts requests reads the first word and already knows which shelf to go to. "Novel...", "Essay...", "Magazine...". If two shelves started with the same word, the librarian would have to read further, or go back, and would stop being a one-glance librarian. A grammar is LL(1) when, for every nonterminal, the first word is always enough. Formally, for every nonterminal A with alternatives α and β, three conditions must hold:

  • the sets FIRST(α) and FIRST(β) are disjoint: no token can start both alternatives;
  • at most one of the two alternatives can derive the empty string ε;
  • if β derives ε, then FIRST(α) and FOLLOW(A) are disjoint: the token that follows A must not also be able to start α.

The first condition is the intuitive one, the third is the subtlest and only makes sense once you have seen FOLLOW: if an alternative can vanish, to know whether to pick that one or the other you have to look at what comes after the nonterminal. The order of the three conditions does not matter: they must all hold. A single violation is enough to give a table cell with two productions, and that is where the one-token parser no longer knows what to do.

FIRST and FOLLOW, computed by the program

FIRST(X) is the set of terminals a string derived from X can start with, plus ε if X can derive the empty string. FOLLOW(A) is the set of terminals that can appear immediately after A in some sentential form, with $ for the end of the input. They are computed by fixed point: you start from empty sets and apply the rules until no set grows any more. Termination is guaranteed because the sets can only grow and the terminals are finitely many.

The following listing is the part that matters most in the whole article. The grammar is a dictionary from a nonterminal to a list of alternatives, and the empty list is the ε production. nullable computes the nullable nonterminals; first_di_sequenza computes FIRST of a sequence X1 X2 ... by scanning the symbols until it finds a non-nullable one; calcola_follow applies the rule by which, in A → α B β, everything in FIRST(β) (ε excluded) enters FOLLOW(B), and if β is nullable FOLLOW(A) enters as well. tabella_ll1 puts the production A → α in the cell M[A, t] for every t in FIRST(α), and for every t in FOLLOW(A) if α is nullable. A cell with two productions is a conflict, and the program counts them.

"""FIRST, FOLLOW and LL(1) table computed from a grammar."""
EPS, FINE = "ε", "$"

# A grammar is a dictionary: nonterminal -> list of alternatives.
# Each alternative is a list of symbols; the empty list is the ε production.
G_ESPR = {
    "E":  [["T", "E'"]],
    "E'": [["+", "T", "E'"], []],
    "T":  [["F", "T'"]],
    "T'": [["*", "F", "T'"], []],
    "F":  [["(", "E", ")"], ["id"]],
}


def nullable(g):
    """Set of nonterminals that derive the empty string (fixed point)."""
    ann = set()
    cambiato = True
    while cambiato:
        cambiato = False
        for a, alts in g.items():
            if a not in ann and any(all(s in ann for s in alt) for alt in alts):
                ann.add(a)
                cambiato = True
    return ann


def first_di_sequenza(seq, first, ann):
    """FIRST of a sequence of symbols; ε appears only if the whole sequence is nullable."""
    out = set()
    for s in seq:
        out |= first[s] if s in first else {s}
        if s not in ann:
            return out
    return out | {EPS}


def calcola_first(g):
    ann = nullable(g)
    first = {a: set() for a in g}
    cambiato = True
    while cambiato:
        cambiato = False
        for a, alts in g.items():
            for alt in alts:
                nuovo = first_di_sequenza(alt, first, ann) - ({EPS} if a not in ann else set())
                if not nuovo <= first[a]:
                    first[a] |= nuovo
                    cambiato = True
    for a in ann:
        first[a].add(EPS)
    return first, ann


def calcola_follow(g, start, first, ann):
    follow = {a: set() for a in g}
    follow[start].add(FINE)
    cambiato = True
    while cambiato:
        cambiato = False
        for a, alts in g.items():
            for alt in alts:
                for i, s in enumerate(alt):
                    if s not in g:
                        continue
                    coda = alt[i + 1:]
                    f = first_di_sequenza(coda, first, ann)
                    nuovo = (f - {EPS}) | (follow[a] if EPS in f else set())
                    if not nuovo <= follow[s]:
                        follow[s] |= nuovo
                        cambiato = True
    return follow


def tabella_ll1(g, start):
    """Returns (table, conflicts). A cell with two productions is a conflict."""
    first, ann = calcola_first(g)
    follow = calcola_follow(g, start, first, ann)
    celle = {}
    for a, alts in g.items():
        for k, alt in enumerate(alts):
            f = first_di_sequenza(alt, first, ann)
            guida = (f - {EPS}) | (follow[a] if EPS in f else set())
            for t in guida:
                celle.setdefault((a, t), []).append((a, tuple(alt)))
    conflitti = {c: p for c, p in celle.items() if len(p) > 1}
    return celle, conflitti, first, follow


def mostra(g, start):
    celle, conflitti, first, follow = tabella_ll1(g, start)
    for a in g:
        print(f"FIRST({a}) = {sorted(first[a])}   FOLLOW({a}) = {sorted(follow[a])}")
    for (a, t) in sorted(celle):
        prod = " | ".join(f"{x} -> {' '.join(r) or EPS}" for x, r in celle[(a, t)])
        print(f"M[{a}, {t}] = {prod}" + ("   <-- CONFLICT" if (a, t) in conflitti else ""))
    print("conflicts:", len(conflitti))


if __name__ == "__main__":
    print("== expressions (no left recursion)")
    mostra(G_ESPR, "E")
    print("== if-then-else, natural version")
    mostra({"S": [["i", "E", "t", "S"], ["i", "E", "t", "S", "e", "S"], ["a"]],
            "E": [["b"]]}, "S")
    print("== if-then-else, after left-factoring")
    mostra({"S": [["i", "E", "t", "S", "S'"], ["a"]],
            "S'": [["e", "S"], []],
            "E": [["b"]]}, "S")

# Output:
# == expressions (no left recursion)
# FIRST(E) = ['(', 'id']   FOLLOW(E) = ['$', ')']
# FIRST(E') = ['+', 'ε']   FOLLOW(E') = ['$', ')']
# FIRST(T) = ['(', 'id']   FOLLOW(T) = ['$', ')', '+']
# FIRST(T') = ['*', 'ε']   FOLLOW(T') = ['$', ')', '+']
# FIRST(F) = ['(', 'id']   FOLLOW(F) = ['$', ')', '*', '+']
# M[E, (] = E -> T E'
# M[E, id] = E -> T E'
# M[E', $] = E' -> ε
# M[E', )] = E' -> ε
# M[E', +] = E' -> + T E'
# M[F, (] = F -> ( E )
# M[F, id] = F -> id
# M[T, (] = T -> F T'
# M[T, id] = T -> F T'
# M[T', $] = T' -> ε
# M[T', )] = T' -> ε
# M[T', *] = T' -> * F T'
# M[T', +] = T' -> ε
# conflicts: 0
# == if-then-else, natural version
# FIRST(S) = ['a', 'i']   FOLLOW(S) = ['$', 'e']
# FIRST(E) = ['b']   FOLLOW(E) = ['t']
# M[E, b] = E -> b
# M[S, a] = S -> a
# M[S, i] = S -> i E t S | S -> i E t S e S   <-- CONFLICT
# conflicts: 1
# == if-then-else, after left-factoring
# FIRST(S) = ['a', 'i']   FOLLOW(S) = ['$', 'e']
# FIRST(S') = ['e', 'ε']   FOLLOW(S') = ['$', 'e']
# FIRST(E) = ['b']   FOLLOW(E) = ['t']
# M[E, b] = E -> b
# M[S, a] = S -> a
# M[S, i] = S -> i E t S S'
# M[S', $] = S' -> ε
# M[S', e] = S' -> e S | S' -> ε   <-- CONFLICT
# conflicts: 1

Read the output for the expression grammar. FOLLOW(F) contains * because in T → F T' what follows is T', and FIRST(T') contains *. It also contains +, ) and $ because T' is nullable, so everything that can follow T can follow F too. No cell has two productions, so the grammar is LL(1). Note that E' and T' have an ε production: the cell M[E', $] and the cell M[E', )] contain E' → ε thanks to FOLLOW, not to FIRST. Without FOLLOW the table would have holes exactly where the expression ends.

When the grammar is not LL(1)

The other two blocks of the output are grammars broken on purpose. The first is if-then-else written in the most natural way: S → i E t S | i E t S e S | a. The first two alternatives begin with the same token i, so the cell M[S, i] has two productions and the program reports the conflict. The standard remedy is left-factoring: you pull out the common prefix and defer the choice to a new nonterminal, S → i E t S S' with S' → e S | ε.

The third part of the output shows that this is not enough: the conflict moves to M[S', e]. The token e is in FIRST(e S) but also in FOLLOW(S'): S' can vanish, and then what follows is what follows S, that is, possibly an e. This is the dangling else case, in which an else can attach to two different ifs. Here the conflict is not a defect of form, it is the ambiguity of the grammar (previous article): no transformation removes it, you have to choose a rule. In the recursive descent parser you pick the alternative e S every time you meet e, that is, the else binds to the nearest if, and the choice is declared in the code instead of being hidden in a table.

There are three causes of non-LL(1), and you must recognize them at a glance:

  • common prefix between two alternatives (A → α β | α γ): solved by left-factoring into A → α A', A' → β | γ;
  • left recursion (A → A α | β): solved with A → β A', A' → α A' | ε;
  • true ambiguity: no mechanical transformation removes it and a design decision is needed.

The first two are mere questions of form and the transformation preserves the language, the third is a property of the language itself. The starting expression grammar, E → E + T | T, is of the second type: E appears as the first symbol of its own body. A recursive descent parser written literally on that rule calls E from inside E without consuming a single token, and never stops. The last line of the verification listing further below shows it: Python stops with a RecursionError. Nystrom, in Crafting Interpreters, observes that top-down techniques such as recursive descent have problems with left recursion, and replaces the rule with an equivalent one that uses repetition, that is, a loop.

The transformation has a price that is often forgotten: E' → + T E' is right-recursive, and the tree that comes out binds a + b + c as a + (b + c). For addition the value does not change, for subtraction it does: (8 - 3) - 2 is 3, 8 - (3 - 2) is 7. You fix it in the parser's actions, building the tree with a loop that accumulates on the left: you do it for real in the last article of the series.

Recursive descent and the table-driven parser

From an LL(1) grammar you get two equivalent parsers. In recursive descent every nonterminal becomes a function, and the choice of alternative is an if on the current token. In the table-driven parser a generic loop uses a stack: if a terminal is on top it compares it with the token, if a nonterminal is on top it looks up the cell M[X, token] and pushes the body of the production onto the stack, in reverse order, so that the first symbol comes out first.

The listing contains both. In Discesa, the methods Ep and Tp pick the non-ε production only if the token is + or *, and otherwise apply ε without checking that the token is in FOLLOW. This is a legitimate choice: if the token is wrong, the error will surface later, when the caller tries to eat something that is not there. In parse_tabella the check is instead made immediately, from the missing cell, and the message lists the expected tokens by reading the table row. Both record the productions used, so that the leftmost derivations can be compared.

"""Two parsers for the same grammar: hand-written recursive descent and table-driven."""
from ll1 import G_ESPR, tabella_ll1, FINE


class ErroreSintassi(Exception):
    pass


class Discesa:
    """One method per nonterminal; each method picks the alternative by looking at ONE token."""

    def __init__(self, tokens):
        self.t = list(tokens) + [FINE]
        self.i = 0
        self.regole = []                      # productions used, in order

    def guarda(self):
        return self.t[self.i]

    def mangia(self, atteso):
        if self.guarda() != atteso:
            raise ErroreSintassi(f"expected {atteso!r}, found {self.guarda()!r} (position {self.i})")
        self.i += 1

    def E(self):
        self.regole.append("E -> T E'")
        self.T(); self.Ep()

    def Ep(self):
        if self.guarda() == "+":
            self.regole.append("E' -> + T E'")
            self.mangia("+"); self.T(); self.Ep()
        else:                                  # FOLLOW(E') = { ), $ }: ε, without checking
            self.regole.append("E' -> ε")

    def T(self):
        self.regole.append("T -> F T'")
        self.F(); self.Tp()

    def Tp(self):
        if self.guarda() == "*":
            self.regole.append("T' -> * F T'")
            self.mangia("*"); self.F(); self.Tp()
        else:
            self.regole.append("T' -> ε")

    def F(self):
        if self.guarda() == "(":
            self.regole.append("F -> ( E )")
            self.mangia("("); self.E(); self.mangia(")")
        elif self.guarda() == "id":
            self.regole.append("F -> id")
            self.mangia("id")
        else:
            raise ErroreSintassi(f"in F expected '(' or 'id', found {self.guarda()!r} (position {self.i})")


def parse_discesa(tokens):
    p = Discesa(tokens)
    p.E()
    p.mangia(FINE)
    return p.regole


def parse_tabella(tokens, tabella, start="E"):
    """Explicit stack: a terminal on top is matched, a nonterminal is expanded."""
    ingresso, i = list(tokens) + [FINE], 0
    pila, regole = [FINE, start], []
    while pila:
        x = pila.pop()
        if x not in {a for a, _ in tabella}:                  # terminal
            if ingresso[i] != x:
                raise ErroreSintassi(f"expected {x!r}, found {ingresso[i]!r} (position {i})")
            i += 1
            continue
        celle = tabella.get((x, ingresso[i]))
        if not celle:
            attesi = sorted(t for (a, t) in tabella if a == x)
            raise ErroreSintassi(f"in {x} expected one of {attesi}, found {ingresso[i]!r} (position {i})")
        a, rhs = celle[0]
        regole.append(f"{a} -> {' '.join(rhs) or 'ε'}")
        pila.extend(reversed(rhs))
    return regole


if __name__ == "__main__":
    tabella, _, _, _ = tabella_ll1(G_ESPR, "E")
    prova = "id + id * ( id + id )".split()
    r1, r2 = parse_discesa(prova), parse_tabella(prova, tabella)
    print("same productions in the same order:", r1 == r2, "-", len(r1), "productions")
    print("first five:", r1[:5])
    for sbagliata in ("id + * id", "( id + id", "id id", ") id"):
        for nome, f in (("discesa", parse_discesa), ("tabella", lambda t: parse_tabella(t, tabella))):
            try:
                f(sbagliata.split())
            except ErroreSintassi as e:
                print(f"{sbagliata!r:14} {nome:8} -> {e}")

# Output:
# same productions in the same order: True - 20 productions
# first five: ["E -> T E'", "T -> F T'", 'F -> id', "T' -> ε", "E' -> + T E'"]
# 'id + * id'    discesa  -> in F expected '(' or 'id', found '*' (position 2)
# 'id + * id'    tabella  -> in T expected one of ['(', 'id'], found '*' (position 2)
# '( id + id'    discesa  -> expected ')', found '$' (position 4)
# '( id + id'    tabella  -> expected ')', found '$' (position 4)
# 'id id'        discesa  -> expected '$', found 'id' (position 1)
# 'id id'        tabella  -> in T' expected one of ['$', ')', '*', '+'], found 'id' (position 1)
# ') id'         discesa  -> in F expected '(' or 'id', found ')' (position 0)
# ') id'         tabella  -> in E expected one of ['(', 'id'], found ')' (position 0)

The output says two things. The first: on the valid string the two parsers apply the same 20 productions in the same order, that is, they rebuild the same leftmost derivation. The second concerns errors: on the string id id the table complains at once in T', listing $ ) * + as allowed tokens, while the descent applies ε for T' and E' and discovers the error only on the way out, when it expects the end of the input. Both reject, but the second message is more useful to whoever writes the program. This is one of the reasons why hand-written parsers often check FOLLOW even where it would not be needed.

Which one to choose? The table is generated from a grammar and changes without rewriting code, and that is the reason parser generators exist. Recursive descent is readable, can be debugged with an ordinary debugger and can be extended with arbitrary actions. Nystrom writes that production compilers such as GCC, V8 and Roslyn use recursive descent; this is a claim by the author of Crafting Interpreters, which I report here as such and which I have not verified on the sources of the three projects.

How to check a parser: an independent oracle

A parser that accepts the two or three examples of the article is not proven correct. The check you can do with little effort is enumeration: build all the strings up to a given length over the token alphabet and verify that the parser accepts them exactly when it should. With 5 tokens (id + * ( )) and maximum length 7 the strings are 97,656, few for the computer and many for the eye. What remains is to decide what "when it should" means: you need a judge that does not share the parser's code.

The judge is an Earley recognizer (Earley, 1970, Communications of the ACM), which accepts any context-free grammar, even a left-recursive and ambiguous one, so it can be queried on the original grammar E → E + T | T. If the LL(1) parser, which works on the transformed grammar, accepts the same strings, the transformation preserved the language. The oracle listing is short: Earley items are quadruples (nonterminal, alternative, dot position, origin) and the three operations, prediction, scan and completion, fill a set for each input position; the line on nullable handles ε productions.

"""Earley recognizer: an oracle independent of the parsers we want to check.

It works for any context-free grammar, even ambiguous or left-recursive.
It uses the same format as ll1.py: dictionary nonterminal -> list of alternatives.
"""


def annullabili(g):
    ann, cambiato = set(), True
    while cambiato:
        cambiato = False
        for a, alts in g.items():
            if a not in ann and any(all(s in ann for s in alt) for alt in alts):
                ann.add(a)
                cambiato = True
    return ann


def riconosce(g, start, tokens):
    ann = annullabili(g)
    # An item is (nonterminal, alternative index, dot position, origin).
    insiemi = [set() for _ in range(len(tokens) + 1)]
    for k in range(len(g[start])):
        insiemi[0].add((start, k, 0, 0))
    for i in range(len(tokens) + 1):
        lavoro = list(insiemi[i])
        while lavoro:
            a, k, p, o = lavoro.pop()
            alt = g[a][k]
            nuovi = []
            if p < len(alt):
                s = alt[p]
                if s in g:                                    # prediction
                    nuovi += [(s, j, 0, i) for j in range(len(g[s]))]
                    if s in ann:                              # skip over nullables
                        nuovi.append((a, k, p + 1, o))
                elif i < len(tokens) and tokens[i] == s:      # scan
                    insiemi[i + 1].add((a, k, p + 1, o))
            else:                                             # completion
                nuovi += [(b, j, q + 1, ob) for (b, j, q, ob) in insiemi[o]
                          if q < len(g[b][j]) and g[b][j][q] == a]
            for e in nuovi:
                if e not in insiemi[i]:
                    insiemi[i].add(e)
                    lavoro.append(e)
    return any((start, k, len(g[start][k]), 0) in insiemi[len(tokens)]
               for k in range(len(g[start])))

This block is a library and prints nothing: the verification program, shown below, uses it. For each string it compares four answers (oracle on the original grammar, oracle on the transformed one, recursive descent, table parser) and counts the disagreements. Then it makes two more checks. The first is a second computation from the opposite side: it generates the sentences of the language by rewriting the leftmost nonterminal, with pruning on length, and compares the set with the recognized one. The second is a mutation: it removes the cell M[T', *] from the table and measures how many disagreements appear, to see whether the check is able to notice a wrong parser.

"""Confirmation on an enumerated set: every string of length <= 7 over the token alphabet."""
from itertools import product

from ll1 import G_ESPR, tabella_ll1
from discesa import parse_discesa, parse_tabella, ErroreSintassi
from oracolo import riconosce

# The "natural" grammar, left-recursive and ambiguous in its derivations: used only by the oracle.
G_ORIG = {
    "E": [["E", "+", "T"], ["T"]],
    "T": [["T", "*", "F"], ["F"]],
    "F": [["(", "E", ")"], ["id"]],
}
ALFABETO = ["id", "+", "*", "(", ")"]
MAX = 7


def accetta(f, s):
    try:
        f(s)
        return True
    except ErroreSintassi:
        return False


def linguaggio_generato(g, start, massimo):
    """Second computation, from the grammar side: all sentences of at most `massimo` tokens.

    Starts from [start] and rewrites the leftmost nonterminal. Here every symbol produces
    at least one token, so a sentential form longer than `massimo` can be discarded.
    """
    viste, frasi, da_fare = set(), set(), [(start,)]
    while da_fare:
        forma = da_fare.pop()
        if forma in viste or len(forma) > massimo:
            continue
        viste.add(forma)
        posto = next((i for i, x in enumerate(forma) if x in g), None)
        if posto is None:
            frasi.add(forma)
            continue
        for alt in g[forma[posto]]:
            da_fare.append(forma[:posto] + tuple(alt) + forma[posto + 1:])
    return frasi


def ricorsione_a_sinistra_ingenua(tokens):
    """Recursive descent written literally on E -> E + T | T: E calls E without consuming anything."""
    def E(i):
        E(i)                      # first alternative: E -> E + T
        return i
    return E(0)


if __name__ == "__main__":
    tabella, conflitti, _, _ = tabella_ll1(G_ESPR, "E")
    guasta = {c: p for c, p in tabella.items() if c != ("T'", "*")}   # table with one cell removed
    tot = valide = disaccordi = disaccordi_guasta = 0
    for n in range(MAX + 1):
        for s in product(ALFABETO, repeat=n):
            s = list(s)
            o = riconosce(G_ORIG, "E", s)           # original grammar
            o2 = riconosce(G_ESPR, "E", s)          # transformed grammar
            d = accetta(parse_discesa, s)
            t = accetta(lambda x: parse_tabella(x, tabella), s)
            tot += 1
            valide += o
            disaccordi += (len({o, o2, d, t}) != 1)
            disaccordi_guasta += (accetta(lambda x: parse_tabella(x, guasta), s) != o)
    print(f"strings examined: {tot}, valid according to the oracle: {valide}, disagreements: {disaccordi}")
    generate = linguaggio_generato(G_ORIG, "E", MAX)
    riconosciute = {tuple(s) for n in range(MAX + 1) for s in product(ALFABETO, repeat=n)
                    if riconosce(G_ORIG, "E", list(s))}
    print("sentences generated by the grammar:", len(generate), "- equal to the recognized ones:", generate == riconosciute)
    print("table with cell M[T', *] removed, disagreements:", disaccordi_guasta)
    print("conflicts in the table:", len(conflitti))
    try:
        ricorsione_a_sinistra_ingenua([])
    except RecursionError as e:
        print("left recursion:", type(e).__name__)

# Output:
# strings examined: 97656, valid according to the oracle: 60, disagreements: 0
# sentences generated by the grammar: 60 - equal to the recognized ones: True
# table with cell M[T', *] removed, disagreements: 38
# conflicts in the table: 0
# left recursion: RecursionError

The 97,656 strings give zero disagreements among the four recognizers, and the sentences generated by the grammar are 60, exactly the 60 that the oracle recognizes: the two computations, starting from opposite sides, agree. The faulty table, instead, is wrong on 38 strings, and this is the number that makes the zero of the others credible: a check that does not notice a known defect proves nothing. The last line confirms the argument of the previous section, recursive descent written on left recursion ends with RecursionError.

The limits must be stated. This is a verification by enumeration up to length 7: it is not a proof of equivalence and it does not cover longer strings, for example parentheses nested to depth 4, which require at least 9 tokens. The argument that holds in general is another one: the left-recursion transformation preserves the language, and the LL(1) table without conflicts makes the parser deterministic. Enumeration serves to find transcription errors, which are the most frequent. To run the listings save the four files in the same folder and launch python3 verifica.py without the -I option, which would prevent Python from importing modules from the current folder.

Beyond one token of lookahead

LL(1) is restrictive: many real languages have constructs that require looking further ahead. You can generalize to LL(k), with k tokens of lookahead, but the tables grow quickly with k. Parr, Harwell and Fisher proposed in 2014 an alternative, Adaptive LL(*), in which the depth of the lookahead is not fixed in advance but is decided during parsing (I verified title, authors and venue on the Crossref registry; the article was not read in full). The trade-off is between the simplicity of the one-token parser and the freedom to write more natural grammars, and it is paid for in analysis cost.

There is also the opposite road: giving up top-down parsing and moving to bottom-up, where the decision is deferred until the whole body of a production has been seen. Grammars with left recursion, like the E → E + T | T we started with, then become natural. You see it in the next article, bottom-up parsers LR(1), SLR and LALR.

What you can do now

Given a language, you can compute FIRST, FOLLOW and the LL(1) table with a program, recognize whether a conflict comes from a common prefix, from left recursion or from true ambiguity, and rewrite the grammar in the first two cases. You can write the same parser as recursive functions and as a loop with a stack, and you can explain why the error messages of the two differ. Above all you can check a parser against an independent judge on an enumerated set, and verify that the check is able to notice a defect. The next step is the sixth article, in which a recursive descent parser feeds semantic analysis, code generation and optimization.

Frequently asked questions

Why does left recursion send a recursive descent parser into a loop?

Because the nonterminal's function calls itself as its first step, before consuming a token: the state does not change and the recursion never has a base case. The verification listing shows it with a RecursionError. You fix it by rewriting the rule as A → β A', A' → α A' | ε, or by using a loop.

Is FOLLOW really needed if I already know FIRST?

Yes, for the productions that can derive ε. When a nonterminal can vanish, the choice to make it vanish depends on what comes next, and that information is in FOLLOW. In the expression example the cells M[E', $] and M[E', )] exist only thanks to FOLLOW.

Does left-factoring always solve an LL(1) conflict?

No. It solves common prefixes, but not ambiguity: in the if-then-else example the conflict moves to M[S', e] because the problem is in the language, not in the form. In that case you choose a rule, for example binding the else to the nearest if, and you write it explicitly in the parser.

Sources

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects