fpeg 0.1.0

A PEG parsing library: grammars loaded at runtime, a bytecode parsing machine and a lossless parse tree
Documentation
// SPDX-FileCopyrightText: 2026 Dominik Schwimmbeck
// SPDX-License-Identifier: MIT OR Apache-2.0

// Python 3.15, scannerless. Blocks follow columns, brackets join lines, a backslash continues
// a line, and f-strings and t-strings nest inside replacement fields, with any quotes inside
// them. Hard keywords are reserved, soft keywords stay names. Some texts that CPython refuses
// parse, which the page of known limits lists: indentation that mixes tabs and spaces where
// Python finds it ambiguous, targets of assignments, deletions, loops and with items that are
// any primary expression, and a few forms CPython refuses with a message of its own.
//
// Starred items and comprehension clauses call the levels of the expression block that Python
// takes there.

// In a replacement field, outside any bracket in it, a colon starts the format. Format specs
// count how deeply they nest within one f-string or t-string, and a triple-quoted one lets
// them hold line breaks.
%flag bracket replacement spec nested_spec long_string
%word [\p{XID_Continue}]
%keywords soft "match" "case" "_" "type" "lazy"
%ignore [ \t\x0C]+ | COMMENT | "\\" _LINE_BREAK &. | %if(bracket) _LINE_BREAK

start: _BLANK_LINES? statements=_line*
// A line of a block: a statement at the block's column, else an error, where a statement must
// stand or where a line is indented with no block to open.
_line: %same statement | %same &. (!() ^ statement) | %indent(&. (!() ^ indented))

?statement: compound | simple_statements
simple_statements: items=(simple ++ ";") ";"? ((_NEWLINE | !.) ^ newline)
?simple: assignment
       | type_alias
       | return
       | import_name
       | import_from
       | raise
       | pass
       | del
       | yield_statement
       | assert
       | break
       | continue
       | global
       | nonlocal
       | expression_statement

?assignment: target=single_target ":" annotation=expression ("=" value=annotated_value)? -> annotated_assign
           | (targets=star_targets "=" !"=")+ value=annotated_value -> assign
           | target=single_target op=AUGMENTED value=annotated_value -> augmented_assign
?annotated_value: yield_expression | star_expressions
type_alias: "type" name=NAME params=type_params? "=" value=expression
return: "return" value=star_expressions?
raise: "raise" (exception=expression ("from" cause=expression)?)?
pass: "pass"
break: "break"
continue: "continue"
del: "del" targets=star_targets
yield_statement: value=yield_expression
assert: "assert" test=expression ("," message=expression)?
global: "global" names=(NAME ++ ",")
nonlocal: "nonlocal" names=(NAME ++ ",")
expression_statement: value=star_expressions

import_name: lazy="lazy"? "import" names=(dotted_as_name ++ ",")
dotted_as_name: name=dotted_name ("as" alias=NAME)?
dotted_name: parts=(NAME ++ ".")
import_from: lazy="lazy"? "from" (levels=("..." | ".")* module=dotted_name | levels=("..." | ".")+) "import" names=import_names
?import_names: "*" -> import_all
             | "(" %on(bracket, items=(import_as_name ++ ",") ","? ")") -> import_list
             | items=(import_as_name ++ ",") -> import_list
import_as_name: name=NAME ("as" alias=NAME)?

?compound: function_def
         | if
         | class_def
         | with
         | for
         | try
         | while
         | match
         | decorated

?block: indented_block | simple_statements
indented_block: _NEWLINE (%indent(statements=_line+) ^ indent)

decorated: decorators=(decorator %same)+ definition=(function_def | class_def)
decorator: "@" value=named_expression _NEWLINE
function_def: async="async"? "def" name=NAME params=type_params? "(" %on(bracket, parameters=parameters? ")") ("->" returns=expression)? (":" ^ colon) body=block
class_def: "class" name=NAME params=type_params? ("(" %on(bracket, bases=arguments? ")"))? (":" ^ colon) body=block
if: "if" test=named_expression (":" ^ colon) body=block branches=(%same elif)* (%same "else" (":" ^ colon) orelse=block)?
elif: "elif" test=named_expression (":" ^ colon) body=block
while: "while" test=named_expression (":" ^ colon) body=block (%same "else" (":" ^ colon) orelse=block)?
for: async="async"? "for" targets=star_targets "in" iter=star_expressions (":" ^ colon) body=block (%same "else" (":" ^ colon) orelse=block)?
with: async="async"? "with" items=with_items (":" ^ colon) body=block
?with_items: "(" %on(bracket, items=(with_item ++ ",") ","? ")") &":" -> with_list
           | items=(with_item ++ ",") -> with_list
