Every time you hit compile, something quietly extraordinary happens before a single instruction executes. Your source code â a flat river of characters â must be read, understood, and restructured into a parse tree: a nested shape that captures which expressions contain which sub-expressions, which statements belong to which blocks, which operators bind more tightly than others.
That act of restructuring is parsing, and it is governed by the language's context-free grammar (CFG). A CFG is a set of production rules that says things like "an expression is a term, or an expression followed by + and a term." The parser's job is to find which sequence of rule applications produces the exact token stream it sees.
Two great families of algorithms have dominated this space since the 1960s:
- LL (Left-to-right, Leftmost-derivation) parsers build the tree top-down, predicting which rule to apply next by peeking at the next token.
- LR (Left-to-right, Rightmost-derivation in reverse) parsers build the tree bottom-up, using a stack to accumulate tokens and reduce them to grammar symbols whenever a rule's right-hand side is complete.
The letters encode the strategy: L = scan left-to-right, L/R = leftmost vs rightmost derivation, and the optional number k in LL(k) or LR(k) says how many tokens the parser peeks ahead. Most real grammars are handled by LALR(1) or LR(1) â looking just one token ahead â which is both sufficient and efficient.
Comments
Loading comments...