Conceptcore
Context-free grammars
Also called grammar, CFG, BNF, Backus-Naur form, EBNF, ABNF, PEG, parsing expression grammar, production rule, nonterminal, terminal, ambiguous grammar, syntax notation.
A context-free grammar defines the syntax of a language with rules that replace a name by a sequence of names and symbols. BNF, EBNF and PEG are the notations that language definitions use.
- Applies to
- core-languages
Idea
A grammar defines which sequences of tokens are programs of a language. A context-free grammar does this with production rules: each rule says that a name, a nonterminal, can be replaced by a sequence of nonterminals and tokens. The rule E -> E "+" T says that an expression can be an expression, a plus sign and a term. A sequence of tokens belongs to the language when the rules can derive it from the start symbol, and the steps of that derivation form a parse tree. Language references write their grammars in notations for such rules: BNF, EBNF, ABNF and, more and more, parsing expression grammars, or PEGs.
from functools import cache
AMBIGUOUS = { # E -> E "+" E | E "*" E | num
"E": [["E", "+", "E"], ["E", "*", "E"], ["num"]],
}
LAYERED = { # E -> E "+" T | T ; T -> T "*" F | F ; F -> num
"E": [["E", "+", "T"], ["T"]],
"T": [["T", "*", "F"], ["F"]],
"F": [["num"]],
}
def parses(grammar, tokens):
@cache
def trees(sym, i, j): # every tree that derives tokens[i:j] from sym
if sym not in grammar: # a terminal matches exactly one token
ok = j == i + 1 and (tokens[i] == sym or sym == "num" and tokens[i].isdigit())
return [tokens[i]] if ok else []
out = []
for alt in grammar[sym]:
for kids in fill(alt, i, j):
out.append(kids[0] if len(kids) == 1 else "(" + " ".join(kids) + ")")
return out
def fill(alt, i, j): # share tokens[i:j] among the symbols of alt
if len(alt) == 1:
return [[t] for t in trees(alt[0], i, j)]
return [[t] + rest for k in range(i + 1, j - len(alt) + 2)
for t in trees(alt[0], i, k) for rest in fill(alt[1:], k, j)]
return trees("E", 0, len(tokens))
for text in ["1 + 2 * 3", "1 + 2 + 3 + 4 + 5"]:
for name, grammar in [("ambiguous", AMBIGUOUS), ("layered", LAYERED)]:
found = parses(grammar, text.split())
print(f"{name:9} {text:17} {len(found):2} trees {found[:2]}")
ambiguous 1 + 2 * 3 2 trees ['(1 + (2 * 3))', '((1 + 2) * 3)']
layered 1 + 2 * 3 1 trees ['(1 + (2 * 3))']
ambiguous 1 + 2 + 3 + 4 + 5 14 trees ['(1 + (2 + (3 + (4 + 5))))', '(1 + (2 + ((3 + 4) + 5)))']
layered 1 + 2 + 3 + 4 + 5 1 trees ['((((1 + 2) + 3) + 4) + 5)']
The program stores each grammar as data, a map from a nonterminal to its alternatives, and finds every parse tree for a list of tokens by trying each way to share the tokens among the symbols of each rule. Both grammars accept the same expressions. The first grammar is ambiguous: it gives two trees for 1 + 2 * 3 and 14 trees for a sum of five numbers, so it does not say what the expression means. The layered grammar gives one tree for each input, with * below + and each sum grouped from the left, because each rule has only one way to apply.
How it works
Rules, terminals and nonterminals. A context-free grammar has four parts: the terminals, which are the tokens that a lexer produces; the nonterminals, which name the constructs of the language; the production rules; and a start symbol. "Context-free" means that a rule for a nonterminal applies wherever the nonterminal appears, whatever is around it. Bryan Ford sums up the position of these grammars: "For decades we have been using Chomsky’s generative system of grammars, particularly context-free grammars (CFGs) and regular expressions (REs), to express the syntax of programming languages".1 Regular expressions describe the tokens, as in tokens and lexing, and context-free grammars describe how tokens nest.
BNF. The Algol 60 report introduced the notation now called Backus-Naur form. A rule such as <ab> ::= ( | [ | <ab> ( | <ab> <d> defines <ab>, and the report explains: "Sequences of characters enclosed in the bracket <> represent metalinguistic variables whose values are sequences of symbols."2 The ::= reads "is defined as", the | separates alternatives, and repetition needs a recursive rule.
EBNF and its relatives. Extended BNF adds operators for the patterns that BNF writes with extra rules: brackets for an optional part, braces for repetition, and parentheses for grouping. The Go specification states: "The syntax is specified using a variant of Extended Backus-Naur Form (EBNF)", and it adds a naming rule: "Lowercase production names are used to identify lexical (terminal) tokens. Non-terminals are in CamelCase."3 Python's reference uses "a grammar notation that is a mixture of EBNF and PEG".4 Internet standards use ABNF; RFC 5234 says that "a modified version of Backus-Naur Form (BNF), called Augmented BNF (ABNF), has been popular among many Internet specifications."5 Each notation describes the same class of languages, with a different syntax for the rules.
Ambiguity, precedence and associativity. A grammar is ambiguous when one input has two parse trees, as the first grammar in the example shows. A language definition must remove the ambiguity, because each tree gives the program a different meaning. Layered grammars do this for operators: one nonterminal for each level of precedence, with the tighter operators lower in the tree. Left-recursive rules such as E -> E "+" T make an operator group from the left, and right-recursive rules make it group from the right. Where a grammar stays ambiguous, the specification adds a rule in words. C and C++ attach an else to the nearest if, and cppreference states that "the else is associated with the closest if that does not yet have an associated else".6 C++ reads a statement that can be a declaration as a declaration, a rule that "is sometimes counter-intuitive and has been called the most vexing parse".7
Parsing expression grammars. A PEG looks like EBNF but describes a parser, not a set of strings. Ford writes: "Where CFGs express nondeterministic choice between alternatives, PEGs instead use prioritized choice."1 PEP 617, which moved CPython to a PEG parser in Python 3.9, puts it the same way: "The fundamental technical difference is that the choice operator is ordered."8 A PEG is never ambiguous, because the first alternative that matches wins, and a packrat parser runs any PEG in linear time by remembering the results of each rule at each position. The cost is that alternatives must be in the right order, as the Python example shows with < and <=.
From a grammar to a parser. A grammar is also a plan for a parser. Recursive descent writes one function for each nonterminal; parser generators such as yacc, Bison and ANTLR read the grammar and produce the parser; parser combinators build it from functions that mirror the operators of EBNF. Each method has limits. A recursive descent parser cannot use left recursion as written, which PEP 617 defines: "A rule is left-recursive if it can derive to a sentential form with itself as the leftmost symbol."8 Such rules become loops over EBNF repetition, and LR generators accept them directly. The parser builds an abstract syntax tree, which keeps the structure and drops the punctuation.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Library | |
| C++ | Library | |
| Java | Library | |
| C | Library | |
| C# | Library | |
| JavaScript | Library | |
| TypeScript | Library | Peggy, nearley, Chevrotain and ANTLR generate typed parsers from grammars. |
| Go | Library | |
| Rust | Library | |
| Kotlin | Library | ANTLR, better-parse and the Kotlin target of other generators build parsers from grammars; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | Queries do not define grammars; each database parses SQL with its own grammar. |
| Bash | Does not apply | Scripts split text with words, patterns and external tools such as awk, and have no notation for grammars. |
| PowerShell | Idiom | Scripts use .NET regular expressions, whose balancing groups match nested structure; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | Markup has a grammar but cannot define one. |
| CSS | Does not apply | The value definition syntax of the CSS specifications is a grammar notation, but style sheets cannot use it. |
| Regular expressions | Native | A regular expression is a grammar for a regular language, and PCRE and .NET add recursion or balancing groups for nested text. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | library | Lark, pyparsing, ANTLR; CPython parses with a PEG |
| JavaScript | library | Peggy, nearley, Chevrotain; parser combinators |
| TypeScript | library | as JavaScript, with typed parse trees |
| Java | library | ANTLR, JavaCC, parboiled |
| Kotlin | library | ANTLR, better-parse |
| C# | library | ANTLR, Pidgin, Superpower; regex balancing groups |
| Go | library | goyacc, golang.org/x/exp/ebnf; recursive descent |
| Rust | library | pest, LALRPOP, nom, chumsky |
| C | library | yacc, GNU Bison, flex |
| C++ | library | Boost.Spirit, PEGTL, Bison |
| Bash | n/a | no notation for grammars |
| PowerShell | idiom | .NET regular expressions with balancing groups |
| SQL | n/a | queries cannot define grammars |
| Regex | native | a regular expression is a grammar for a regular language |
| HTML | n/a | markup cannot define a grammar |
| CSS | n/a | the value definition syntax is for specifications only |
Every language has a grammar, but no core language of this site has a notation for grammars in its standard library, so the table records how programs get one. Parser generators and combinator libraries exist for all of the general-purpose languages, and ANTLR alone has targets for most of them. Regex is the exception in the other direction: a regular expression is itself a grammar, for the smaller class of regular languages, and the .NET and PCRE engines add features that reach past that class.
Each example file shows a different side of grammars. The Python file shows the ordered choice of a PEG and the effect of right recursion. The JavaScript file writes EBNF rules as parser combinators, and the Rust file turns a layered grammar into recursive descent with loops. The Java file uses a grammar to generate sentences, and the Go file checks a grammar for undefined and unused rules. The C# file matches nested parentheses, which a true regular expression cannot do. The C and C++ files show two places where the grammar of the language is ambiguous and a rule in the standard decides: the dangling else and the most vexing parse.
import re
def lit(s):
return lambda text, i: i + len(s) if text.startswith(s, i) else None
def seq(*parsers):
def parse(text, i):
for p in parsers:
i = p(text, i)
if i is None:
return None
return i
return parse
def choice(*parsers): # PEG: the first alternative that matches wins
def parse(text, i):
for p in parsers:
j = p(text, i)
if j is not None:
return j
return None
return parse
def end(text, i):
return i if i == len(text) else None
short_first = seq(choice(lit("<"), lit("<=")), end)
long_first = seq(choice(lit("<="), lit("<")), end)
for text in ["<", "<="]:
print(f"{text!r:5} short first: {short_first(text, 0) is not None!s:5}"
f" long first: {long_first(text, 0) is not None}")
print("regex <|<= on '<=':", re.fullmatch("<|<=", "<=") is not None)
'<' short first: True long first: True
'<=' short first: False long first: True
regex <|<= on '<=': True
This code runs but gives a wrong answer on purpose.
import re
def tokens(text):
return re.findall(r"\d+|\S", text)
def expr(ts): # expr = number [ "-" expr ] (right recursive)
left = int(ts.pop(0))
if ts and ts[0] == "-":
ts.pop(0)
return left - expr(ts)
return left
print("10 - 3 - 2 =", expr(tokens("10 - 3 - 2")))
10 - 3 - 2 = 9
- Verdict: library. The standard library has no parser generator, so programs use Lark, pyparsing, parsimonious or the Python target of ANTLR. CPython itself parses with a PEG grammar, and the language reference writes its syntax in a mix of EBNF and PEG notation. The run block builds the three PEG operators as functions and shows ordered choice: when
"<"is the first alternative, it matches the start of<=, the choice commits, and the end of input then fails. A regular expression backtracks into the other alternative, so it accepts the same text. - The wrong block follows the rule
expr = number [ "-" expr ]literally. The recursion is on the right, so the parser groups10 - 3 - 2as10 - (3 - 2)and prints 9, not 5. Writeexpr = number { "-" number }and parse the repetition with a loop, as the Rust file does.
#include <iostream>
#include <type_traits>
struct Timer {
Timer() { std::cout << "a Timer is constructed\n"; }
};
int main() {
Timer a(); // the grammar reads this as a function declaration
Timer b{}; // braces always make an object
std::cout << std::boolalpha;
std::cout << "a is a function: " << std::is_function_v<decltype(a)> << '\n';
std::cout << "b is a function: " << std::is_function_v<decltype(b)> << '\n';
}
a Timer is constructed
a is a function: true
b is a function: false
- Verdict: library. Boost.Spirit writes EBNF-like grammars as C++ expressions, PEGTL writes PEG grammars as templates, and Bison generates C++ parsers. The grammar of C++ is ambiguous between declarations and expressions, and the rule is that any statement that can be a declaration is one. So
Timer a();declares a function nameda, and onlybis aTimer. Braces, as inTimer b{};, cannot be read as a declaration of a function.
import java.util.List;
import java.util.Map;
import java.util.Random;
public class Main {
// stmt = name "=" expr ";" | "print" expr ";" .
// expr = term | term "+" expr .
// term = name | number | "(" expr ")" .
static final Map<String, List<List<String>>> GRAMMAR = Map.of(
"stmt", List.of(List.of("name", "=", "expr", ";"), List.of("print", "expr", ";")),
"expr", List.of(List.of("term"), List.of("term", "+", "expr")),
"term", List.of(List.of("name"), List.of("number"), List.of("(", "expr", ")")),
"name", List.of(List.of("x"), List.of("y"), List.of("total")),
"number", List.of(List.of("0"), List.of("1"), List.of("42")));
static void generate(String symbol, Random rnd, StringBuilder out) {
List<List<String>> alts = GRAMMAR.get(symbol);
if (alts == null) { // a terminal stands for itself
out.append(symbol).append(' ');
return;
}
for (String s : alts.get(rnd.nextInt(alts.size()))) {
generate(s, rnd, out);
}
}
public static void main(String[] args) {
Random rnd = new Random(7);
for (int k = 0; k < 6; k++) {
StringBuilder out = new StringBuilder();
generate("stmt", rnd, out);
System.out.println(out.toString().strip());
}
}
}
print y + 1 ;
print x + y + 0 + x + ( 42 + y + ( y ) ) + total + x ;
print ( y ) ;
print y ;
x = total ;
print x + y ;
- Verdict: library. ANTLR, JavaCC and parboiled generate parsers from grammars, and the Java Language Specification defines Java with its own grammar notation. A grammar generates sentences as well as describes them: the example starts from
stmt, picks a random alternative for each nonterminal, and writes terminals as they are. Each output line is a valid statement of the little language. Test tools use this to create inputs for parsers and compilers. A fixed seed makes the output the same on every run.
#include <stdio.h>
#include <stdlib.h>
/* Precedence climbing: a table of levels replaces one grammar rule per level. */
static const char *p;
static int prec(char op) {
switch (op) {
case '+': case '-': return 1;
case '*': case '/': return 2;
case '^': return 3;
default: return 0;
}
}
static void skip(void) {
while (*p == ' ') p++;
}
static long expr(int min);
static long atom(void) {
skip();
if (*p == '(') {
p++;
long v = expr(1);
skip();
p++; /* the closing parenthesis */
return v;
}
char *end;
long v = strtol(p, &end, 10);
p = end;
return v;
}
static long power(long b, long e) {
long r = 1;
while (e-- > 0) r *= b;
return r;
}
static long expr(int min) {
long left = atom();
for (;;) {
skip();
char op = *p;
int q = prec(op);
if (q == 0 || q < min) return left;
p++;
long right = expr(op == '^' ? q : q + 1); /* '^' groups to the right */
switch (op) {
case '+': left += right; break;
case '-': left -= right; break;
case '*': left *= right; break;
case '/': left /= right; break;
default: left = power(left, right); break;
}
}
}
int main(void) {
const char *tests[] = {"10 - 3 - 2", "1 + 2 * 3", "2 ^ 3 ^ 2", "(2 ^ 3) ^ 2"};
for (int i = 0; i < 4; i++) {
p = tests[i];
printf("%-12s = %ld\n", tests[i], expr(1));
}
return 0;
}
10 - 3 - 2 = 5
1 + 2 * 3 = 7
2 ^ 3 ^ 2 = 512
(2 ^ 3) ^ 2 = 64
This code runs but gives a wrong answer on purpose.
#include <stdio.h>
static void check(int a, int b) {
printf("a=%2d b=%2d:", a, b);
if (a > 0)
if (b > 0)
printf(" both positive");
else /* the indentation suggests the outer if */
printf(" a is not positive");
printf("\n");
}
int main(void) {
check(1, 1);
check(1, -1);
check(-1, 1);
return 0;
}
a= 1 b= 1: both positive
a= 1 b=-1: a is not positive
a=-1 b= 1:
- Verdict: library. yacc and its successor GNU Bison generate C parsers from grammars, and lex and flex generate the lexers that feed them. The run block parses with precedence climbing, which replaces one grammar rule for each level with a table of levels. Operators on the left group first, except
^, which groups to the right, so2 ^ 3 ^ 2is2 ^ 9. - The wrong block shows the dangling else. The grammar of C allows both readings of
if (a) if (b) x; else y;, and the standard picks the innerif, whatever the indentation shows. So the second call prints the message for the wrong case, and the third prints nothing. Use braces on every branch of a nestedif.
using System;
using System.Text.RegularExpressions;
// Balanced parentheses form a context-free language, not a regular one.
// .NET balancing groups give the regex engine a stack of captures.
var balanced = new Regex(@"^(?:[^()]|(?<open>\()|(?<-open>\)))*(?(open)(?!))$");
// A true regular expression handles only a fixed depth, here two levels.
var depthTwo = new Regex(@"^(?:[^()]|\((?:[^()]|\([^()]*\))*\))*$");
foreach (var s in new[] { "f(a, g(b))", "((x))", "(((x)))", "f(a))", "(()" })
{
Console.WriteLine($"{s,-11} balancing groups: {balanced.IsMatch(s),-5} depth-two regex: {depthTwo.IsMatch(s)}");
}
f(a, g(b)) balancing groups: True depth-two regex: True
((x)) balancing groups: True depth-two regex: True
(((x))) balancing groups: True depth-two regex: False
f(a)) balancing groups: False depth-two regex: False
(() balancing groups: False depth-two regex: False
- Verdict: library. ANTLR, Pidgin, Superpower and Sprache give C# parsers from grammars or combinators, and Roslyn exposes the syntax of C# itself. Balanced parentheses are the standard example of a context-free language that no regular expression can match. The depth-two pattern shows the limit: a true regular expression must spell out each level, so it rejects
(((x))). .NET adds balancing groups, which push a capture for each(and pop one for each), and the conditional(?(open)(?!))fails if any capture remains.
// Each parser takes (text, pos) and returns [value, newPos], or null on failure.
const lit = (s) => (t, i) => (t.startsWith(s, i) ? [s, i + s.length] : null);
const num = (t, i) => {
const re = /\d+/y;
re.lastIndex = i;
const m = re.exec(t);
return m ? [Number(m[0]), re.lastIndex] : null;
};
const seq = (...ps) => (t, i) => {
const out = [];
for (const p of ps) {
const r = p(t, i);
if (!r) return null;
out.push(r[0]);
i = r[1];
}
return [out, i];
};
const alt = (...ps) => (t, i) => {
for (const p of ps) {
const r = p(t, i);
if (r) return r;
}
return null;
};
const many = (p) => (t, i) => {
const out = [];
for (let r; (r = p(t, i)); i = r[1]) out.push(r[0]);
return [out, i];
};
const opt = (p) => (t, i) => p(t, i) ?? [null, i];
const map = (p, f) => (t, i) => {
const r = p(t, i);
return r && [f(r[0]), r[1]];
};
// list = "[" [ item { "," item } ] "]" .
// item = number | list .
const item = (t, i) => alt(num, list)(t, i);
const rest = many(map(seq(lit(","), item), ([, x]) => x));
const items = map(seq(item, rest), ([x, xs]) => [x, ...xs]);
const list = map(seq(lit("["), opt(items), lit("]")), ([, xs]) => xs ?? []);
for (const text of ["[1,[2,3],[]]", "[10,20]", "[1,]", "[1 2]"]) {
const r = list(text, 0);
const ok = r && r[1] === text.length;
console.log(text.padEnd(13), ok ? JSON.stringify(r[0]) : "syntax error");
}
[1,[2,3],[]] [1,[2,3],[]]
[10,20] [10,20]
[1,] syntax error
[1 2] syntax error
- Verdict: library. Peggy, nearley, Chevrotain and the JavaScript target of ANTLR turn grammars into parsers. The example writes parser combinators, small functions that each match one construct and combine like the operators of EBNF:
seqfor a sequence,altfor a choice,manyfor braces andoptfor brackets. The code forlistanditemthen reads like the two grammar rules in the comment above it, and each rule returns the value that the rule describes.
package main
import (
"fmt"
"regexp"
"sort"
"strings"
)
// A grammar in the EBNF style of the Go specification.
const grammar = `
Expr = Term { ( "+" | "-" ) Term } .
Term = Factor { ( "*" | "/" ) Factor } .
Factor = number | "(" Expr ")" | Call .
Call = name "(" [ ArgList ] ")" .
Args = Expr { "," Expr } .
Unused = "?" .
`
func main() {
defined := map[string]bool{}
used := map[string]bool{"Expr": true} // Expr is the start symbol
symbol := regexp.MustCompile(`"[^"]*"|[A-Za-z_]\w*`)
for _, line := range strings.Split(strings.TrimSpace(grammar), "\n") {
lhs, rhs, _ := strings.Cut(line, "=")
defined[strings.TrimSpace(lhs)] = true
for _, s := range symbol.FindAllString(rhs, -1) {
if s[0] >= 'A' && s[0] <= 'Z' { // CamelCase names are nonterminals
used[s] = true
}
}
}
var undefined, unused []string
for s := range used {
if !defined[s] {
undefined = append(undefined, s)
}
}
for s := range defined {
if !used[s] {
unused = append(unused, s)
}
}
sort.Strings(undefined)
sort.Strings(unused)
fmt.Println("productions:", len(defined))
fmt.Println("undefined: ", undefined)
fmt.Println("unused: ", unused)
}
productions: 6
undefined: [ArgList]
unused: [Args Unused]
- Verdict: library. The
goyacctool ingolang.org/x/toolsgenerates LALR parsers, andgolang.org/x/exp/ebnfreads and checks grammars in the notation of the Go specification. The example does a small part of that check by hand. It reads six productions, treats CamelCase names as nonterminals as the specification does, and reportsArgList, a name that the grammar uses but never defines, and two productions that the start symbol cannot reach. Real grammars collect such mistakes as they grow.
// expr = term { ("+" | "-") term } .
// term = factor { ("*" | "/") factor } .
// factor = number | "(" expr ")" .
enum Expr {
Num(i64),
Bin(char, Box<Expr>, Box<Expr>),
}
struct Parser {
toks: Vec<String>,
pos: usize,
}
impl Parser {
fn peek(&self) -> Option<&str> {
self.toks.get(self.pos).map(|s| s.as_str())
}
fn next(&mut self) -> String {
self.pos += 1;
self.toks[self.pos - 1].clone()
}
fn expr(&mut self) -> Expr {
let mut left = self.term();
while let Some(op @ ("+" | "-")) = self.peek() {
let op = op.chars().next().unwrap();
self.pos += 1;
left = Expr::Bin(op, Box::new(left), Box::new(self.term())); // the loop groups to the left
}
left
}
fn term(&mut self) -> Expr {
let mut left = self.factor();
while let Some(op @ ("*" | "/")) = self.peek() {
let op = op.chars().next().unwrap();
self.pos += 1;
left = Expr::Bin(op, Box::new(left), Box::new(self.factor()));
}
left
}
fn factor(&mut self) -> Expr {
let t = self.next();
if t == "(" {
let e = self.expr();
self.next(); // the closing parenthesis
e
} else {
Expr::Num(t.parse().unwrap())
}
}
}
fn tokens(src: &str) -> Vec<String> {
let mut out = Vec::new();
let mut num = String::new();
for c in src.chars() {
if c.is_ascii_digit() {
num.push(c);
continue;
}
if !num.is_empty() {
out.push(std::mem::take(&mut num));
}
if !c.is_whitespace() {
out.push(c.to_string());
}
}
if !num.is_empty() {
out.push(num);
}
out
}
fn show(e: &Expr) -> String {
match e {
Expr::Num(n) => n.to_string(),
Expr::Bin(op, a, b) => format!("({} {} {})", show(a), op, show(b)),
}
}
fn eval(e: &Expr) -> i64 {
match e {
Expr::Num(n) => *n,
Expr::Bin(op, a, b) => {
let (x, y) = (eval(a), eval(b));
match op {
'+' => x + y,
'-' => x - y,
'*' => x * y,
_ => x / y,
}
}
}
}
fn main() {
for src in ["10 - 3 - 2", "1 + 2 * 3", "(1 + 2) * 3", "100 / 10 / 5"] {
let mut p = Parser { toks: tokens(src), pos: 0 };
let e = p.expr();
println!("{:<13} {:<20} = {}", src, show(&e), eval(&e));
}
}
10 - 3 - 2 ((10 - 3) - 2) = 5
1 + 2 * 3 (1 + (2 * 3)) = 7
(1 + 2) * 3 ((1 + 2) * 3) = 9
100 / 10 / 5 ((100 / 10) / 5) = 2
- Verdict: library. pest uses PEG grammars, LALRPOP generates LR parsers, and nom and chumsky build parsers from combinators. The example turns a layered EBNF grammar into one function per rule. Each level of the grammar is one level of precedence, so
*binds tighter than+, and each repetition in braces becomes awhileloop that builds the tree from the left, so10 - 3 - 2is(10 - 3) - 2. The printed trees show both facts.
Variations and related ideas
- The Chomsky hierarchy. Regular grammars describe tokens, context-free grammars describe nesting, and context-sensitive and unrestricted grammars describe more but are hard to parse. See finite-state machines.
- LL and LR grammars. Subsets of the context-free grammars that a parser can handle with one token of lookahead, top-down for LL and bottom-up for LR and LALR. Parser generators report a conflict when a grammar is outside the subset.
- Attribute grammars. Rules carry computations, such as types or values, that flow up and down the parse tree.
- Syntax diagrams. Railroad diagrams draw each rule as a track, as in the JSON home page and the Pascal and SQLite manuals.
- Scannerless parsing. PEGs and some generalized parsers read characters directly, with no separate lexer, so the grammar also holds the lexical rules.
- Generalized parsing. GLR, Earley and GLL parsers accept every context-free grammar, including ambiguous ones, and return all the trees, as the example does.
- Island and fuzzy grammars. Tools that read code in many languages, or code with errors, parse only the parts that they need.
- Macros and syntax extension. Some languages let programs add rules to the grammar. See syntactic macros.
Pitfalls
- Ambiguous grammars. A grammar with two trees for one input gives two meanings. Layer the rules by precedence, or state the rule that picks one tree, and test the grammar with a parser generator that reports conflicts.
- The wrong associativity. A right-recursive rule makes subtraction group from the right, so
10 - 3 - 2gives 9. The wrong block in the Python file shows this. Use EBNF repetition and build the tree in a loop. - Left recursion in a top-down parser. A recursive descent parser for
E -> E "+" Tcalls itself forever. Rewrite the rule asE -> T { "+" T }. - Order of PEG alternatives. A PEG choice commits to the first alternative that matches, so a short alternative before a longer one with the same start hides the longer one. Put the longer alternative first.
- The dangling else. Indentation does not decide which
ifowns anelsein C, C++, Java, C# and JavaScript. The wrong block in the C file shows this. Use braces. - Regular expressions for nested text. HTML, JSON and source code nest without limit, and a true regular expression handles only a fixed depth. Use a parser.
Cost
A recursive descent or LL parser for an LL grammar, and an LR parser for an LR grammar, run in time linear in the number of tokens. A packrat parser runs a PEG in linear time but stores a result for each rule at each position, so its memory grows with the input times the number of rules, and most PEG parsers, CPython's among them, store results only for some rules. General context-free parsing with Earley or GLR is cubic in the worst case and close to linear for grammars of real languages. Enumerating every tree, as the example does, is exponential, because ambiguous grammars can have a number of trees that grows like the Catalan numbers, 14 for five numbers and 4862 for ten.
History
Noam Chomsky defined context-free grammars, which he called phrase-structure grammars, in 1956 and 1957 to describe natural language. John Backus presented a notation for the syntax of IAL, the language that became Algol, at a conference in Paris in 1959, and Peter Naur used it, with changes, in the Algol 60 report of 1960.2 Donald Knuth proposed the name Backus-Naur form in 1964. Algol 60 was the first major language with a formal grammar. Its 1960 report allowed the dangling else, and the Revised Report of 1963 removed it with a rule that forbids an if statement directly after then.
Stephen C. Johnson wrote yacc at Bell Labs in the 1970s, which made LALR parser generators a standard tool, and Niklaus Wirth proposed EBNF in 1977 to end the variety of notations. ISO standardized a form of EBNF in 1996, and ABNF became an Internet standard with RFC 5234 in 2008.5 Terence Parr started the tool that became ANTLR around 1989. Bryan Ford defined parsing expression grammars in 2004,1 and Python moved to a PEG parser in version 3.9 in 2020.8
References
- Bryan Ford, Parsing Expression Grammars: A Recognition-Based Syntactic Foundation, POPL 2004, Abstract and Introduction
- Revised Report on the Algorithmic Language Algol 60, 1.1 Formalism for syntactic description
- The Go Programming Language Specification, Notation
- Introduction, The Python Language Reference, 1.2 Notation
- RFC 5234, Augmented BNF for Syntax Specifications: ABNF, 1. Introduction
- if statement, cppreference.com, Explanation
- Direct-initialization, cppreference.com, Notes
- PEP 617, New PEG parser for CPython, Background on PEG parsers
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 C9V35Z Edit this page History Report an error Markdown