Conceptcore
Recursive descent parsing
Also called recursive descent parser, top-down parsing, Pratt parsing, precedence climbing, top down operator precedence.
A recursive descent parser has one function for each rule of the grammar. Each function reads its tokens and calls the functions of inner rules, so the call stack follows the nesting of the input.
- Applies to
- core-languages
Idea
A parser reads a sequence of tokens and finds its structure. A recursive descent parser does this with ordinary functions. There is one function for each rule of the grammar. The function for a rule reads the tokens that the rule matches. Where the rule refers to another rule, the function calls the function of that rule. Where a rule refers to itself, through parentheses for example, the function calls itself. The call stack of the parser then has the same shape as the nesting of the input.
The method is called top-down because it starts from the outermost rule and works down to the leaves. GCC, V8 and Roslyn use it.1 It needs no generator tool. The programmer writes each error message, and the code follows the grammar closely enough that a reader can check one against the other.
The grammar on this page covers integer arithmetic. Each line is one rule, and each rule becomes one function.
expr = term { ("+" | "-") term }
term = unary { ("*" | "/") unary }
unary = "-" unary | power
power = atom [ "^" unary ]
atom = NUMBER | "(" expr ")"
{ ... } means zero or more times, [ ... ] means optional, and | separates choices. The order of the rules gives the precedence: + and - bind loosest, ^ binds tightest. The form of the rules gives the associativity, as the next section shows.
How it works
Tokens first
A lexer, also called a tokenizer, turns the characters into tokens. A parser that works on tokens does not have to skip spaces or read the digits of a number. Each token keeps its position, so that an error message can point at the source.
One function per rule
The parser keeps an index into the token list. peek looks at the next token without using it, and take uses it. One token of lookahead is enough for this grammar: the next token always tells the parser which choice to take. Each function returns the text of its rule with full parentheses and the value of the rule. A real front end returns an Abstract syntax tree node instead.
def tokenize(src):
tokens, i = [], 0
while i < len(src):
c = src[i]
if c.isspace():
i += 1
elif c.isdigit():
j = i
while j < len(src) and src[j].isdigit():
j += 1
tokens.append(("num", src[i:j], i))
i = j
elif c in "+-*/^()":
tokens.append((c, c, i))
i += 1
else:
raise SyntaxError(f"unexpected character {c!r} at column {i + 1}")
tokens.append(("end", "", len(src)))
return tokens
def combine(op, left, right):
(ltext, a), (rtext, b) = left, right
match op:
case "+":
value = a + b
case "-":
value = a - b
case "*":
value = a * b
case "/":
value = a // b
case "^":
value = a**b
return f"({ltext} {op} {rtext})", value
class Parser:
def __init__(self, src):
self.tokens = tokenize(src)
self.i = 0
def peek(self):
return self.tokens[self.i][0]
def take(self):
self.i += 1
return self.tokens[self.i - 1]
def fail(self, expected):
column = self.tokens[self.i][2] + 1
raise SyntaxError(f"expected {expected} at column {column}")
def parse(self):
result = self.expr()
if self.peek() != "end":
self.fail("an operator")
return result
def expr(self): # expr = term { ("+" | "-") term }
left = self.term()
while self.peek() in ("+", "-"):
op = self.take()[0]
left = combine(op, left, self.term())
return left
def term(self): # term = unary { ("*" | "/") unary }
left = self.unary()
while self.peek() in ("*", "/"):
op = self.take()[0]
left = combine(op, left, self.unary())
return left
def unary(self): # unary = "-" unary | power
if self.peek() == "-":
self.take()
text, value = self.unary()
return f"(-{text})", -value
return self.power()
def power(self): # power = atom [ "^" unary ]
base = self.atom()
if self.peek() == "^":
self.take()
return combine("^", base, self.unary())
return base
def atom(self): # atom = NUMBER | "(" expr ")"
kind, text, _ = self.tokens[self.i]
if kind == "num":
self.take()
return text, int(text)
if kind == "(":
self.take()
inner = self.expr()
if self.peek() != ")":
self.fail("')'")
self.take()
return inner
self.fail("a number or '('")
for src in ["1 + 2 * 3", "1 - 2 - 3", "2 ^ 3 ^ 2", "-2 ^ 2", "(1 + 2) * 3", "1 + * 2", "(1 + 2", "1 $ 2"]:
try:
text, value = Parser(src).parse()
print(f"{src} -> {text} = {value}")
except SyntaxError as e:
print(f"{src} -> error: {e}")
1 + 2 * 3 -> (1 + (2 * 3)) = 7
1 - 2 - 3 -> ((1 - 2) - 3) = -4
2 ^ 3 ^ 2 -> (2 ^ (3 ^ 2)) = 512
-2 ^ 2 -> (-(2 ^ 2)) = -4
(1 + 2) * 3 -> ((1 + 2) * 3) = 9
1 + * 2 -> error: expected a number or '(' at column 5
(1 + 2 -> error: expected ')' at column 7
1 $ 2 -> error: unexpected character '$' at column 3
Precedence comes from the layers
expr calls term for each operand, and term calls unary. So a * is always consumed inside a term, before expr sees the next +. In 1 + 2 * 3, the multiplication is complete before the addition can use its result. A grammar with one layer per level of precedence is called stratified.2 Parentheses work because atom calls expr again from the bottom layer. The text inside them is parsed as a whole expression and returned as one operand.
Associativity comes from loops and recursion
1 - 2 - 3 must mean (1 - 2) - 3. The loop in expr gives that: it combines the first two operands, then uses the result as the left operand of the next -. A loop makes an operator left-associative.
2 ^ 3 ^ 2 must mean 2 ^ (3 ^ 2). The function power does not loop. After ^, it calls unary, which can reach power again, so the right operand takes the rest of the chain. Recursion on the right makes an operator right-associative.
-2 ^ 2 is -(2 ^ 2), because unary handles the minus and then calls power for the operand. Python's power operator has the same rule: it "binds more tightly than unary operators on its left", and -1**2 is -1.5
The call stack follows the input
Each call of a rule function is a frame on the stack (see Recursion). The trace shows the calls for 1 - 2 * 3. The indentation is the depth of the call.
tokens = ["1", "-", "2", "*", "3", "end"]
pos = 0
depth = 0
def traced(fn):
def wrapper():
global depth
print(" " * depth + fn.__name__ + " at " + tokens[pos])
depth += 1
result = fn()
depth -= 1
return result
return wrapper
@traced
def expr():
global pos
value = term()
while tokens[pos] in ("+", "-"):
op = tokens[pos]
pos += 1
right = term()
value = value + right if op == "+" else value - right
return value
@traced
def term():
global pos
value = atom()
while tokens[pos] == "*":
pos += 1
value *= atom()
return value
@traced
def atom():
global pos
pos += 1
return int(tokens[pos - 1])
print(expr())
expr at 1
term at 1
atom at 1
term at 2
atom at 2
atom at 3
-5
Each number is read by atom at the bottom of a chain of calls. The first number needs a call at every level. The deepest point of the stack matches the deepest nesting of the input. The * is handled inside the second term call, which is why 2 * 3 is one operand of -.
Pratt parsing
A stratified grammar needs one function per level of precedence, and every operand passes through all the levels. A language with fifteen levels of precedence pays for fifteen calls before it reaches a number. Pratt's method, top down operator precedence, uses one function and a table of numbers instead.4
Pratt builds on Floyd's operator precedence. In that scheme, a number is associated with each argument position of an operator. These numbers "are sometimes called binding powers", and an operand goes to the operator whose argument position has the higher number.3 In Pratt's parser, each token has a left binding power, lbp. The parser function takes a right binding power, rbp, the strength with which the caller holds on to the operand. The parser keeps extending the left operand while the next token binds more tightly: "To return to q0 we require rbp < lbp."4
A token can play two roles. Its nud (null denotation) is its meaning with no expression on its left. Its led (left denotation) is its meaning with an expression on its left. In Pratt's words, "the nud of - denotes unary minus, and its led, binary minus".4 For right associativity, Pratt decrements by 1 the right binding powers of the class.3 Here ^ has a left binding power of 30 and calls the parser for its right operand with 29, so a second ^ (30 > 29) joins the right operand.
import re
LBP = {"+": 10, "-": 10, "*": 20, "/": 20, "^": 30}
RIGHT_ASSOC = {"^"}
UNARY_MINUS_BP = 25
def combine(op, left, right):
(ltext, a), (rtext, b) = left, right
match op:
case "+":
value = a + b
case "-":
value = a - b
case "*":
value = a * b
case "/":
value = a // b
case "^":
value = a**b
return f"({ltext} {op} {rtext})", value
def parse(src):
tokens = re.findall(r"\d+|[-+*/^()]", src) + ["end"]
pos = 0
def expression(rbp):
nonlocal pos
token = tokens[pos]
pos += 1
# nud: the meaning of a token with nothing on its left
if token.isdigit():
left = (token, int(token))
elif token == "-":
text, value = expression(UNARY_MINUS_BP)
left = (f"(-{text})", -value)
elif token == "(":
left = expression(0)
pos += 1 # skip ")"
else:
raise SyntaxError(f"unexpected {token!r}")
# led: extend the left operand while the next operator binds tighter
while LBP.get(tokens[pos], 0) > rbp:
op = tokens[pos]
pos += 1
right_bp = LBP[op] - 1 if op in RIGHT_ASSOC else LBP[op]
left = combine(op, left, expression(right_bp))
return left
return expression(0)
for src in ["1 + 2 * 3", "1 - 2 - 3", "2 ^ 3 ^ 2", "-2 ^ 2", "(1 + 2) * 3", "8 / 4 / 2"]:
text, value = parse(src)
print(f"{src} -> {text} = {value}")
1 + 2 * 3 -> (1 + (2 * 3)) = 7
1 - 2 - 3 -> ((1 - 2) - 3) = -4
2 ^ 3 ^ 2 -> (2 ^ (3 ^ 2)) = 512
-2 ^ 2 -> (-(2 ^ 2)) = -4
(1 + 2) * 3 -> ((1 + 2) * 3) = 9
8 / 4 / 2 -> ((8 / 4) / 2) = 1
The results agree with the stratified parser. The precedence is now data: a table of numbers, not a chain of functions. To add an operator, the programmer adds a row to the table.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Idiom | |
| Java | Idiom | |
| C | Idiom | |
| C# | Idiom | |
| JavaScript | Idiom | |
| TypeScript | Idiom | |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Idiom | |
| SQL | Does not apply | A query language works on tables; it has no functions that recurse over a token list. |
| Bash | Idiom | Shell functions can recurse over a global token array and a global index, but every value passes through strings and global variables, so the parser is slow and hard to read. Alternative: A parser written in a general language, called from the script. |
| PowerShell | Idiom | Functions and a script-scope index into the token list give a recursive descent parser; no example file because PowerShell is not installed on the machine that recorded the examples. |
| HTML | Does not apply | Markup has no functions. |
| CSS | Does not apply | Style rules have no functions that call each other. |
| Regular expressions | Absent | A regular expression cannot match parentheses nested to any depth, so it cannot parse the expression grammar. Alternative: A recursive descent parser in a general language. |
A recursive descent parser needs functions that can call themselves, a way to return a result and a way to report an error. Every general-purpose language in tier 1 has them, so the verdict is idiom everywhere. The examples implement the grammar of this page with the same inputs and print the same lines.
| Language | Verdict | Form |
|---|---|---|
| Python | idiom | methods on a parser class; SyntaxError for errors |
| JavaScript | idiom | closures over the token index; SyntaxError for errors |
| TypeScript | idiom | as JavaScript, with a type for the result |
| Java | idiom | methods on a parser class; an unchecked exception for errors |
| Kotlin | idiom | methods on a parser class; a fail function of type Nothing throws the error |
| C# | idiom | methods on a parser class; a custom exception for errors |
| Go | idiom | methods on a parser struct; errors returned by panic and recover inside the parser |
| Rust | idiom | methods that return Result; ? passes errors up the recursion |
| C++ | idiom | member functions; an exception for errors |
| C | idiom | functions over a global cursor; setjmp and longjmp for errors |
| PowerShell | idiom | functions and a script-scope index (no example: pwsh is not installed) |
| Bash | idiom | functions and global variables; possible but slow and hard to read |
| SQL | n/a | a query language with no general recursion over a token list |
| Regex | absent | a regular expression cannot match nested parentheses |
| HTML/CSS | n/a | no functions |
The languages differ in how an error leaves the recursion. An exception unwinds all the frames at once. Rust and Go return the error from each level, Rust with ? and Go with an explicit check, or with panic and recover at the top. C has no exceptions; the C example jumps back to the caller with longjmp.
The languages also differ on -2 ^ 2. Python gives ** higher precedence than unary minus on its left.5 JavaScript makes -2 ** 2 a SyntaxError, so the programmer must write the parentheses.6 The JavaScript example shows the error.
CPython's own parser is generated from a grammar. It is a PEG parser, which PEP 617 describes as usually "constructed as a recursive descent parser in which every rule in the grammar corresponds to a function".7
import re
from dataclasses import dataclass
TOKEN = re.compile(r"\s*(?:(?P<num>\d+)|(?P<op>[-+*/^()])|(?P<bad>\S))")
@dataclass
class Num:
value: int
@dataclass
class Neg:
operand: object
@dataclass
class Bin:
op: str
left: object
right: object
def tokenize(src):
tokens = []
for m in TOKEN.finditer(src):
if m["bad"]:
raise SyntaxError(f"unexpected character {m['bad']!r} at column {m.start('bad') + 1}")
kind = "num" if m["num"] else m["op"]
tokens.append((kind, m[m.lastgroup], m.start(m.lastgroup)))
tokens.append(("end", "", len(src)))
return tokens
class Parser:
def __init__(self, src):
self.tokens = tokenize(src)
self.i = 0
def peek(self):
return self.tokens[self.i][0]
def take(self):
self.i += 1
return self.tokens[self.i - 1]
def fail(self, expected):
raise SyntaxError(f"expected {expected} at column {self.tokens[self.i][2] + 1}")
def parse(self):
tree = self.expr()
if self.peek() != "end":
self.fail("an operator")
return tree
def expr(self):
left = self.term()
while self.peek() in ("+", "-"):
left = Bin(self.take()[0], left, self.term())
return left
def term(self):
left = self.unary()
while self.peek() in ("*", "/"):
left = Bin(self.take()[0], left, self.unary())
return left
def unary(self):
if self.peek() != "-":
return self.power()
self.take()
return Neg(self.unary())
def power(self):
base = self.atom()
if self.peek() != "^":
return base
self.take()
return Bin("^", base, self.unary())
def atom(self):
kind, text, _ = self.tokens[self.i]
if kind == "num":
self.take()
return Num(int(text))
if kind == "(":
self.take()
inner = self.expr()
if self.peek() != ")":
self.fail("')'")
self.take()
return inner
self.fail("a number or '('")
def show(node):
match node:
case Num(value):
return str(value)
case Neg(operand):
return f"(-{show(operand)})"
case Bin(op, left, right):
return f"({show(left)} {op} {show(right)})"
def evaluate(node):
match node:
case Num(value):
return value
case Neg(operand):
return -evaluate(operand)
case Bin("+", l, r):
return evaluate(l) + evaluate(r)
case Bin("-", l, r):
return evaluate(l) - evaluate(r)
case Bin("*", l, r):
return evaluate(l) * evaluate(r)
case Bin("/", l, r):
return evaluate(l) // evaluate(r)
case Bin("^", l, r):
return evaluate(l) ** evaluate(r)
for src in ["1 + 2 * 3", "1 - 2 - 3", "2 ^ 3 ^ 2", "-2 ^ 2", "(1 + 2) * 3", "1 + * 2", "(1 + 2", "1 $ 2"]:
try:
tree = Parser(src).parse()
print(f"{src} -> {show(tree)} = {evaluate(tree)}")
except SyntaxError as e:
print(f"{src} -> error: {e}")
print(Parser("1 - 2 - 3").parse())
1 + 2 * 3 -> (1 + (2 * 3)) = 7
1 - 2 - 3 -> ((1 - 2) - 3) = -4
2 ^ 3 ^ 2 -> (2 ^ (3 ^ 2)) = 512
-2 ^ 2 -> (-(2 ^ 2)) = -4
(1 + 2) * 3 -> ((1 + 2) * 3) = 9
1 + * 2 -> error: expected a number or '(' at column 5
(1 + 2 -> error: expected ')' at column 7
1 $ 2 -> error: unexpected character '$' at column 3
Bin(op='-', left=Bin(op='-', left=Num(value=1), right=Num(value=2)), right=Num(value=3))
- Verdict: idiom. This version separates the two jobs. The parser builds an Abstract syntax tree from dataclasses, and two functions walk the tree with
match: one prints it and one evaluates it. The evaluator is a small Tree-walking interpreter. - The tokenizer is one regular expression with named groups. The group
badmatches any other character, so an unknown character becomes an error and is never skipped. - The last line prints the tree of
1 - 2 - 3. The first subtraction is the left child of the second, which is what left associativity means.
#include <cctype>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
struct Token {
std::string kind, text;
std::size_t col;
};
using Result = std::pair<std::string, long long>;
struct ParseError : std::runtime_error {
using std::runtime_error::runtime_error;
};
std::vector<Token> tokenize(const std::string& src) {
std::vector<Token> tokens;
std::size_t i = 0;
while (i < src.size()) {
char c = src[i];
if (c == ' ') {
++i;
} else if (std::isdigit(static_cast<unsigned char>(c))) {
std::size_t j = i;
while (j < src.size() && std::isdigit(static_cast<unsigned char>(src[j]))) ++j;
tokens.push_back({"num", src.substr(i, j - i), i});
i = j;
} else if (std::string("+-*/^()").find(c) != std::string::npos) {
tokens.push_back({std::string(1, c), std::string(1, c), i});
++i;
} else {
throw ParseError("unexpected character '" + std::string(1, c) + "' at column " + std::to_string(i + 1));
}
}
tokens.push_back({"end", "", src.size()});
return tokens;
}
Result combine(const std::string& op, const Result& l, const Result& r) {
long long a = l.second, b = r.second, v = 1;
if (op == "+") v = a + b;
else if (op == "-") v = a - b;
else if (op == "*") v = a * b;
else if (op == "/") v = a / b;
else for (long long k = 0; k < b; ++k) v *= a;
return {"(" + l.first + " " + op + " " + r.first + ")", v};
}
class Parser {
public:
explicit Parser(const std::string& src) : tokens_(tokenize(src)) {}
Result parse() {
Result result = expr();
if (peek() != "end") fail("an operator");
return result;
}
private:
std::vector<Token> tokens_;
std::size_t i_ = 0;
const std::string& peek() const { return tokens_[i_].kind; }
const Token& take() { return tokens_[i_++]; }
[[noreturn]] void fail(const std::string& expected) const {
throw ParseError("expected " + expected + " at column " + std::to_string(tokens_[i_].col + 1));
}
Result expr() {
Result left = term();
while (peek() == "+" || peek() == "-") {
std::string op = take().kind;
left = combine(op, left, term());
}
return left;
}
Result term() {
Result left = unary();
while (peek() == "*" || peek() == "/") {
std::string op = take().kind;
left = combine(op, left, unary());
}
return left;
}
Result unary() {
if (peek() != "-") return power();
take();
auto [text, value] = unary();
return {"(-" + text + ")", -value};
}
Result power() {
Result base = atom();
if (peek() != "^") return base;
take();
return combine("^", base, unary());
}
Result atom() {
const Token& tok = tokens_[i_];
if (tok.kind == "num") {
take();
return {tok.text, std::stoll(tok.text)};
}
if (tok.kind == "(") {
take();
Result inner = expr();
if (peek() != ")") fail("')'");
take();
return inner;
}
fail("a number or '('");
}
};
int main() {
for (const std::string src : {"1 + 2 * 3", "1 - 2 - 3", "2 ^ 3 ^ 2", "-2 ^ 2", "(1 + 2) * 3", "1 + * 2", "(1 + 2", "1 $ 2"}) {
try {
auto [text, value] = Parser(src).parse();
std::cout << src << " -> " << text << " = " << value << '\n';
} catch (const ParseError& e) {
std::cout << src << " -> error: " << e.what() << '\n';
}
}
}
1 + 2 * 3 -> (1 + (2 * 3)) = 7
1 - 2 - 3 -> ((1 - 2) - 3) = -4
2 ^ 3 ^ 2 -> (2 ^ (3 ^ 2)) = 512
-2 ^ 2 -> (-(2 ^ 2)) = -4
(1 + 2) * 3 -> ((1 + 2) * 3) = 9
1 + * 2 -> error: expected a number or '(' at column 5
(1 + 2 -> error: expected ')' at column 7
1 $ 2 -> error: unexpected character '$' at column 3
- Verdict: idiom. One member function per rule, and an exception class derived from
std::runtime_errorfor errors in the input. failhas the attributenoreturn. The compiler then acceptsatom, which ends with a call tofailand noreturn.- The operator is copied into
opbefore the right operand is parsed. In a call such ascombine(take().kind, left, term()), C++ does not fix the order in which the arguments are evaluated, soterm()could run beforetake().
import java.util.ArrayList;
import java.util.List;
public class Main {
record Token(String kind, String text, int col) {}
record Result(String text, long value) {}
static class ParseError extends RuntimeException {
ParseError(String message) { super(message); }
}
static List<Token> tokenize(String src) {
List<Token> tokens = new ArrayList<>();
int i = 0;
while (i < src.length()) {
char c = src.charAt(i);
if (c == ' ') {
i++;
} else if (Character.isDigit(c)) {
int j = i;
while (j < src.length() && Character.isDigit(src.charAt(j))) j++;
tokens.add(new Token("num", src.substring(i, j), i));
i = j;
} else if ("+-*/^()".indexOf(c) >= 0) {
tokens.add(new Token(String.valueOf(c), String.valueOf(c), i));
i++;
} else {
throw new ParseError("unexpected character '" + c + "' at column " + (i + 1));
}
}
tokens.add(new Token("end", "", src.length()));
return tokens;
}
static long pow(long base, long exp) {
long result = 1;
for (long k = 0; k < exp; k++) result *= base;
return result;
}
static Result combine(String op, Result l, Result r) {
long a = l.value(), b = r.value();
long value = switch (op) {
case "+" -> a + b;
case "-" -> a - b;
case "*" -> a * b;
case "/" -> a / b;
default -> pow(a, b);
};
return new Result("(" + l.text() + " " + op + " " + r.text() + ")", value);
}
static class Parser {
private final List<Token> tokens;
private int i;
Parser(String src) { tokens = tokenize(src); }
Result parse() {
Result result = expr();
if (!peek().equals("end")) throw fail("an operator");
return result;
}
private String peek() { return tokens.get(i).kind(); }
private Token take() { return tokens.get(i++); }
private ParseError fail(String expected) {
return new ParseError("expected " + expected + " at column " + (tokens.get(i).col() + 1));
}
private Result expr() {
Result left = term();
while (peek().equals("+") || peek().equals("-")) left = combine(take().kind(), left, term());
return left;
}
private Result term() {
Result left = unary();
while (peek().equals("*") || peek().equals("/")) left = combine(take().kind(), left, unary());
return left;
}
private Result unary() {
if (!peek().equals("-")) return power();
take();
Result operand = unary();
return new Result("(-" + operand.text() + ")", -operand.value());
}
private Result power() {
Result base = atom();
if (!peek().equals("^")) return base;
take();
return combine("^", base, unary());
}
private Result atom() {
Token tok = tokens.get(i);
if (tok.kind().equals("num")) {
take();
return new Result(tok.text(), Long.parseLong(tok.text()));
}
if (tok.kind().equals("(")) {
take();
Result inner = expr();
if (!peek().equals(")")) throw fail("')'");
take();
return inner;
}
throw fail("a number or '('");
}
}
public static void main(String[] args) {
String[] inputs = {"1 + 2 * 3", "1 - 2 - 3", "2 ^ 3 ^ 2", "-2 ^ 2", "(1 + 2) * 3", "1 + * 2", "(1 + 2", "1 $ 2"};
for (String src : inputs) {
try {
Result r = new Parser(src).parse();
System.out.println(src + " -> " + r.text() + " = " + r.value());
} catch (ParseError e) {
System.out.println(src + " -> error: " + e.getMessage());
}
}
}
}
1 + 2 * 3 -> (1 + (2 * 3)) = 7
1 - 2 - 3 -> ((1 - 2) - 3) = -4
2 ^ 3 ^ 2 -> (2 ^ (3 ^ 2)) = 512
-2 ^ 2 -> (-(2 ^ 2)) = -4
(1 + 2) * 3 -> ((1 + 2) * 3) = 9
1 + * 2 -> error: expected a number or '(' at column 5
(1 + 2 -> error: expected ')' at column 7
1 $ 2 -> error: unexpected character '$' at column 3
- Verdict: idiom. One private method per rule, and records for tokens and results.
failreturns the exception, and the caller writesthrow fail(...). The compiler then knows that the method does not continue after the call, soatomneeds no dummy return value.ParseErrorextendsRuntimeException, so the recursive methods need nothrowsclause. Thecatchinmainhandles only parse errors.
#include <ctype.h>
#include <setjmp.h>
#include <stdio.h>
#include <string.h>
/* The parser state is global: the source, the cursor and the jump target for errors. */
static const char *src;
static size_t pos;
static jmp_buf on_error;
static char message[80];
typedef struct {
char text[128];
long value;
} Result;
static void fail(const char *expected) {
snprintf(message, sizeof message, "expected %s at column %zu", expected, pos + 1);
longjmp(on_error, 1);
}
/* The lexer works on demand: peek skips spaces and returns the next token kind. */
static char peek(void) {
while (src[pos] == ' ') pos++;
char c = src[pos];
if (c == '\0') return 'e';
if (isdigit((unsigned char)c)) return 'n';
if (strchr("+-*/^()", c)) return c;
snprintf(message, sizeof message, "unexpected character '%c' at column %zu", c, pos + 1);
longjmp(on_error, 1);
}
static Result combine(char op, Result l, Result r) {
Result out;
long a = l.value, b = r.value, v = 1;
switch (op) {
case '+': v = a + b; break;
case '-': v = a - b; break;
case '*': v = a * b; break;
case '/': v = a / b; break;
default: for (long k = 0; k < b; k++) v *= a;
}
snprintf(out.text, sizeof out.text, "(%s %c %s)", l.text, op, r.text);
out.value = v;
return out;
}
static Result expr(void);
static Result unary(void);
static Result atom(void) {
Result out;
char k = peek();
if (k == 'n') {
size_t start = pos;
out.value = 0;
while (isdigit((unsigned char)src[pos])) out.value = out.value * 10 + (src[pos++] - '0');
snprintf(out.text, sizeof out.text, "%.*s", (int)(pos - start), src + start);
return out;
}
if (k == '(') {
pos++;
out = expr();
if (peek() != ')') fail("')'");
pos++;
return out;
}
fail("a number or '('");
return out;
}
static Result power(void) {
Result base = atom();
if (peek() != '^') return base;
pos++;
return combine('^', base, unary());
}
static Result unary(void) {
if (peek() != '-') return power();
pos++;
Result r = unary(), out;
snprintf(out.text, sizeof out.text, "(-%s)", r.text);
out.value = -r.value;
return out;
}
static Result term(void) {
Result left = unary();
for (char op = peek(); op == '*' || op == '/'; op = peek()) {
pos++;
left = combine(op, left, unary());
}
return left;
}
static Result expr(void) {
Result left = term();
for (char op = peek(); op == '+' || op == '-'; op = peek()) {
pos++;
left = combine(op, left, term());
}
return left;
}
int main(void) {
const char *inputs[] = {"1 + 2 * 3", "1 - 2 - 3", "2 ^ 3 ^ 2", "-2 ^ 2", "(1 + 2) * 3", "1 + * 2", "(1 + 2", "1 $ 2"};
for (size_t n = 0; n < sizeof inputs / sizeof inputs[0]; n++) {
src = inputs[n];
pos = 0;
if (setjmp(on_error) != 0) {
printf("%s -> error: %s\n", src, message);
continue;
}
Result r = expr();
if (peek() != 'e') fail("an operator");
printf("%s -> %s = %ld\n", src, r.text, r.value);
}
return 0;
}
1 + 2 * 3 -> (1 + (2 * 3)) = 7
1 - 2 - 3 -> ((1 - 2) - 3) = -4
2 ^ 3 ^ 2 -> (2 ^ (3 ^ 2)) = 512
-2 ^ 2 -> (-(2 ^ 2)) = -4
(1 + 2) * 3 -> ((1 + 2) * 3) = 9
1 + * 2 -> error: expected a number or '(' at column 5
(1 + 2 -> error: expected ')' at column 7
1 $ 2 -> error: unexpected character '$' at column 3
- Verdict: idiom. One function per rule over a global cursor. The lexer is not a separate pass:
peekskips spaces and classifies the next character when the parser asks for it. - An error calls
longjmp, which returns control to thesetjmpinmainand discards every frame of the recursion at once. This is safe here because the parser allocates no memory on the heap. A parser that calledmallocwould leak whatever it held at the time of the jump. - The text of each result lives in a fixed buffer of 128 bytes, and
snprintfcuts off longer text. A real parser would build an Abstract syntax tree on the heap instead.
using System;
using System.Collections.Generic;
string[] inputs = { "1 + 2 * 3", "1 - 2 - 3", "2 ^ 3 ^ 2", "-2 ^ 2", "(1 + 2) * 3", "1 + * 2", "(1 + 2", "1 $ 2" };
foreach (var src in inputs)
{
try
{
var (text, value) = new Parser(src).Parse();
Console.WriteLine($"{src} -> {text} = {value}");
}
catch (ParseError e)
{
Console.WriteLine($"{src} -> error: {e.Message}");
}
}
record Token(string Kind, string Text, int Col);
class ParseError(string message) : Exception(message);
class Parser
{
readonly List<Token> tokens = new();
int i;
public Parser(string src)
{
int p = 0;
while (p < src.Length)
{
char c = src[p];
if (c == ' ') { p++; }
else if (char.IsDigit(c))
{
int j = p;
while (j < src.Length && char.IsDigit(src[j])) j++;
tokens.Add(new Token("num", src[p..j], p));
p = j;
}
else if ("+-*/^()".Contains(c)) { tokens.Add(new Token(c.ToString(), c.ToString(), p)); p++; }
else throw new ParseError($"unexpected character '{c}' at column {p + 1}");
}
tokens.Add(new Token("end", "", src.Length));
}
public (string Text, long Value) Parse()
{
var result = Expr();
if (Peek() != "end") throw Fail("an operator");
return result;
}
string Peek() => tokens[i].Kind;
Token Take() => tokens[i++];
ParseError Fail(string expected) => new($"expected {expected} at column {tokens[i].Col + 1}");
static (string, long) Combine(string op, (string Text, long Value) l, (string Text, long Value) r)
{
long a = l.Value, b = r.Value;
long value = op switch
{
"+" => a + b,
"-" => a - b,
"*" => a * b,
"/" => a / b,
_ => (long)Math.Pow(a, b),
};
return ($"({l.Text} {op} {r.Text})", value);
}
(string Text, long Value) Expr()
{
var left = Term();
while (Peek() is "+" or "-") left = Combine(Take().Kind, left, Term());
return left;
}
(string Text, long Value) Term()
{
var left = Unary();
while (Peek() is "*" or "/") left = Combine(Take().Kind, left, Unary());
return left;
}
(string Text, long Value) Unary()
{
if (Peek() != "-") return Power();
Take();
var (text, value) = Unary();
return ($"(-{text})", -value);
}
(string Text, long Value) Power()
{
var b = Atom();
if (Peek() != "^") return b;
Take();
return Combine("^", b, Unary());
}
(string Text, long Value) Atom()
{
var tok = tokens[i];
if (tok.Kind == "num")
{
Take();
return (tok.Text, long.Parse(tok.Text));
}
if (tok.Kind == "(")
{
Take();
var inner = Expr();
if (Peek() != ")") throw Fail("')'");
Take();
return inner;
}
throw Fail("a number or '('");
}
}
1 + 2 * 3 -> (1 + (2 * 3)) = 7
1 - 2 - 3 -> ((1 - 2) - 3) = -4
2 ^ 3 ^ 2 -> (2 ^ (3 ^ 2)) = 512
-2 ^ 2 -> (-(2 ^ 2)) = -4
(1 + 2) * 3 -> ((1 + 2) * 3) = 9
1 + * 2 -> error: expected a number or '(' at column 5
(1 + 2 -> error: expected ')' at column 7
1 $ 2 -> error: unexpected character '$' at column 3
- Verdict: idiom. One method per rule. Each rule returns a named tuple of the text and the value, which the caller can deconstruct.
Peek() is "+" or "-"is a pattern withor. It tests the next token against two constants without repeating the call.ParseErroruses a primary constructor. Thecatchclause handles only errors in the input.
function tokenize(src) {
const tokens = [];
const re = /\s*(?:(\d+)|([-+*/^()])|(\S))/y;
let m;
while ((m = re.exec(src)) !== null) {
if (m[3]) throw new SyntaxError(`unexpected character '${m[3]}' at column ${re.lastIndex}`);
if (m[1]) tokens.push({ kind: "num", text: m[1], col: re.lastIndex - m[1].length });
else if (m[2]) tokens.push({ kind: m[2], text: m[2], col: re.lastIndex - 1 });
else break;
}
tokens.push({ kind: "end", text: "", col: src.length });
return tokens;
}
function combine(op, [lt, a], [rt, b]) {
const value = { "+": a + b, "-": a - b, "*": a * b, "/": Math.trunc(a / b), "^": a ** b }[op];
return [`(${lt} ${op} ${rt})`, value];
}
function parse(src) {
const tokens = tokenize(src);
let i = 0;
const peek = () => tokens[i].kind;
const take = () => tokens[i++];
const fail = (expected) => {
throw new SyntaxError(`expected ${expected} at column ${tokens[i].col + 1}`);
};
function expr() {
let left = term();
while (peek() === "+" || peek() === "-") left = combine(take().kind, left, term());
return left;
}
function term() {
let left = unary();
while (peek() === "*" || peek() === "/") left = combine(take().kind, left, unary());
return left;
}
function unary() {
if (peek() !== "-") return power();
take();
const [text, value] = unary();
return [`(-${text})`, -value];
}
function power() {
const base = atom();
if (peek() !== "^") return base;
take();
return combine("^", base, unary());
}
function atom() {
const tok = tokens[i];
if (tok.kind === "num") {
take();
return [tok.text, Number(tok.text)];
}
if (tok.kind === "(") {
take();
const inner = expr();
if (peek() !== ")") fail("')'");
take();
return inner;
}
fail("a number or '('");
}
const result = expr();
if (peek() !== "end") fail("an operator");
return result;
}
for (const src of ["1 + 2 * 3", "1 - 2 - 3", "2 ^ 3 ^ 2", "-2 ^ 2", "(1 + 2) * 3", "1 + * 2", "(1 + 2", "1 $ 2"]) {
try {
const [text, value] = parse(src);
console.log(`${src} -> ${text} = ${value}`);
} catch (e) {
if (!(e instanceof SyntaxError)) throw e;
console.log(`${src} -> error: ${e.message}`);
}
}
1 + 2 * 3 -> (1 + (2 * 3)) = 7
1 - 2 - 3 -> ((1 - 2) - 3) = -4
2 ^ 3 ^ 2 -> (2 ^ (3 ^ 2)) = 512
-2 ^ 2 -> (-(2 ^ 2)) = -4
(1 + 2) * 3 -> ((1 + 2) * 3) = 9
1 + * 2 -> error: expected a number or '(' at column 5
(1 + 2 -> error: expected ')' at column 7
1 $ 2 -> error: unexpected character '$' at column 3
- Verdict: idiom. The rule functions are closures inside
parse, so they share the token list and the index without a class. - The tokenizer uses a sticky regular expression (flag
y). Each match must start where the last one ended, so no character is skipped without a check. catchtestsinstanceof SyntaxErrorand throws other errors again. A bug in the parser then shows as a bug, not as a syntax error of the input.
JavaScript itself refuses the expression that the grammar above accepts. A unary operator directly before the base of ** is a syntax error, so -2 ** 2 does not parse, and the programmer must write (-2) ** 2 or -(2 ** 2).
for (const src of ["-2 ** 2", "(-2) ** 2", "-(2 ** 2)", "2 ** 3 ** 2"]) {
try {
console.log(`${src} = ${new Function(`return ${src};`)()}`);
} catch (e) {
console.log(`${src} -> ${e.name}`);
}
}
-2 ** 2 -> SyntaxError
(-2) ** 2 = 4
-(2 ** 2) = -4
2 ** 3 ** 2 = 512
type Token = { kind: string; text: string; col: number };
type Result = [text: string, value: number];
class ParseError extends Error {}
function tokenize(src: string): Token[] {
const tokens: Token[] = [];
let i = 0;
while (i < src.length) {
const c = src[i];
if (c === " ") {
i++;
} else if (c >= "0" && c <= "9") {
let j = i;
while (j < src.length && src[j] >= "0" && src[j] <= "9") j++;
tokens.push({ kind: "num", text: src.slice(i, j), col: i });
i = j;
} else if ("+-*/^()".includes(c)) {
tokens.push({ kind: c, text: c, col: i });
i++;
} else {
throw new ParseError(`unexpected character '${c}' at column ${i + 1}`);
}
}
tokens.push({ kind: "end", text: "", col: src.length });
return tokens;
}
function combine(op: string, [lt, a]: Result, [rt, b]: Result): Result {
let value: number;
switch (op) {
case "+": value = a + b; break;
case "-": value = a - b; break;
case "*": value = a * b; break;
case "/": value = Math.trunc(a / b); break;
default: value = a ** b;
}
return [`(${lt} ${op} ${rt})`, value];
}
class Parser {
private tokens: Token[];
private i = 0;
constructor(src: string) {
this.tokens = tokenize(src);
}
parse(): Result {
const result = this.expr();
if (this.peek() !== "end") this.fail("an operator");
return result;
}
private peek(): string {
return this.tokens[this.i].kind;
}
private take(): Token {
return this.tokens[this.i++];
}
private fail(expected: string): never {
throw new ParseError(`expected ${expected} at column ${this.tokens[this.i].col + 1}`);
}
private expr(): Result {
let left = this.term();
while (this.peek() === "+" || this.peek() === "-") left = combine(this.take().kind, left, this.term());
return left;
}
private term(): Result {
let left = this.unary();
while (this.peek() === "*" || this.peek() === "/") left = combine(this.take().kind, left, this.unary());
return left;
}
private unary(): Result {
if (this.peek() !== "-") return this.power();
this.take();
const [text, value] = this.unary();
return [`(-${text})`, -value];
}
private power(): Result {
const base = this.atom();
if (this.peek() !== "^") return base;
this.take();
return combine("^", base, this.unary());
}
private atom(): Result {
const tok = this.tokens[this.i];
if (tok.kind === "num") {
this.take();
return [tok.text, Number(tok.text)];
}
if (tok.kind === "(") {
this.take();
const inner = this.expr();
if (this.peek() !== ")") this.fail("')'");
this.take();
return inner;
}
return this.fail("a number or '('");
}
}
for (const src of ["1 + 2 * 3", "1 - 2 - 3", "2 ^ 3 ^ 2", "-2 ^ 2", "(1 + 2) * 3", "1 + * 2", "(1 + 2", "1 $ 2"]) {
try {
const [text, value] = new Parser(src).parse();
console.log(`${src} -> ${text} = ${value}`);
} catch (e) {
if (!(e instanceof ParseError)) throw e;
console.log(`${src} -> error: ${e.message}`);
}
}
1 + 2 * 3 -> (1 + (2 * 3)) = 7
1 - 2 - 3 -> ((1 - 2) - 3) = -4
2 ^ 3 ^ 2 -> (2 ^ (3 ^ 2)) = 512
-2 ^ 2 -> (-(2 ^ 2)) = -4
(1 + 2) * 3 -> ((1 + 2) * 3) = 9
1 + * 2 -> error: expected a number or '(' at column 5
(1 + 2 -> error: expected ')' at column 7
1 $ 2 -> error: unexpected character '$' at column 3
- Verdict: idiom. The parser is a class with one private method per rule. The result type is a labelled tuple of the text and the value.
failhas the return typenever. The checker knows that the code after a call tofaildoes not run, soatomcan end withreturn this.fail(...).- A dedicated
ParseErrorclass separates errors in the input from bugs in the parser.
package main
import (
"fmt"
"strconv"
"strings"
)
type token struct {
kind, text string
col int
}
type result struct {
text string
value int
}
type parseError struct{ msg string }
func (e parseError) Error() string { return e.msg }
func tokenize(src string) ([]token, error) {
var tokens []token
for i := 0; i < len(src); {
c := src[i]
switch {
case c == ' ':
i++
case c >= '0' && c <= '9':
j := i
for j < len(src) && src[j] >= '0' && src[j] <= '9' {
j++
}
tokens = append(tokens, token{"num", src[i:j], i})
i = j
case strings.IndexByte("+-*/^()", c) >= 0:
tokens = append(tokens, token{string(c), string(c), i})
i++
default:
return nil, parseError{fmt.Sprintf("unexpected character '%c' at column %d", c, i+1)}
}
}
return append(tokens, token{"end", "", len(src)}), nil
}
func combine(op string, l, r result) result {
a, b := l.value, r.value
var v int
switch op {
case "+":
v = a + b
case "-":
v = a - b
case "*":
v = a * b
case "/":
v = a / b
case "^":
v = 1
for k := 0; k < b; k++ {
v *= a
}
}
return result{fmt.Sprintf("(%s %s %s)", l.text, op, r.text), v}
}
type parser struct {
tokens []token
i int
}
func (p *parser) peek() string { return p.tokens[p.i].kind }
func (p *parser) take() token {
p.i++
return p.tokens[p.i-1]
}
func (p *parser) fail(expected string) {
panic(parseError{fmt.Sprintf("expected %s at column %d", expected, p.tokens[p.i].col+1)})
}
func (p *parser) expr() result {
left := p.term()
for p.peek() == "+" || p.peek() == "-" {
left = combine(p.take().kind, left, p.term())
}
return left
}
func (p *parser) term() result {
left := p.unary()
for p.peek() == "*" || p.peek() == "/" {
left = combine(p.take().kind, left, p.unary())
}
return left
}
func (p *parser) unary() result {
if p.peek() != "-" {
return p.power()
}
p.take()
r := p.unary()
return result{"(-" + r.text + ")", -r.value}
}
func (p *parser) power() result {
base := p.atom()
if p.peek() != "^" {
return base
}
p.take()
return combine("^", base, p.unary())
}
func (p *parser) atom() result {
tok := p.tokens[p.i]
switch tok.kind {
case "num":
p.take()
n, _ := strconv.Atoi(tok.text)
return result{tok.text, n}
case "(":
p.take()
inner := p.expr()
if p.peek() != ")" {
p.fail("')'")
}
p.take()
return inner
}
p.fail("a number or '('")
return result{}
}
// parse turns a panic with a parseError back into an ordinary error value.
// Any other panic is a bug in the parser, so it panics again.
func parse(src string) (res result, err error) {
tokens, err := tokenize(src)
if err != nil {
return result{}, err
}
defer func() {
if r := recover(); r != nil {
pe, ok := r.(parseError)
if !ok {
panic(r)
}
err = pe
}
}()
p := &parser{tokens: tokens}
res = p.expr()
if p.peek() != "end" {
p.fail("an operator")
}
return res, nil
}
func main() {
for _, src := range []string{"1 + 2 * 3", "1 - 2 - 3", "2 ^ 3 ^ 2", "-2 ^ 2", "(1 + 2) * 3", "1 + * 2", "(1 + 2", "1 $ 2"} {
r, err := parse(src)
if err != nil {
fmt.Printf("%s -> error: %v\n", src, err)
continue
}
fmt.Printf("%s -> %s = %d\n", src, r.text, r.value)
}
}
1 + 2 * 3 -> (1 + (2 * 3)) = 7
1 - 2 - 3 -> ((1 - 2) - 3) = -4
2 ^ 3 ^ 2 -> (2 ^ (3 ^ 2)) = 512
-2 ^ 2 -> (-(2 ^ 2)) = -4
(1 + 2) * 3 -> ((1 + 2) * 3) = 9
1 + * 2 -> error: expected a number or '(' at column 5
(1 + 2 -> error: expected ')' at column 7
1 $ 2 -> error: unexpected character '$' at column 3
- Verdict: idiom. One method per rule on a
parserstruct. - Go functions return errors as values. Inside a deep recursion that means an
if err != nilcheck after every call. This parser panics with aparseErrorinstead, and the exported entry pointparserecovers it and returns an ordinaryerror. The panic never leaves the package. - The deferred function panics again for any value that is not a
parseError. An index out of range then still shows as a crash. atomends withreturn result{}afterp.fail. The compiler does not know thatfailnever returns, so the function needs a final return.
#[derive(Clone)]
struct Token {
kind: String,
text: String,
col: usize,
}
type Parsed = Result<(String, i64), String>;
fn tokenize(src: &str) -> Result<Vec<Token>, String> {
let bytes = src.as_bytes();
let mut tokens = Vec::new();
let mut i = 0;
while i < bytes.len() {
let c = bytes[i] as char;
if c == ' ' {
i += 1;
} else if c.is_ascii_digit() {
let start = i;
while i < bytes.len() && bytes[i].is_ascii_digit() {
i += 1;
}
tokens.push(Token { kind: "num".into(), text: src[start..i].into(), col: start });
} else if "+-*/^()".contains(c) {
tokens.push(Token { kind: c.to_string(), text: c.to_string(), col: i });
i += 1;
} else {
return Err(format!("unexpected character '{}' at column {}", c, i + 1));
}
}
tokens.push(Token { kind: "end".into(), text: String::new(), col: src.len() });
Ok(tokens)
}
fn combine(op: &str, (lt, a): (String, i64), (rt, b): (String, i64)) -> (String, i64) {
let value = match op {
"+" => a + b,
"-" => a - b,
"*" => a * b,
"/" => a / b,
_ => a.pow(b as u32),
};
(format!("({} {} {})", lt, op, rt), value)
}
struct Parser {
tokens: Vec<Token>,
i: usize,
}
impl Parser {
fn peek(&self) -> &str {
&self.tokens[self.i].kind
}
fn take(&mut self) -> Token {
self.i += 1;
self.tokens[self.i - 1].clone()
}
fn fail<T>(&self, expected: &str) -> Result<T, String> {
Err(format!("expected {} at column {}", expected, self.tokens[self.i].col + 1))
}
fn expr(&mut self) -> Parsed {
let mut left = self.term()?;
while matches!(self.peek(), "+" | "-") {
let op = self.take().kind;
left = combine(&op, left, self.term()?);
}
Ok(left)
}
fn term(&mut self) -> Parsed {
let mut left = self.unary()?;
while matches!(self.peek(), "*" | "/") {
let op = self.take().kind;
left = combine(&op, left, self.unary()?);
}
Ok(left)
}
fn unary(&mut self) -> Parsed {
if self.peek() != "-" {
return self.power();
}
self.take();
let (text, value) = self.unary()?;
Ok((format!("(-{})", text), -value))
}
fn power(&mut self) -> Parsed {
let base = self.atom()?;
if self.peek() != "^" {
return Ok(base);
}
self.take();
Ok(combine("^", base, self.unary()?))
}
fn atom(&mut self) -> Parsed {
match self.peek() {
"num" => {
let tok = self.take();
Ok((tok.text.clone(), tok.text.parse().unwrap()))
}
"(" => {
self.take();
let inner = self.expr()?;
if self.peek() != ")" {
return self.fail("')'");
}
self.take();
Ok(inner)
}
_ => self.fail("a number or '('"),
}
}
}
fn parse(src: &str) -> Parsed {
let mut p = Parser { tokens: tokenize(src)?, i: 0 };
let result = p.expr()?;
if p.peek() != "end" {
return p.fail("an operator");
}
Ok(result)
}
fn main() {
for src in ["1 + 2 * 3", "1 - 2 - 3", "2 ^ 3 ^ 2", "-2 ^ 2", "(1 + 2) * 3", "1 + * 2", "(1 + 2", "1 $ 2"] {
match parse(src) {
Ok((text, value)) => println!("{} -> {} = {}", src, text, value),
Err(msg) => println!("{} -> error: {}", src, msg),
}
}
}
1 + 2 * 3 -> (1 + (2 * 3)) = 7
1 - 2 - 3 -> ((1 - 2) - 3) = -4
2 ^ 3 ^ 2 -> (2 ^ (3 ^ 2)) = 512
-2 ^ 2 -> (-(2 ^ 2)) = -4
(1 + 2) * 3 -> ((1 + 2) * 3) = 9
1 + * 2 -> error: expected a number or '(' at column 5
(1 + 2 -> error: expected ')' at column 7
1 $ 2 -> error: unexpected character '$' at column 3
- Verdict: idiom. Each rule is a method that returns
Result. The?operator returns an error to the caller at once, so an error deep in the recursion travels up through every rule with no extra code. failis generic in its success type. The same function serves a rule that returns a pair and the entry point.matches!(self.peek(), "+" | "-")tests the next token against a pattern with two choices and gives abool.
data class Token(val kind: String, val text: String, val col: Int)
data class Result(val text: String, val value: Long)
class ParseError(message: String) : Exception(message)
fun tokenize(src: String): List<Token> {
val tokens = mutableListOf<Token>()
var i = 0
while (i < src.length) {
val c = src[i]
when {
c == ' ' -> i++
c.isDigit() -> {
var j = i
while (j < src.length && src[j].isDigit()) j++
tokens += Token("num", src.substring(i, j), i)
i = j
}
c in "+-*/^()" -> {
tokens += Token(c.toString(), c.toString(), i)
i++
}
else -> throw ParseError("unexpected character '$c' at column ${i + 1}")
}
}
tokens += Token("end", "", src.length)
return tokens
}
fun combine(op: String, l: Result, r: Result): Result {
val (a, b) = l.value to r.value
val value = when (op) {
"+" -> a + b
"-" -> a - b
"*" -> a * b
"/" -> a / b
else -> (1..b).fold(1L) { acc, _ -> acc * a }
}
return Result("(${l.text} $op ${r.text})", value)
}
class Parser(src: String) {
private val tokens = tokenize(src)
private var i = 0
private fun peek() = tokens[i].kind
private fun take() = tokens[i++]
private fun fail(expected: String): Nothing =
throw ParseError("expected $expected at column ${tokens[i].col + 1}")
fun parse(): Result {
val result = expr()
if (peek() != "end") fail("an operator")
return result
}
private fun expr(): Result {
var left = term()
while (peek() == "+" || peek() == "-") left = combine(take().kind, left, term())
return left
}
private fun term(): Result {
var left = unary()
while (peek() == "*" || peek() == "/") left = combine(take().kind, left, unary())
return left
}
private fun unary(): Result {
if (peek() != "-") return power()
take()
val operand = unary()
return Result("(-${operand.text})", -operand.value)
}
private fun power(): Result {
val base = atom()
if (peek() != "^") return base
take()
return combine("^", base, unary())
}
private fun atom(): Result {
val tok = tokens[i]
return when (tok.kind) {
"num" -> {
take()
Result(tok.text, tok.text.toLong())
}
"(" -> {
take()
val inner = expr()
if (peek() != ")") fail("')'")
take()
inner
}
else -> fail("a number or '('")
}
}
}
fun main() {
for (src in listOf("1 + 2 * 3", "1 - 2 - 3", "2 ^ 3 ^ 2", "-2 ^ 2", "(1 + 2) * 3", "1 + * 2", "(1 + 2", "1 $ 2")) {
try {
val (text, value) = Parser(src).parse()
println("$src -> $text = $value")
} catch (e: ParseError) {
println("$src -> error: ${e.message}")
}
}
}
1 + 2 * 3 -> (1 + (2 * 3)) = 7
1 - 2 - 3 -> ((1 - 2) - 3) = -4
2 ^ 3 ^ 2 -> (2 ^ (3 ^ 2)) = 512
-2 ^ 2 -> (-(2 ^ 2)) = -4
(1 + 2) * 3 -> ((1 + 2) * 3) = 9
1 + * 2 -> error: expected a number or '(' at column 5
(1 + 2 -> error: expected ')' at column 7
1 $ 2 -> error: unexpected character '$' at column 3
- Verdict: idiom. One private function per rule.
whenused as an expression selects the case inatom. failhas the return typeNothing. The compiler knows that it never returns, so it can be a branch of awhenthat must produce aResult.- Destructuring a data class, as in
val (text, value) = ..., unpacks the result.
Variations and related ideas
- Pratt parsing and precedence climbing. One loop and a table of binding powers replace one function per level (see How it works).4 A parser can use functions per rule for statements and a Pratt loop for expressions.
- Backtracking and PEG. A parser that cannot decide with one token of lookahead can try one choice and go back to try another. A PEG parser tries its choices in order. Without help, this backtracking can take exponential time. Packrat parsing avoids that by memoizing the result of each rule at each position, at the cost of memory.7
- Left recursion in PEG. CPython's PEG parser accepts left-recursive rules. It uses a technique based on the memoization cache, so that
rule: rule 'a'does not recurse forever.8 - Error recovery. A parser that stops at the first error reports one problem per run. Panic mode recovery skips tokens until a point where the grammar can restart, such as the end of a statement, and then continues to find more errors.9
- Bottom-up parsers. LR parsers start from the leaves and combine them into larger and larger structures.1
- Parser combinators. A library builds parsers from functions that combine smaller parsers. The result is still recursive descent, written with higher-order functions (see Closure).
Pitfalls
Left recursion
The natural way to write a left-associative operator in a grammar is expr = expr "-" term | term. A rule is left-recursive if it can derive a form that starts with itself.10 The function for such a rule calls itself before it reads a token. The second call is in the same state as the first, so the recursion never ends "until the parser hits a stack overflow and dies".2
This code raises RecursionError, on purpose.
tokens = ["1", "-", "2", "-", "3", "end"]
pos = 0
def expr(): # expr = expr "-" term | term
global pos
left = expr()
if tokens[pos] == "-":
pos += 1
return left - term()
return left
def term():
global pos
pos += 1
return int(tokens[pos - 1])
print(expr())
The fix is the loop: expr = term { "-" term }. The loop consumes a token before it goes around again, so each step makes progress, and it keeps the left associativity.
tokens = ["1", "-", "2", "-", "3", "end"]
pos = 0
def expr(): # expr = term { "-" term }
global pos
left = term()
while tokens[pos] == "-":
pos += 1
left = left - term()
return left
def term():
global pos
pos += 1
return int(tokens[pos - 1])
print(expr())
-4
Right recursion in place of a loop
Another way to remove the left recursion is to move the recursive call to the right: expr = term [ "-" expr ]. The parser now ends, but it parses 1 - 2 - 3 as 1 - (2 - 3). The answer is wrong, and no error tells the programmer.
This code runs but gives a wrong answer on purpose.
tokens = ["1", "-", "2", "-", "3", "end"]
pos = 0
def expr(): # expr = term [ "-" expr ]
global pos
left = term()
if tokens[pos] == "-":
pos += 1
return left - expr()
return left
def term():
global pos
pos += 1
return int(tokens[pos - 1])
print(expr())
2
The result is 2, not -4. Right recursion is correct only for operators that are right-associative, such as ^. Use a loop for the left-associative ones.
Deep nesting overflows the stack
Each ( adds frames for every rule from expr down to atom. Input with thousands of nested parentheses overflows the stack of a recursive descent parser. The input may come from a user or an attacker. CPython sets a limit and reports a syntax error.
try:
eval("(" * 300 + "1" + ")" * 300)
except SyntaxError as e:
print("SyntaxError:", e.msg)
SyntaxError: too many nested parentheses
A parser of untrusted input should count its depth in the function for parentheses and report an error when the count passes a limit. A clear error is better than a crash of the process.
Cost
- Time. With one token of lookahead and no backtracking, each token is read once, and the parser runs in time proportional to the length of the input. Backtracking can make the time exponential unless the parser memoizes, as packrat parsers do.7
- Calls per operand. In a stratified grammar, an operand passes through every level between the current rule and
atom. The trace above shows six calls for three numbers. Pratt parsing makes one call per operand and one table lookup per operator.4 - Stack. The stack depth is proportional to the nesting depth of the input, times the number of levels between
exprandatom. - Code. A recursive descent parser is a few lines per rule. A change to the grammar is a change to the matching function.
History
- 1963. Robert W. Floyd suggested operator precedence. Numbers associated with argument positions, called binding powers, decide which operator takes an operand. Floyd showed that ALGOL 60 could be handled in this way.3
- 1973. Vaughan Pratt published "Top Down Operator Precedence" at the first POPL. He made Floyd's method work top-down, "implementing the stack by means of recursion, a technique known as recursive descent", and attached the nud and led code to the tokens.4
- 2020. PEP 617, created on 24 March 2020, proposed a PEG parser for CPython. The parser supports left-recursive rules through its memoization cache.8
References
- Robert Nystrom, Crafting Interpreters, chapter 6, Parsing Expressions, 6.2 Recursive Descent Parsing
- Robert Nystrom, Crafting Interpreters, chapter 6, Parsing Expressions, 6.1 Ambiguity and the Parsing Game (precedence, associativity, left recursion)
- Vaughan R. Pratt, Top Down Operator Precedence, Proceedings of the 1st ACM SIGACT-SIGPLAN Symposium on Principles of Programming Languages (POPL '73), 1973, pages 41 to 51 (full text at https://tdop.github.io/), section 2.2, Conventions for Linearizing Trees (Floyd's operator precedence, binding powers, decrementing the right binding powers)
- Vaughan R. Pratt, Top Down Operator Precedence, Proceedings of the 1st ACM SIGACT-SIGPLAN Symposium on Principles of Programming Languages (POPL '73), 1973, pages 41 to 51 (full text at https://tdop.github.io/), section 3, Implementation (rbp, lbp, nud, led, recursive descent)
- The Python Language Reference, Expressions, Python 3.14, 6.5 The power operator
- MDN Web Docs, Exponentiation (**), Description
- PEP 617, New PEG parser for CPython, Background on PEG parsers (recursive descent, packrat parsing)
- PEP 617, New PEG parser for CPython, Left recursion
- Robert Nystrom, Crafting Interpreters, chapter 6, Parsing Expressions, 6.3.1 Panic mode error recovery
- PEP 617, New PEG parser for CPython, Lack of left recursion (the definition of a left-recursive rule)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag PQR252 Edit this page History Report an error Markdown