TatSu: PEG Parser Generator

5.18.0 · active · verified Sun Apr 12

TatSu is a Python library that takes a grammar defined in a variation of EBNF (Extended Backus–Naur Form) and generates a memoizing PEG (Parsing Expression Grammar) / Packrat parser. It is actively maintained with frequent minor releases, providing a powerful tool for creating custom parsers and Abstract Syntax Trees (ASTs). The current version is 5.18.0.

Warnings

Install

Imports

Quickstart

This quickstart defines a simple calculator grammar and uses `tatsu.parse` to directly parse an input string, producing an Abstract Syntax Tree (AST). For complex parsing logic or evaluation, a custom 'semantics' class is typically passed to the parse function.

from tatsu import parse

grammar = r'''
    @@grammar::Calc
    start: expression $ ;
    expression: term (('+' | '-') term)* ;
    term: factor (('*' | '/') factor)* ;
    factor: NUMBER | '(' expression ')' ;
    NUMBER: /\d+/ ;
'''

input_text = '1 + 2 * (3 - 4)'

try:
    # Parse the input using the grammar
    ast = parse(grammar, input_text)
    print(f'Input: {input_text}')
    print(f'AST: {ast}')

    # Example with a simple calculation (requires a semantics class for evaluation)
    # For a full calculation example, typically a semantics class is used.
    # For this quickstart, we just show the parsing to AST.
except Exception as e:
    print(f'Error parsing: {e}')

view raw JSON →