17 Parsing Expression Grammars

The pegs/ namespace matches Unicode text with parsing expression grammars (PEGs). A grammar can use recursive rules, captures, labels and ordinary DUST actions. It requires the stdlib plugin. Matching is not guaranteed to take linear time.

17.1. Compile, match and search

Signature Result
(pegs/compile pattern) An immutable compiled PEG
(pegs/match pattern text [start [options]]) A capture List, or null for no match
(pegs/find pattern text [start [options]]) The first matching start index, or null
(pegs/find-all pattern text [start [options]]) All matching start indices, including overlaps
(pegs/replace-first pattern text replacement [start [options]]) Replace the first match
(pegs/replace pattern text replacement [start [options]]) Replace non-overlapping matches
(pegs/compile-form form [env]) Compile pattern data with an optional bindings Map

The first six forms take unquoted pattern syntax. They are macros, and cannot be passed to apply. A pattern can refer to a local containing a compiled PEG or a character predicate. pegs/compile-form is an ordinary function. Its optional env Map has String keys naming PEG, predicate, or action bindings. It does not evaluate pattern data as DUST code. Keep action functions in env to keep their original lexical bindings.

Input must be a valid UTF-8 String. The optional start defaults to zero; null also selects zero. Otherwise it must be an integer from zero through the input's code-point count, inclusive. The optional options map comes last. Without options, or with null, the operation uses the default step budget. Its only option, steps, is a positive integer that sets the operation's step budget (see Values, errors and limits), as in (pegs/match p text null {steps 50000000}). Options must be null or a map. An unknown option or a steps value that is not a positive integer is an error. Indices count code points, not bytes. Line and column start at one. LF starts a new line, and CRLF is one line break. A match accepts a prefix. Add (end) to require the end of the active input window.

(let [p (pegs/compile "a")]
  (pegs/match (seq p "b" (end)) "ab"))