with_item: context=expression ("as" target=star_target)?
try: "try" (":" ^ colon) body=block (
        (handlers=(%same except)+ | handlers=(%same except_star)+)
            (%same "else" (":" ^ colon) orelse=block)? (%same "finally" (":" ^ colon) final=block)?
        | %same "finally" (":" ^ colon) final=block)
except: "except" !"*" (types=expression "as" name=NAME | types=expressions)? (":" ^ colon) body=block
except_star: "except" "*" (types=expression "as" name=NAME | types=expressions) (":" ^ colon) body=block

match: "match" subject=subject ":" _NEWLINE %indent(cases=(%same case)+)
?subject: items=star_named_expression "," (items=(star_named_expression ++ ",") ","?)? -> tuple_expression
        | named_expression
case: "case" pattern=patterns ("if" guard=named_expression)? ":" body=block

?patterns: items=maybe_star_pattern "," (items=(maybe_star_pattern ++ ",") ","?)? -> sequence_pattern
         | pattern
?pattern: pattern=or_pattern "as" !"_" target=NAME -> as_pattern
        | or_pattern
?or_pattern: alternatives=closed_pattern ("|" alternatives=closed_pattern)+ -> or_pattern
           | closed_pattern
// In CPython's order, so that _ is a wildcard before it could start a value or class pattern.
?closed_pattern: literal_pattern
               | capture_pattern
               | wildcard_pattern
               | value_pattern
               | group_pattern
               | sequence_pattern
               | mapping_pattern
               | class_pattern
literal_pattern: value=(complex_number | signed_number | strings | "None" | "True" | "False")
// The first part of a complex literal is real and the second imaginary.
complex_number: !(("+" | "-")? IMAGINARY_NUMBER) real=signed_number op=("+" | "-") &IMAGINARY_NUMBER imaginary=NUMBER
signed_number: sign=("+" | "-")? number=NUMBER
class_pattern: class=pattern_name "(" %on(bracket, _class_arguments)
// Positional patterns come before keyword patterns. As in CPython, each order is tried whole,
// so a wildcard taken as positional before a keyword pattern makes the pattern fail.
_class_arguments: arguments=(pattern ++ ",") ","? ")"
                | arguments=(keyword_pattern ++ ",") ","? ")"
                | arguments=(pattern ++ ",") "," arguments=(keyword_pattern ++ ",") ","? ")"
                | ")"
keyword_pattern: name=NAME "=" pattern=pattern
value_pattern: parts=NAME ("." parts=NAME)+ !"("
wildcard_pattern: "_"
capture_pattern: !"_" name=NAME !("." | "(" | "=")
group_pattern: "(" %on(bracket, pattern=pattern ")")
sequence_pattern: "[" %on(bracket, (items=(maybe_star_pattern ++ ",") ","?)? "]")
                | "(" %on(bracket, (items=maybe_star_pattern "," (items=(maybe_star_pattern ++ ",") ","?)?)? ")")
?maybe_star_pattern: "*" target=NAME -> star_pattern
                   | pattern
mapping_pattern: "{" %on(bracket, ((items=(key_pattern ++ ",") ("," items=double_star_pattern)? | items=double_star_pattern) ","?)? "}")
key_pattern: key=(literal_pattern | value_pattern) ":" pattern=pattern
double_star_pattern: "**" !"_" target=NAME
pattern_name: parts=(NAME ++ ".")

parameters: _parameters<parameter, default_parameter, star_parameter, double_star_parameter>
lambda_parameters: _parameters<lambda_parameter, lambda_default, lambda_star, lambda_double_star>
// Parameters without a default come before those with one, and "/" may follow any of them.
// Then come "*" with or without a name, the keyword-only parameters, at least one after a
// bare "*", and "**".
_parameters<plain, defaulted, star, double_star>: (_positional<plain, defaulted> ("," _starred<plain, defaulted, star, double_star>)? | _starred<plain, defaulted, star, double_star>) ","?
_positional<plain, defaulted>: (items=(plain ++ ",") ",")? items=(defaulted ++ ",") ("," items=positional_only ("," items=(defaulted ++ ","))?)?
                             | items=(plain ++ ",") ("," items=positional_only ("," items=(plain ++ ","))?)? ("," items=(defaulted ++ ","))?
