hat.peg

PEG Parser

Implementation of PEG parser as described in paper "Parsing Expression Grammars: A Recognition-Based Syntactic Foundation" (Bryan Ford, 2004). PEG's grammar itself can be defined by PEG grammar::

# Hierarchical syntax
Grammar    <- Spacing Definition+ EndOfFile
Definition <- Identifier LEFTARROW Expression
Expression <- Sequence (SLASH Sequence)*
Sequence   <- Prefix*
Prefix     <- (AND / NOT)? Suffix
Suffix     <- Primary (QUESTION / STAR / PLUS)?
Primary    <- Identifier !LEFTARROW
            / OPEN Expression CLOSE
            / Literal
            / Class
            / DOT

# Lexical syntax
Identifier <- IdentStart IdentCont* Spacing
IdentStart <- [a-zA-Z_]
IdentCont  <- IdentStart / [0-9]
Literal    <- ['] (!['] Char)* ['] Spacing
            / ["] (!["] Char)* ["] Spacing
Class      <- '[' (!']' Range)* ']' Spacing
Range      <- Char '-' Char / Char
Char       <- '\\' [nrt'"\[\]\\]
            / '\\' 'x' Hex Hex
            / '\\' 'u' Hex Hex Hex Hex
            / !'\\' .
Hex        <- [0-9a-fA-F]

LEFTARROW  <- '<-' Spacing
SLASH      <- '/' Spacing
AND        <- '&' Spacing
NOT        <- '!' Spacing
QUESTION   <- '?' Spacing
STAR       <- '*' Spacing
PLUS       <- '+' Spacing
OPEN       <- '(' Spacing
CLOSE      <- ')' Spacing
DOT        <- '.' Spacing

Spacing    <- (Space / Comment)*
Comment    <- '#' (!EndOfLine .)* (EndOfLine / EndOfFile)
Space      <- ' ' / '\t' / EndOfLine
EndOfLine  <- '\r\n' / '\n' / '\r'
EndOfFile  <- !.

Example usage of PEG parser::

import functools
import hat.peg

grammar = hat.peg.Grammar(r'''
    Expr    <- Sum
    Sum     <- Product (('+' / '-') Product)*
    Product <- Value (('*' / '/') Value)*
    Value   <- Spacing ([0-9]+ / '(' Expr ')') Spacing
    Spacing <- ' '*
''', 'Expr')

ast = grammar.parse('1 + 2 * 3 + (4 - 5) * 6 + 7')

result = hat.peg.walk_ast(ast, {
    'Expr': lambda n, c: c[0],
    'Sum': lambda n, c: functools.reduce(
        (lambda acc, x: acc + x[1] if x[0] == '+' else acc - x[1]),
        zip(c[1::2], c[2::2]),
        c[0]),
    'Product': lambda n, c: functools.reduce(
        (lambda acc, x: acc * x[1] if x[0] == '*' else acc / x[1]),
        zip(c[1::2], c[2::2]),
        c[0]),
    'Value': lambda n, c: (c[2] if c[1] == '(' else
                           int(''.join(c[1:-1])))})

assert result == 8
  1r"""PEG Parser
  2
  3Implementation of PEG parser as described in paper "Parsing Expression
  4Grammars: A Recognition-Based Syntactic Foundation" (Bryan Ford, 2004).
  5PEG's grammar itself can be defined by PEG grammar::
  6
  7    # Hierarchical syntax
  8    Grammar    <- Spacing Definition+ EndOfFile
  9    Definition <- Identifier LEFTARROW Expression
 10    Expression <- Sequence (SLASH Sequence)*
 11    Sequence   <- Prefix*
 12    Prefix     <- (AND / NOT)? Suffix
 13    Suffix     <- Primary (QUESTION / STAR / PLUS)?
 14    Primary    <- Identifier !LEFTARROW
 15                / OPEN Expression CLOSE
 16                / Literal
 17                / Class
 18                / DOT
 19
 20    # Lexical syntax
 21    Identifier <- IdentStart IdentCont* Spacing
 22    IdentStart <- [a-zA-Z_]
 23    IdentCont  <- IdentStart / [0-9]
 24    Literal    <- ['] (!['] Char)* ['] Spacing
 25                / ["] (!["] Char)* ["] Spacing
 26    Class      <- '[' (!']' Range)* ']' Spacing
 27    Range      <- Char '-' Char / Char
 28    Char       <- '\\' [nrt'"\[\]\\]
 29                / '\\' 'x' Hex Hex
 30                / '\\' 'u' Hex Hex Hex Hex
 31                / !'\\' .
 32    Hex        <- [0-9a-fA-F]
 33
 34    LEFTARROW  <- '<-' Spacing
 35    SLASH      <- '/' Spacing
 36    AND        <- '&' Spacing
 37    NOT        <- '!' Spacing
 38    QUESTION   <- '?' Spacing
 39    STAR       <- '*' Spacing
 40    PLUS       <- '+' Spacing
 41    OPEN       <- '(' Spacing
 42    CLOSE      <- ')' Spacing
 43    DOT        <- '.' Spacing
 44
 45    Spacing    <- (Space / Comment)*
 46    Comment    <- '#' (!EndOfLine .)* (EndOfLine / EndOfFile)
 47    Space      <- ' ' / '\t' / EndOfLine
 48    EndOfLine  <- '\r\n' / '\n' / '\r'
 49    EndOfFile  <- !.
 50
 51Example usage of PEG parser::
 52
 53    import functools
 54    import hat.peg
 55
 56    grammar = hat.peg.Grammar(r'''
 57        Expr    <- Sum
 58        Sum     <- Product (('+' / '-') Product)*
 59        Product <- Value (('*' / '/') Value)*
 60        Value   <- Spacing ([0-9]+ / '(' Expr ')') Spacing
 61        Spacing <- ' '*
 62    ''', 'Expr')
 63
 64    ast = grammar.parse('1 + 2 * 3 + (4 - 5) * 6 + 7')
 65
 66    result = hat.peg.walk_ast(ast, {
 67        'Expr': lambda n, c: c[0],
 68        'Sum': lambda n, c: functools.reduce(
 69            (lambda acc, x: acc + x[1] if x[0] == '+' else acc - x[1]),
 70            zip(c[1::2], c[2::2]),
 71            c[0]),
 72        'Product': lambda n, c: functools.reduce(
 73            (lambda acc, x: acc * x[1] if x[0] == '*' else acc / x[1]),
 74            zip(c[1::2], c[2::2]),
 75            c[0]),
 76        'Value': lambda n, c: (c[2] if c[1] == '(' else
 77                               int(''.join(c[1:-1])))})
 78
 79    assert result == 8
 80
 81"""
 82
 83from hat.peg.common import (Node,
 84                            Action,
 85                            CallFrame,
 86                            DebugState,
 87                            DebugCb,
 88                            walk_ast,
 89                            console_debug_cb)
 90from hat.peg.grammar import Grammar
 91
 92
 93__all__ = ['Node',
 94           'Action',
 95           'CallFrame',
 96           'DebugState',
 97           'DebugCb',
 98           'walk_ast',
 99           'console_debug_cb',
100           'Grammar']
class Node(typing.NamedTuple):
 6class Node(typing.NamedTuple):
 7    """Abstract syntax tree node.
 8
 9    Node names are identifiers of parser's definitions and values
10    are other nodes or string values representing matched `Literal`, `Class`
11    or `Dot` leaves.
12
13    """
14    name: str
15    value: Sequence[typing.Union['Node', str]]

Abstract syntax tree node.

Node names are identifiers of parser's definitions and values are other nodes or string values representing matched Literal, Class or Dot leaves.

Node(name: str, value: Sequence[ForwardRef('Node') | str])

Create new instance of Node(name, value)

name: str

Alias for field number 0

value: Sequence[Node | str]

Alias for field number 1

Action = collections.abc.Callable[[Node, collections.abc.Sequence], typing.Any]
class CallFrame(typing.NamedTuple):
22class CallFrame(typing.NamedTuple):
23    """Call frame"""
24    name: str
25    position: int

Call frame

CallFrame(name: str, position: int)

Create new instance of CallFrame(name, position)

name: str

Alias for field number 0

position: int

Alias for field number 1

class DebugState(typing.NamedTuple):
28class DebugState(typing.NamedTuple):
29    """Debug state"""
30    data: str
31    """input data"""
32    position: int
33    """current input data position"""
34    node: Node | None
35    """matched node or ``None`` if match failed"""
36    call_stack: Sequence[CallFrame]
37    """call stack"""

Debug state

DebugState( data: str, position: int, node: Node | None, call_stack: Sequence[CallFrame])

Create new instance of DebugState(data, position, node, call_stack)

data: str

input data

position: int

current input data position

node: Node | None

matched node or None if match failed

call_stack: Sequence[CallFrame]

call stack

DebugCb = collections.abc.Callable[[DebugState], None]
def walk_ast( node: Node, actions: dict[str, Callable[[Node, Sequence], typing.Any]], default_action: Callable[[Node, Sequence], Any] | None = None) -> Any:
44def walk_ast(node: Node,
45             actions: dict[str, Action],
46             default_action: Action | None = None
47             ) -> typing.Any:
48    """Simple depth-first abstract syntax tree walker.
49
50    Actions are key value pairs where keys represent node names and values
51    are callables that should be called for appropriate node. Each callable
52    receives matched node and list of results from recursively applying
53    this function on child nodes. For nodes which name doesn't match any
54    action, default action is used. If default action is not defined and node
55    name doesn't match action, result is None and recursion is stopped.
56
57    """
58    action = actions.get(node.name, default_action)
59    if not action:
60        return
61
62    children = [walk_ast(i, actions, default_action)
63                if isinstance(i, Node) else i
64                for i in node.value]
65
66    return action(node, children)

Simple depth-first abstract syntax tree walker.

Actions are key value pairs where keys represent node names and values are callables that should be called for appropriate node. Each callable receives matched node and list of results from recursively applying this function on child nodes. For nodes which name doesn't match any action, default action is used. If default action is not defined and node name doesn't match action, result is None and recursion is stopped.

def console_debug_cb(state: DebugState):
69def console_debug_cb(state: DebugState):
70    """Simple console debugger."""
71    success = '+++' if state.node else '---'
72    stack = ', '.join(frame.name for frame in reversed(state.call_stack))
73    position = state.call_stack[-1].position
74
75    print(success, stack)
76    print('<<<', state.data[position:state.position])
77    print('>>>', state.data[state.position:], flush=True)

Simple console debugger.

class Grammar:
20class Grammar:
21    """PEG Grammar.
22
23    If starting definition is not set, first definition is assumed.
24
25    Args:
26        grammar: grammar definitions
27        starting: starting definition name
28
29    """
30
31    def __init__(self,
32                 grammar: str,
33                 starting: str | None = None):
34        definitions = {}
35
36        ast = _meta_parser.parse(grammar)
37
38        for identifier, expression in common.walk_ast(ast, _meta_actions):
39            if identifier in definitions:
40                raise Exception(f'duplicate definition {identifier}')
41
42            if starting is None:
43                starting = identifier
44
45            definitions[identifier] = _reduce_expression(expression)
46
47        if starting not in definitions:
48            raise Exception(f'undefined starting identifier {starting}')
49
50        for expression in definitions.values():
51            for identifier in _get_identifiers(expression):
52                if identifier not in definitions:
53                    raise Exception(f'undefined identifier {identifier}')
54
55        self._parser = Parser(definitions=definitions,
56                              starting=starting)
57
58    def parse(self,
59              data: str,
60              debug_cb: common.DebugCb | None = None
61              ) -> common.Node:
62        """Parse input data.
63
64        `debug_cb` is optional function which can be used for monitoring and
65        debugging parse steps. It is called each time named definition
66        is successfully or unsuccessfully matched.
67
68        """
69        return self._parser.parse(data=data,
70                                  debug_cb=debug_cb)

PEG Grammar.

If starting definition is not set, first definition is assumed.

Arguments:
  • grammar: grammar definitions
  • starting: starting definition name
Grammar(grammar: str, starting: str | None = None)
31    def __init__(self,
32                 grammar: str,
33                 starting: str | None = None):
34        definitions = {}
35
36        ast = _meta_parser.parse(grammar)
37
38        for identifier, expression in common.walk_ast(ast, _meta_actions):
39            if identifier in definitions:
40                raise Exception(f'duplicate definition {identifier}')
41
42            if starting is None:
43                starting = identifier
44
45            definitions[identifier] = _reduce_expression(expression)
46
47        if starting not in definitions:
48            raise Exception(f'undefined starting identifier {starting}')
49
50        for expression in definitions.values():
51            for identifier in _get_identifiers(expression):
52                if identifier not in definitions:
53                    raise Exception(f'undefined identifier {identifier}')
54
55        self._parser = Parser(definitions=definitions,
56                              starting=starting)
def parse( self, data: str, debug_cb: Callable[[DebugState], None] | None = None) -> Node:
58    def parse(self,
59              data: str,
60              debug_cb: common.DebugCb | None = None
61              ) -> common.Node:
62        """Parse input data.
63
64        `debug_cb` is optional function which can be used for monitoring and
65        debugging parse steps. It is called each time named definition
66        is successfully or unsuccessfully matched.
67
68        """
69        return self._parser.parse(data=data,
70                                  debug_cb=debug_cb)

Parse input data.

debug_cb is optional function which can be used for monitoring and debugging parse steps. It is called each time named definition is successfully or unsuccessfully matched.