(pegs/match (seq #re "([a-z]+)" ":" ($ (+ chars/ascii-digit?)) (end)) "spice:42")
(pegs/match (seq (position) 1 (line) (column)) "α\r\nβ" 3)

Results, in order:

[]
["spice" "42"]
[3 2 2]
(let [suffix "!"
      action (fn [text] (str text suffix))
      p (pegs/compile-form `(call ($ (+ chars/word?)) action) {action action})]
  (pegs/match p "spice"))
(pegs/match #peg (seq "a" ($ "b")) "ab")

Results, in order:

["spice!"]
["b"]

Search includes the boundary at the end of the input. find-all resumes one code point after each match's start, so matches can overlap. Replacements resume at the end of a consuming match. After an empty replacement, search advances one code point and preserves that input character. An empty match at the end is processed once.

A replacement is a String or a function. The function receives captures as positional arguments. With no captures, it receives the whole matched text. Its result must be a String. The prefix before start remains unchanged. No match leaves the input unchanged.

(pegs/find (end) "abc")
(pegs/find-all "" "ab")
(pegs/replace "" "ab" "-")
(pegs/find-all "aa" "aaa")
(pegs/replace "aa" "aaa" "X")
(pegs/replace-first "a" "aaa" "X")
(pegs/replace ($ (+ chars/ascii-digit?)) "a12b34" (fn [n] (str "[" n "]")))

Results, in order:

3
[0 1 2]
"-a-b-"
[0 1]
"Xa"
"Xaa"
"a[12]b[34]"

17.2. Patterns and rule names

A String matches literal text. A nonnegative integer consumes that many code points. true succeeds empty, and false fails. A grammar Map requires a main rule. Rules can refer forward and call each other recursively. Compilation rejects recursion that can repeat without consuming input, including cycles through lookahead or nullable external PEGs.

A bare name selects a rule in the nearest enclosing grammar, then an outer grammar, then a captured compiled PEG or function. A referenced rule name must not also name a lexical binding. Quote literal text: "word" matches text, and word refers to a rule or binding.

A function in pattern position is a consuming character predicate. It receives one code point as a String; true consumes it and false fails. A non-Boolean result is a Type_Mismatch. At end of input the predicate is not called. Use a named function such as chars/letter?, a lexical function binding, or an inline (fn [c] ( c "a"))=. The chars/ predicates accept one String that contains exactly one code point and return a Boolean. They are also schemas. In a pattern, write the name without the call, such as chars/letter?.

Signature Matches
(chars/letter? c) One Unicode letter
(chars/word? c) One Unicode letter or decimal digit
(chars/space? c) One Unicode whitespace code point
(chars/ascii-letter? c) One ASCII letter
(chars/ascii-word? c) One ASCII letter or decimal digit
(chars/ascii-space? c) One ASCII whitespace character
(chars/ascii-digit? c) One ASCII decimal digit
(chars/hex? c) One ASCII hexadecimal digit
pegs/newline CRLF or LF
pegs/line-end Newline or end of the active window

The reusable PEG values contain ordinary patterns. Outside pattern syntax, read them as :pegs/newline and :pegs/line-end, like other builtin constants.

Operators are recognized only in invocation heads. Label names and error tags are literal names, not variable lookups. A List pattern must have the form [name "<-" p].

17.3. Operators

Here, p and q are patterns. Bounds and capture indices are literal nonnegative integers. Unknown operators and incorrect arities are errors.

Operator Behavior
(seq p*) Match in order; an empty sequence succeeds
(or p*) Select the first success; an empty choice fails
(repeat p min max) Greedy repetition; null maximum means unbounded
(opt p), (? p) Repeat zero or one time
(any p), (* p) Repeat zero or more times
(some p), (+ p) Repeat one or more times
(not p) Require failure, consume nothing, discard captures and labels
(look p) Require success, consume nothing, keep captures and labels
(end) Require the end of the active window
(set "chars") Consume one member code point
(range "az" "AZ" ...) Consume one code point in any inclusive pair
(to p) Consume up to the first match; discard its captures and labels
(thru p) Consume through the first match; keep its captures and labels
(within p window) Match window, then run p inside it; consume the whole window
(split p separator) Run p in each segment, keeping its captures; consume the window
(sep-by p separator) Match p followed by zero or more separator p pairs
(capture p), ($ p) Append consumed text after p's captures
(group p) Replace p's captures with one List, including an empty List
(drop p) Remove captures, keeping labels
(join p) Concatenate captures' str representations into one String
(nth p index) Keep capture index; a missing capture fails
(number p [base]) Parse consumed text into one number; invalid text fails
(position), (line), (column) Append the absolute input coordinate
(label p name), [name "<-" p] Require exactly one capture and bind its name
(backref name) Append the bound capture without consuming
(backmatch name) Match the bound String at the current position
(call p [params] body*), (call p f) Replace captures with one action result
(check p [params] body*), (check p f) As call; false, null or an ordinary error result fails
(error [p [tags]]) Abort the PEG call with an error when p matches

Each range String contains exactly two ordered code points. number defaults to base 10 and accepts DUST integer/float spelling. Other bases, from 2 through 36, accept signed integers. The whole consumed text must parse without overflow.

to and thru try every boundary, including the window's end. A successful thru executes its pattern once. within discards window captures and labels. Its inner pattern need not consume the whole window unless it uses end. split includes empty and trailing segments and discards separator captures and labels. An empty separator match is an invalid-PEG error. Each separator is found once per boundary. All coordinates remain relative to the original input.

17.4. Captures, actions and backtracking

A match returns a List even when it captures nothing. False, null and ordinary error values can be captured data. nth selects a capture, not an element inside a captured List. An unset backreference fails. A label bound to false or null is set. backmatch requires a String label.

A failed branch restores the input position, captures and labels. Ordered choice does not reopen a successful alternative after a later failure. Repetition does not give back successful iterations. An unbounded repetition undoes an empty attempt and stops without counting it. Finite repetition can count empty successes up to its bound.

(pegs/match (or (seq ($ "a") "x") ($ "ab")) "ab")
(pegs/match (seq (or "a" "ab") "c") "abc")
(pegs/match (seq (any "a") "a") "aaa")
(pegs/match (any ($ "")) "")
(pegs/match (some ($ "")) "")
(pegs/match (group "a") "a")
(pegs/match (nth (group (seq ($ "a") ($ "b"))) 1) "ab")
(pegs/match (nth (seq ($ "a") ($ "b")) 1) "ab")

Results, in order:

["ab"]
null
null
[]
null
[[]]
null
["b"]

Each rule or compiled-PEG call has a fresh label frame. A nested rule cannot overwrite its caller's labels. Label a nested call to export its single result. Duplicate syntactic label definitions in one frame are invalid. Repetition of one definition keeps its last successful binding.

Inline actions can read labels introduced by their pattern. These labels shadow outer locals. An optional label that was not bound supplies null. Positional parameters support ordinary function destructuring, _ and .... A name cannot occur in both positional parameters and implicit labels.

Label-only actions can omit parameters: (call p body*). A sole Local/Const reference, Function value or (fn ...) expression instead selects the function form. Use explicit [] to make a bare label reference an inline body. An empty parameter List ignores positional captures. The function form receives positional captures under ordinary function arity rules.

Actions execute immediately. Backtracking does not undo their mutations, transactions or I/O. Another attempted branch can execute an action again. Compilation never executes actions. Cancellation and exhausted budgets propagate through or, not and check.

(let [seen []]
  [(pegs/match (or (seq (call "a" [] (lists/append seen 1)) "x") "ab") "ab")
   seen])
(pegs/match (call (seq ($ "a") ($ "b")) [first ... rest] [first rest]) "ab")
(pegs/match (nth (call "" [] false) 0) "")
(pegs/match (nth (call "" [] null) 0) "")

Results, in order:

[[] [1]]
[["a" ["b"]]]
[false]
[null]
(pegs/match
  {main node
   node (check
          (seq "<" [tag "<-" ($ (+ chars/word?))] ">"
               [children "<-" (group (* node))]
               "</" [close "<-" ($ (+ chars/word?))] ">")
          (when (= tag close) {tag tag children children}))}
  "<a><b></b></a>")

Results, in order:

[{tag "a" children [{tag "b" children []}]}]

A regex leaf matches at the current position using the native regex engine. It appends numbered groups 1 through N, excluding group zero. Unmatched groups append null. Named groups keep numeric slots and do not define PEG labels. A successful regex is atomic. Later failure cannot request another match length. Anchors see the active window, not a suffix beginning at each search candidate.

17.5. Comments and source data

DUST semicolon comments in patterns and actions are source annotations. They do not affect operands, validation, matching or compiled-code cache keys. Authored namespace source keeps its comments and source spans through save/load. Canonical PEG values and evaluated results do not keep authored comments.

#mute removal happens before arity and name checks. A muted required root is an error. Comments in subject text are ordinary input. The grammar must explicitly recognize or skip them.

(pegs/match (seq "a" ; annotation, not an operand
                #mute (unknown ignored)
                "b") "ab")
(pegs/match ($ (seq ";" (to pegs/line-end))) "; keep me")

Results, in order:

[]
["; keep me"]
; A Fluent message subset: comments, identifiers and plain-text values.
; This grammar does not implement Fluent expressions or its resolver.
(pegs/match
  {main (seq (* (or (drop comment) message)) (end))
   horizontal-space (set " \t")
   comment (seq "#" (to pegs/line-end) pegs/line-end)
   message (call
             (seq [id "<-" ($ (seq chars/ascii-letter? (* (or chars/ascii-word? "-"))))]
                  (* horizontal-space) "=" (* horizontal-space)
                  [value "<-" ($ (to pegs/line-end))] pegs/line-end)
             {id id value value})}
  "# Greeting\nhello-user = Hello, traveler!\nfarewell = Goodbye")

Results, in order:

[{id "hello-user" value "Hello, traveler!"} {id "farewell" value "Goodbye"}]

17.6. Values, errors and limits

A #peg pattern value contains one pattern form. Quoting or decoding preserves that source without executing it. Materialization requires stdlib. Closed PEGs serialize with normalized source through all document codecs and can be used in another runtime. Referenced closed PEGs are included in that source. A PEG with live lexical action bindings works in its runtime, but serialization reports the existing unrepresentable-function error. Compiled PEGs compare by identity. Rebinding an outer local does not replace an already captured value. Mutable captured values keep their ordinary aliases.

Invalid patterns report <invalid peg> with a message and pattern-path. The path contains rule names and zero-based operand indices. Action errors retain their ordinary classifications and DUST source positions.

The error operator defaults to true. Its last String capture supplies the message, or the message is PEG match failed. Its error has peg and the literal tags, plus input-index, input-line and input-column at the operator's entry position. These subject coordinates are separate from DUST position. Tags cannot use diagnostic field names: message, input-index, input-line, input-column, position, code or value. The error aborts the PEG operation and returns ordinary #err data to DUST.

Compilation limits source nodes to 1,000,000. It has no work limit and no depth limit, and a grammar can have any number of rules: the evaluation's CPU and memory budgets bound compilation. One PEG operation has a step budget, by default 10,000,000 steps, shared across input preparation, dispatch, search and native regex visits. It is a work bound: it ends a pattern that runs away, even with unlimited CPU time. Past it, the operation fails with a Resource_Limit error that names the budget. The steps option sets another budget for one operation. Nested PEG callbacks share the remaining steps of the operation that called them, and their own steps option has no effect. Rule calls nest to any depth: the step budget and the memory budget bound them. Captures, checkpoints and find-all results have no count limit; the runtime memory budget bounds them. Runtime memory limits include stacks, caches and native scratch. Compilation and matching observe cancellation. The runtime remains reusable after a limit or cancellation. Compiled code caching is limited to 64 entries per runtime.