_starred<plain, defaulted, star, double_star>: items=star ("," items=((defaulted | plain) ++ ","))? ("," items=double_star)?
                                             | items=bare_star "," items=((defaulted | plain) ++ ",") ("," items=double_star)?
                                             | items=double_star
positional_only: "/"
bare_star: "*" -> var_positional
parameter: name=NAME (":" annotation=expression)? !"="
default_parameter: name=NAME (":" annotation=expression)? "=" default=expression -> parameter
star_parameter: "*" name=NAME (":" annotation=star_annotation)? -> var_positional
?star_annotation: "*" value=bitor -> starred
                | expression
double_star_parameter: "**" name=NAME (":" annotation=expression)? -> var_keyword
lambda_parameter: name=NAME !"=" -> parameter
lambda_default: name=NAME "=" default=expression -> parameter
lambda_star: "*" name=NAME -> var_positional
lambda_double_star: "**" name=NAME -> var_keyword
type_params: "[" %on(bracket, items=(type_param ++ ",") ","? "]")
?type_param: "**" name=NAME ("=" default=expression)? -> param_spec
           | "*" name=NAME ("=" default=star_expression)? -> type_var_tuple
           | name=NAME (":" bound=expression)? ("=" default=expression)? -> type_var
arguments: (items=(positional_argument ++ ",") ("," _keyword_arguments)? | _keyword_arguments) ","?
_keyword_arguments: items=(keyword_or_starred ++ ",") ("," items=(keyword_or_double_starred ++ ","))?
                  | items=(keyword_or_double_starred ++ ",")
?positional_argument: "*" value=expression -> starred
                    | named_expression !"="
?keyword_or_starred: keyword
                   | "*" value=expression -> starred
?keyword_or_double_starred: keyword
                          | "**" value=expression -> double_starred
keyword: name=NAME "=" !"=" value=expression

?star_expressions: items=star_expression "," (items=(star_expression ++ ",") ","?)? -> tuple_expression
                 | star_expression
?star_expression: "*" value=bitor -> starred
                | expression
?star_named_expression: "*" value=bitor -> starred
                      | named_expression
?named_expression: target=NAME ":=" value=expression -> named_expression
                 | expression !":="
?expressions: items=expression "," (items=(expression ++ ",") ","?)? -> tuple_expression
            | expression
yield_expression: "yield" "from" value=expression -> yield_from
                | "yield" value=star_expressions? -> yield

expression: %precedence {
    lambda: %if(!replacement) "lambda" parameters=lambda_parameters? ":" body=lambda -> lambda
        | body=or "if" test=or "else" orelse=lambda -> if_expression
    or: values=and ("or" values=and)+ -> bool_or
    and: values=not ("and" values=not)+ -> bool_and
    not: "not" operand=not -> not
    compare: left=bitor (operators=compare_operator comparators=bitor)+ -> compare
    bitor: left=bitor op="|" right=bitxor -> binary
    bitxor: left=bitxor op="^" right=bitand -> binary
    bitand: left=bitand op="&" right=shift -> binary
    shift: left=shift op=("<<" | ">>") right=sum -> binary
    sum: left=sum op=("+" | "-") right=product -> binary
    product: left=product op=("*" | "//" | "/" | "%" | "@") right=unary -> binary
    unary: op=("+" | "-" | "~") operand=unary -> unary
    power: base=await_primary op="**" exponent=unary -> binary
    operand: await_primary
}
?compare_operator: "not" "in" -> not_in
                 | "is" "not" -> is_not
                 | op=("==" | "!=" | "<=" | ">=" | "<" | ">" | "in" | "is") -> operator
?await_primary: "await" value=primary -> await
              | primary

// An assignment tries a primary as its target, and an expression statement the same primary
// again when the assignment fails, which the default memo does not see through the rules between.
@memo
?primary: func=primary arguments=generator_expression -> call
        | func=primary "(" %on(bracket, %off(replacement, arguments=arguments? ")")) -> call
        | value=primary "[" %on(bracket, %off(replacement, slices=slices "]")) -> subscript
        | value=primary "." attribute=NAME -> attribute
        | atom

?atom: strings
     | "True" -> true
     | "False" -> false
     | "None" -> none
     | NAME
     | NUMBER
     | tuple
     | generator_expression
     | group
     | list
     | list_comprehension
     | dict
     | set
     | dict_comprehension
     | set_comprehension
     | "..." -> ellipsis

