Every time a program reads source code, a parser turns a flat string of characters into a tree of meaning. Most modern languages are described by Parsing Expression Grammars (PEGs) — a notation that says, for each grammar rule, "try this alternative first; if it fails, try the next one."
That ordered choice is convenient to write and unambiguous to read, but it hides a danger: a parser that simply tries alternatives may end up re-parsing the same fragment of input hundreds or thousands of times — a classic form of exponential backtracking.
The fix, invented by Bryan Ford in 2002, is almost embarrassingly simple: remember every answer. Before applying a grammar rule at a position, check a table. If the result is already there, return it instantly. If not, compute it, store it, and then return it. Because there are only possible (rule, position) pairs — where is the number of rules and is the input length — the total work is , linear in the input size.
This technique is called packrat parsing, and it guarantees that every PEG grammar is parsed in linear time, with no special-casing or grammar restrictions needed. The price is linear extra memory: one table entry per (rule, position) pair.
Comments
Loading comments...