Guide: Expressions with precedence
Build an arithmetic expression parser producing an AST that respects operator precedence and associativity.
Source: examples/better_errors/main.ml.
Goal:
1+2*3parses as1 + (2 * 3)(1+2)*3parses as(1 + 2) * 31+2+3parses as(1 + 2) + 3
The AST
type expr = | Num of int | Add of expr * expr | Mul of expr * exprRecursive-descent levels
Split the grammar into one function per precedence tier, lowest precedence at the entry point and highest near the leaves:
expr = term (('+' term)*) <- lowest precedenceterm = factor (('*' factor)*) <- higher precedencefactor = number | '(' expr ')' <- atoms and groupinglet rec expr () = let left = term () in let rest = Parseff.many (fun () -> Parseff.skip_whitespace (); let _ = Parseff.expect "a '+' operator" (fun () -> Parseff.char '+') in Parseff.skip_whitespace (); term ()) in List.fold_left (fun acc t -> Add (acc, t)) left rest
and term () = let left = factor () in let rest = Parseff.many (fun () -> Parseff.skip_whitespace (); let _ = Parseff.expect "a '*' operator" (fun () -> Parseff.char '*') in Parseff.skip_whitespace (); factor ()) in List.fold_left (fun acc f -> Mul (acc, f)) left rest
and factor () = Parseff.skip_whitespace (); Parseff.or_ (fun () -> let _ = Parseff.expect "an opening parenthesis" (fun () -> Parseff.char '(') in Parseff.skip_whitespace (); let e = Parseff.rec_ expr in Parseff.skip_whitespace (); let _ = Parseff.expect "a closing parenthesis" (fun () -> Parseff.char ')') in e) (fun () -> let d = Parseff.expect "a number" Parseff.digit in Num (Char.code d - Char.code '0'))Because expr delegates each operand to term, * binds tighter than +. On "1+2*3", term parses 1, expr consumes +, and the second term consumes 2*3 into Mul (Num 2, Num 3) before returning to expr.
With expect, error messages use grammar names instead of raw tokens:
"1+x":expected a number or an opening parenthesis(instead ofexpected digit or '(')"(1+2x":expected a '*' operator, a '+' operator, or a closing parenthesis(instead ofexpected ')', '*', or '+')
Shorter chains with fold_left
Parseff.fold_left replaces the many + List.fold_left boilerplate (use Parseff.fold_right for right-associative operators like ^):
let rec expr () = Parseff.fold_left term (fun () -> Parseff.skip_whitespace (); let _ = Parseff.char '+' in Parseff.skip_whitespace (); fun a b -> Add (a, b))
and term () = Parseff.fold_left factor (fun () -> Parseff.skip_whitespace (); let _ = Parseff.char '*' in Parseff.skip_whitespace (); fun a b -> Mul (a, b))
and factor () = Parseff.skip_whitespace (); Parseff.or_ (fun () -> let _ = Parseff.char '(' in let e = Parseff.rec_ expr in Parseff.skip_whitespace (); let _ = Parseff.char ')' in e) (fun () -> Num (Char.code (Parseff.digit ()) - Char.code '0'))Operator tables: expression
Parseff.expression builds all levels from a single precedence table ordered from lowest to highest precedence, supporting Parseff.infix_left, Parseff.infix_right, Parseff.prefix, and Parseff.postfix:
let add () = Parseff.skip_whitespace (); let _ = Parseff.expect "a '+' operator" (fun () -> Parseff.char '+') in fun a b -> Add (a, b)
let mul () = Parseff.skip_whitespace (); let _ = Parseff.expect "a '*' operator" (fun () -> Parseff.char '*') in fun a b -> Mul (a, b)
let table = [ [ Parseff.infix_left add ]; [ Parseff.infix_left mul ] ]
let rec expr () = Parseff.expression ~operand:factor table
and factor () = Parseff.skip_whitespace (); Parseff.or_ (fun () -> let _ = Parseff.expect "an opening parenthesis" (fun () -> Parseff.char '(') in Parseff.skip_whitespace (); let e = Parseff.rec_ expr in Parseff.skip_whitespace (); let _ = Parseff.expect "a closing parenthesis" (fun () -> Parseff.char ')') in e) (fun () -> let d = Parseff.expect "a number" Parseff.digit in Num (Char.code d - Char.code '0'))If an operator token parser or its right operand fails, expression tries the next operator (so < can precede <<). Because postfix operators have no right operand, list longer postfix tokens before shorter prefixes (e.g. != before !).
Single-lookup dispatch: precedence
For grammars with many precedence levels that can dispatch from Parseff.peek_char or a lexer token, Parseff.precedence avoids scanning a table after every operand:
let operator () = Parseff.skip_whitespace (); match Parseff.peek_char () with | Some '+' -> Some (1, Parseff.infix_left add) | Some '*' -> Some (2, Parseff.infix_left mul) | _ -> None
let rec expr () = Parseff.precedence ~operator factor
and factor () = Parseff.skip_whitespace (); Parseff.or_ (fun () -> let _ = Parseff.char '(' in let e = Parseff.rec_ expr in Parseff.skip_whitespace (); let _ = Parseff.char ')' in e) (fun () -> Num (Char.code (Parseff.digit ()) - Char.code '0'))precedence accepts only infix and postfix operators. Parse prefix operators inside operand by calling Parseff.precedence ~min inside Parseff.rec_. Passing a prefix operator in ~operator is a compile-time type error:
# let negate () = Some (3, Parseff.prefix (fun () e -> Mul (Num (-1), e))) in Parseff.precedence ~operator:negate factor;;Line 2, characters 32-38:Error: The value negate has type unit -> (int * (expr, [> `Prefix ]) Parseff.operator) option but an expression was expected of type unit -> (int * (expr, [< `Infix | `Postfix ]) Parseff.operator) option The second variant type does not allow tag(s) `PrefixError recovery
To collect multiple errors in an expression rather than stopping at the first, see An expression that recovers.
Printing the AST
let rec expr_to_string = function | Num n -> string_of_int n | Add (l, r) -> Printf.sprintf "(%s + %s)" (expr_to_string l) (expr_to_string r) | Mul (l, r) -> Printf.sprintf "(%s * %s)" (expr_to_string l) (expr_to_string r)