tuple: "(" %on(bracket, %off(replacement, (items=star_named_expression "," (items=(star_named_expression ++ ",") ","?)?)? ")"))
group: "(" %on(bracket, %off(replacement, value=(yield_expression | named_expression) ")"))
// A generator unpacks any expression, where list and set comprehensions take the bitor level.
generator_expression: "(" %on(bracket, %off(replacement, element=generator_element clauses=comprehension ")"))
?generator_element: "*" value=expression -> starred
                  | named_expression
list: "[" %on(bracket, %off(replacement, (items=(star_named_expression ++ ",") ","?)? "]"))
list_comprehension: "[" %on(bracket, %off(replacement, element=star_named_expression clauses=comprehension "]"))
dict: "{" %on(bracket, %off(replacement, (items=(dict_item ++ ",") ","?)? "}"))
?dict_item: "**" value=bitor -> double_starred
          | key=expression ":" value=expression -> pair
set: "{" %on(bracket, %off(replacement, items=(star_named_expression ++ ",") ","? "}"))
dict_comprehension: "{" %on(bracket, %off(replacement, (key=expression ":" value=expression | element=double_starred) clauses=comprehension "}"))
// In a comprehension "**" takes any expression, in a dict display the bitor level.
double_starred: "**" value=expression
set_comprehension: "{" %on(bracket, %off(replacement, element=star_named_expression clauses=comprehension "}"))
comprehension: clauses=for_if+
for_if: async="async"? "for" targets=star_targets "in" iter=or conditions=("if" or)*

slices: items=(slice ++ ",") ","?
?slice: lower=expression? ":" !"=" upper=expression? (":" step=expression?)? -> slice
      | "*" value=expression -> starred
      | named_expression

?star_targets: items=star_target "," (items=(star_target ++ ",") ","?)? -> tuple_expression
             | star_target
?star_target: "*" !"*" value=star_target -> starred
            | primary
?single_target: primary

// Bytes, template strings and the other strings each concatenate only with their own kind.
strings: parts=BYTES+
       | parts=fstring<T_RAW_PREFIX, T_PREFIX>+
       | parts=(fstring<F_RAW_PREFIX, F_PREFIX> | STRING)+

@lexical
fstring<raw, plain>: prefix=raw (
        %on(long_string, _f_body<"\"\"\"", _LINE_BREAK, F_RAW_ESCAPE> | _f_body<"'''", _LINE_BREAK, F_RAW_ESCAPE>)
        | %off(long_string, !"\"\"\"" _f_body<"\"", NEVER, F_RAW_ESCAPE> | !"'''" _f_body<"'", NEVER, F_RAW_ESCAPE>))
    | prefix=plain (
        %on(long_string, _f_body<"\"\"\"", _LINE_BREAK, F_ESCAPE> | _f_body<"'''", _LINE_BREAK, F_ESCAPE>)
        | %off(long_string, !"\"\"\"" _f_body<"\"", NEVER, F_ESCAPE> | !"'''" _f_body<"'", NEVER, F_ESCAPE>))

@lexical
_f_body<quote, line_break, escape>: quote %off(bracket, %off(spec, %off(nested_spec, parts=(F_TEXT<quote, line_break, escape> | replacement_field<quote, escape>)*))) quote

// After a format spec the closing brace follows it directly, with no line break skipped. The
// quote that closes the string ends a format spec too.
replacement_field<quote, escape>: "{" %on(bracket, value=%on(replacement, yield_expression | star_expressions) debug="="? conversion=conversion? (format=format_spec<quote, escape> %off(bracket, "}") | "}"))

@lexical
conversion: "!" name=CONVERSION

// A replacement field may stand in two nested format specs at most.
@lexical
format_spec<quote, escape>: ":" %off(bracket, %if(nested_spec) parts=F_SPEC_TEXT<quote, escape>*
                                     | %if(spec) %on(nested_spec, parts=(F_SPEC_TEXT<quote, escape> | replacement_field<quote, escape>)*)
                                     | %on(spec, parts=(F_SPEC_TEXT<quote, escape> | replacement_field<quote, escape>)*))

F_TEXT<quote, line_break, escape> "text": (!quote ([^{}\\\r\n] | line_break | "{{" | "}}" | escape))+
F_SPEC_TEXT<quote, escape> "format specification": (!quote ([^{}\\\r\n] | %if(long_string) _LINE_BREAK | escape))+
// A backslash before a brace stays text, and the brace opens or closes a replacement field.
F_ESCAPE "escape": "\\" (&[{}] | ![{}] ESCAPED)
F_RAW_ESCAPE "escape": "\\" (&[{}] | ![{}] (_LINE_BREAK | .))
NEVER "nothing": !()
F_PREFIX "f-string": [fF]
F_RAW_PREFIX "f-string": [fF] [rR] | [rR] [fF]
T_PREFIX "t-string": [tT]
T_RAW_PREFIX "t-string": [tT] [rR] | [rR] [tT]
CONVERSION "conversion character": [sra] !\p{XID_Continue}

