API reference¶
The public API is exported from the top-level abnf package:
from abnf import Rule, Node, LiteralNode, NodeVisitor, ParseError, GrammarError
The parser combinator primitives (Alternation, Concatenation, Repetition,
Option, Literal, Prose) are internal and not part of the public API; see
Architecture: parser combinators for how they fit together.
Rule¶
- class abnf.Rule(name, definition=None)[source]¶
Bases:
objectA parser generated from an ABNF rule.
To create a Rule object, use Rule.create.
rule = Rule.create(‘URI = scheme “:” hier-part [ “?” query ] [ “#” fragment ]’)
- Parameters:
name (str)
definition (Parser | None)
- property definition: Parser¶
Underlying parser combinator for this rule.
Backed by
self._definition. The property setter forwards writes throughRule._set_definition_hook(when set) so the Rust backend can keep its shadow registry of named-rule handles in sync with the Python-visible definition graph.
- exclude_rule(rule)[source]¶
Exclude values which match
rule. For example, suppose we have the following grammar:foo = %x66.6f.6f keyword = foo identifier = ALPHA *(ALPHA / DIGIT )
We don’t want to allow a keyword to be an identifier. To do this:
Rule('identifier').exclude_rule(Rule('keyword'))
Then attempting to use “foo” as an identifier would result in a ParseError.
- Parameters:
rule (Rule)
- Return type:
None
- parse(source, start)[source]¶
- Parameters:
- Returns:
parse tree, new offset at which to continue parsing
- Return type:
- Raises:
ParseError – if source cannot be parsed using rule.
GrammarError – if rule has no definition. This usually means that a non-terminal in the grammar is not defined or imported.
- parse_all(source)[source]¶
Parses the source from beginning to end. If not all of the source is consumed, a ParseError is raised.
- Parameters:
source (str) – source data
start=0 – offset at which to begin parsing.
- Returns:
parse tree
- Return type:
- Raises:
ParseError – if source cannot be parsed using rule.
GrammarError – if rule has no definition. This usually means that a non-terminal in the grammar is not defined or imported.
Note
The pure-Python backend is recursive-descent, so input nested more deeply than the Python recursion limit permits is reported as a ParseError rather than crashing with RecursionError. The Rust backend is not subject to this limit. If you must parse very deeply nested input on the pure-Python backend, run the parse on a worker thread with a larger stack and a raised recursion limit – both levers are needed, as
setrecursionlimitalone would overflow the C stack:import sys, threading def parse_all_deep(rule, source, *, limit=100_000, stack=256 * 1024 * 1024): threading.stack_size(stack) box = {} def run(): sys.setrecursionlimit(limit) # process-global while running try: box["node"] = rule.parse_all(source) except BaseException as exc: # re-raised on the caller box["exc"] = exc t = threading.Thread(target=run) t.start() t.join() if "exc" in box: raise box["exc"] return box["node"]
- classmethod create(rule_source, start=0)[source]¶
Creates a Rule object from ABNF source. A terminating CRLF will be appended to rule_source if needed to satisfy the ABNF grammar rule for “rule”.
- classmethod load_grammar(grammar, strict=True)[source]¶
Loads grammar and attempts to parse it as a rulelist. If successful, cls is populated with the rules in the rulelist. When strict = True, line endings following rules are normalized to CRLF to satisfy the definition of ‘rulelist. If strict is set to False, the grammar is parsed as is.
- classmethod from_file(path)[source]¶
Loads the contents of path and attempts to parse it as a rulelist. If successful, cls is populated with the rules in the rulelist.
Node¶
LiteralNode¶
NodeVisitor¶
Exceptions¶
- exception abnf.ParseError(parser, start, *args)[source]¶
Bases:
ExceptionRaised in response to errors during parsing.
- exception abnf.GrammarError[source]¶
Bases:
ExceptionRaised in response to errors detected in the grammar.
- exception abnf.GrammarWarning[source]¶
Bases:
UserWarningEmitted for suspect (but not fatal) conditions detected in a grammar, such as a rule that is defined more than once with ‘=’.