STRING "string": [rR] STRING_BODY<RAW_ESCAPE, .> | [uU]? STRING_BODY<ESCAPE, .>
BYTES "bytes": ([rR] [bB] | [bB] [rR]) STRING_BODY<RAW_BYTES_ESCAPE, ASCII> | [bB] STRING_BODY<BYTES_ESCAPE, ASCII>
ASCII: [\x00-\x7F]
STRING_BODY<escape, char>: LONG_STRING<"\"\"\"", escape, char> | LONG_STRING<"'''", escape, char>
                         | SHORT_STRING<"\"", escape, char> | SHORT_STRING<"'", escape, char>
LONG_STRING<quote, escape, char>: quote (!quote (escape | !"\\" char))* quote
// Three quotes always open a long string, so a short one never starts there.
SHORT_STRING<quote, escape, char>: !(quote quote quote) quote (!quote (escape | ![\\\r\n] char))* quote
RAW_ESCAPE: "\\" (_LINE_BREAK | .)
RAW_BYTES_ESCAPE: "\\" (_LINE_BREAK | ASCII)
BYTES_ESCAPE: "\\" ("x" HEX{2} | ![x] (_LINE_BREAK | ASCII))
ESCAPE: "\\" ESCAPED
// Unknown escapes keep their backslash, but these four must be complete, and \U names a code
// point up to U+10FFFF.
ESCAPED: "x" HEX{2} | "u" HEX{4} | "U" ("000" HEX{5} | "0010" HEX{4}) | "N{" [^}\r\n]+ "}" | ![xuUN] (_LINE_BREAK | .)
HEX: [0-9a-fA-F]

@reserved
NAME "name": [\p{XID_Start}_] \p{XID_Continue}*
// Only decimal numbers can be imaginary, and then leading zeros are fine.
NUMBER "number": HEX_NUMBER | OCT_NUMBER | BIN_NUMBER | IMAGINARY_NUMBER | FLOAT_NUMBER | INT_NUMBER
IMAGINARY_NUMBER: (FLOAT_NUMBER | DIGITS) [jJ]
HEX_NUMBER: "0" [xX] ("_"? [0-9a-fA-F])+
OCT_NUMBER: "0" [oO] ("_"? [0-7])+
BIN_NUMBER: "0" [bB] ("_"? [01])+
FLOAT_NUMBER: (DIGITS? "." DIGITS | DIGITS ".") EXPONENT? | DIGITS EXPONENT
INT_NUMBER: [1-9] ("_"? [0-9])* | "0" ("_"? "0")*
DIGITS: [0-9] ("_"? [0-9])*
EXPONENT: [eE] [+\-]? DIGITS
AUGMENTED "augmented assignment": "**=" | "//=" | ">>=" | "<<=" | "+=" | "-=" | "*=" | "/=" | "%=" | "@=" | "&=" | "|=" | "^="
COMMENT: "#" [^\r\n]*
_LINE_BREAK "line break": "\r\n" | "\n" | "\r"
_NEWLINE "newline": _LINE_BREAK _BLANK_LINES?
_BLANK_LINES "blank line": (([ \t\x0C] | "\\" _LINE_BREAK)* COMMENT? _LINE_BREAK)+
_LINE_REST "rest of the line": (!_LINE_BREAK .)* (_NEWLINE | !.)

// Recovery. A label stands where a failure can only be a mistake of the text, so that the
// labels change nothing the grammar accepts: the colon of a compound statement, the end of a
// simple statement, the block after a colon, a line at the column of its block that is no
// statement, and a line indented further than its block, so that every line is a statement or
// an error. A parse with recovery skips the rest of a header or a line, takes a missing block
// as missing, and parses a run of lines indented too far as statements where it can, so that
// their trees stay, skipping the lines it cannot.
%recover colon: (!(_LINE_BREAK | ":" &_LINE_BREAK) .)* ":"?
%recover newline: _LINE_REST
%recover indent: ()
%recover statement: _LINE_REST
%recover indented: ((%same | %indent(())) &. (statement | _LINE_REST))+