Skip to content

parser

Location dataclass

Where a token starts in the source text. offset is 0-based, and line and column are 1-based.

Source code in src/syntactes/parser/token.py
@dataclass(frozen=True)
class Location:
    """
    Where a token starts in the source text. `offset` is 0-based, and `line`
    and `column` are 1-based.
    """

    offset: int
    line: int
    column: int

    @classmethod
    def from_object(cls, obj: Any) -> Self:
        """
        Builds a location from a mapping with the keys `offset`, `line` and
        `column`, or from any other object with those attributes, such as a
        lexer's own location. Other keys and attributes are ignored, and each
        value is converted with `int`.

        Raises `syntactes.parser.LocationObjectError` if a key or attribute is
        missing, or if its value can't be converted to an integer, with the
        conversion's exception as its cause.
        """
        attrs = ("offset", "line", "column")

        if isinstance(obj, Mapping):
            for key in attrs:
                if key not in obj:
                    raise LocationObjectError(
                        f"cannot create Location object from {obj!r}, missing {key!r} key"
                    )

            data = {}
            try:
                for key in attrs:
                    data[key] = int(obj.get(key))
            except (ValueError, TypeError) as e:
                raise LocationObjectError(
                    f"cannot create Location object from {obj!r}, {key!r} cannot be converted to an integer"
                ) from e

            return cls(**data)

        for attr in attrs:
            if not hasattr(obj, attr):
                raise LocationObjectError(
                    f"cannot create Location object from {obj!r}, missing attribute {attr!r}"
                )

        data = {}
        try:
            for attr in attrs:
                data[attr] = int(getattr(obj, attr))
        except (ValueError, TypeError) as e:
            raise LocationObjectError(
                f"cannot create Location object from {obj!r}, {attr!r} cannot be converted to an integer"
            ) from e

        return cls(**data)

from_object(obj) classmethod

Builds a location from a mapping with the keys offset, line and column, or from any other object with those attributes, such as a lexer's own location. Other keys and attributes are ignored, and each value is converted with int.

Raises syntactes.parser.LocationObjectError if a key or attribute is missing, or if its value can't be converted to an integer, with the conversion's exception as its cause.

Source code in src/syntactes/parser/token.py
@classmethod
def from_object(cls, obj: Any) -> Self:
    """
    Builds a location from a mapping with the keys `offset`, `line` and
    `column`, or from any other object with those attributes, such as a
    lexer's own location. Other keys and attributes are ignored, and each
    value is converted with `int`.

    Raises `syntactes.parser.LocationObjectError` if a key or attribute is
    missing, or if its value can't be converted to an integer, with the
    conversion's exception as its cause.
    """
    attrs = ("offset", "line", "column")

    if isinstance(obj, Mapping):
        for key in attrs:
            if key not in obj:
                raise LocationObjectError(
                    f"cannot create Location object from {obj!r}, missing {key!r} key"
                )

        data = {}
        try:
            for key in attrs:
                data[key] = int(obj.get(key))
        except (ValueError, TypeError) as e:
            raise LocationObjectError(
                f"cannot create Location object from {obj!r}, {key!r} cannot be converted to an integer"
            ) from e

        return cls(**data)

    for attr in attrs:
        if not hasattr(obj, attr):
            raise LocationObjectError(
                f"cannot create Location object from {obj!r}, missing attribute {attr!r}"
            )

    data = {}
    try:
        for attr in attrs:
            data[attr] = int(getattr(obj, attr))
    except (ValueError, TypeError) as e:
        raise LocationObjectError(
            f"cannot create Location object from {obj!r}, {attr!r} cannot be converted to an integer"
        ) from e

    return cls(**data)

Token

A token of the stream a parser reads: a terminal symbol, the Location it starts at, and the value it was read with, e.g. Token(NUMBER, Location(0, 1, 1), "42"). Callbacks receive one token per right-hand side symbol. A non-terminal's token holds the value computed for its rule, and the location of its first token (for an empty rule, of the token that follows it).

Tokens are equal if their symbols and values are. Hashing uses only the symbol, so a token with an unhashable value can still be hashed.

Source code in src/syntactes/parser/token.py
class Token:
    """
    A token of the stream a parser reads: a terminal symbol, the `Location` it
    starts at, and the value it was read with, e.g.
    `Token(NUMBER, Location(0, 1, 1), "42")`. Callbacks receive one token per
    right-hand side symbol. A non-terminal's token holds the value computed for
    its rule, and the location of its first token (for an empty rule, of the
    token that follows it).

    Tokens are equal if their symbols and values are. Hashing uses only the
    symbol, so a token with an unhashable value can still be hashed.
    """

    def __init__(self, symbol: Symbol, location: Location, value: Any = None) -> None:
        self.symbol = symbol
        self.location = location
        self.value = value

    def __repr__(self) -> str:
        return f"<Token: {self.symbol}, {self.value!r}>"

    def __str__(self) -> str:
        return str(self.symbol)

    def __hash__(self) -> int:
        return hash(self.symbol)

    def __eq__(self, other) -> bool:
        if self is other:
            return True

        if not isinstance(other, Token):
            return False

        return self.symbol == other.symbol and self.value == other.value

LR0Parser

Bases: Parser

Parser that uses an LR0 parsing table.

Source code in src/syntactes/parser/parser.py
class LR0Parser(Parser):
    """
    Parser that uses an LR0 parsing table.
    """

    generator_cls = LR0Generator

LR1Parser

Bases: Parser

Parser that uses an LR1 parsing table.

Source code in src/syntactes/parser/parser.py
class LR1Parser(Parser):
    """
    Parser that uses an LR1 parsing table.
    """

    generator_cls = LR1Generator

Parser

Bases: ABC

Base class of the LR parsers. Parses a stream of tokens with a parsing table, and on each reduction computes the rule's value: with the callback registered with execute_on, else with the rule's primitive from the grammar.

Source code in src/syntactes/parser/parser.py
class Parser(ABC):
    """
    Base class of the LR parsers. Parses a stream of tokens with a parsing table,
    and on each reduction computes the rule's value: with the callback registered
    with `execute_on`, else with the rule's primitive from the grammar.
    """

    generator_cls: type

    def __init__(self, table: ParsingTable) -> None:
        self._table = table
        self._executables: dict[Rule, Executable] = {}

    @classmethod
    def from_grammar(cls, grammar: Grammar) -> "Parser":
        """
        Create a parser for the given grammar.
        """
        generator = cls.generator_cls(grammar)
        parsing_table = generator.generate()
        parser = cls(parsing_table)
        return parser

    def execute_on[F: Executable](self, rule: Rule | str) -> Callable[[F], F]:
        """
        Decorate a function to be executed when this parser reduces by `rule`.

        `rule` is a `Rule` or its text, as `str(rule)` prints it: the left-hand
        side, `->`, then the right-hand side symbols separated by whitespace,
        e.g. `"E -> T + E"`. An empty rule is `"A -> ε"` or `"A ->"`, and the
        starting rule ends with `$`. Symbols are matched by name. The text can
        start with the rule's primitive, as in `Grammar.from_text`
        (`"int % T -> x"`, `"add(1,3) % E -> E + T"`), which must then match
        the grammar's; without operands, `"add % E -> E + T"` matches any.

        The function is called with one token per right-hand side symbol of the
        rule, and returns the value of the left-hand side token. The decorated
        function is returned unchanged.

        Raises `ValueError` if `rule` is not a rule of the parser's grammar, if
        its text is malformed, matches more than one rule, or gives a primitive
        the rule doesn't have.
        """
        if isinstance(rule, str):
            rule = self._rule_from_text(rule)

        if rule not in self._table.grammar.rules:
            raise ValueError(f"Rule '{rule}' is not in the parser's grammar.")

        def executable_decorator(executable_fn: F) -> F:
            self._executables[rule] = executable_fn
            return executable_fn

        return executable_decorator

    def _rule_from_text(self, text: str) -> Rule:
        """
        Returns the rule of the parser's grammar that `text` names, as described
        in `execute_on`.
        """
        left, arrow, rest = text.partition("->")
        prefix, percent, lhs = left.partition("%")
        if not percent:
            prefix, lhs = "", prefix

        lhs_names = lhs.split()
        if not arrow or len(lhs_names) != 1 or (percent and not prefix.strip()):
            raise ValueError(
                f"Invalid rule '{text}', expected '[primitive %] lhs -> symbols'."
            )

        rhs_names = tuple(rest.split())
        empty = rhs_names in ((), (Symbol.null().name,))
        matches = [
            rule
            for rule in self._table.grammar.rules
            if rule.lhs.name == lhs_names[0]
            and (
                rule.is_empty()
                if empty
                else tuple(s.name for s in rule.rhs) == rhs_names
            )
        ]

        if not matches:
            raise ValueError(f"Rule '{text}' is not in the parser's grammar.")

        if len(matches) > 1:
            raise ValueError(
                f"Rule '{text}' matches more than one rule of the parser's grammar,"
                " pass the Rule instead."
            )

        rule = matches[0]
        if percent:
            self._check_primitive(rule, prefix.strip(), text)

        return rule

    def _check_primitive(self, rule: Rule, prefix: str, text: str) -> None:
        """
        Raises `ValueError` unless `prefix`, the primitive of a rule's text, is
        the rule's primitive in the grammar, with its operands if it gives any.
        """
        try:
            name, operands = _split_primitive(prefix)
        except ValueError:
            raise ValueError(
                f"Invalid primitive '{prefix}' in rule '{text}', expected 'name' or"
                " 'name(i,j)'."
            ) from None

        grammar = self._table.grammar
        primitive = grammar.primitives.get(rule)
        if primitive is None:
            raise ValueError(f"Rule '{rule}' has no primitive, but '{text}' has.")

        if primitive.string() != name:
            raise ValueError(
                f"Rule '{rule}' has primitive '{primitive.string()}', not '{name}'."
            )

        if operands is None:
            return

        expected = grammar.operands.get(rule)
        if expected is None:
            raise ValueError(f"Rule '{rule}' has no operands, but '{text}' has.")

        if operands != expected:
            raise ValueError(f"Rule '{rule}' has operands {expected}, not {operands}.")

    def parse(self, stream: Iterable[Token]) -> object:
        """
        Parses the given stream of tokens. Expects a token with the EOF symbol,
        `Token(Symbol.eof(), location)`, as the last one.

        On each reduction the parser pushes a token for the left-hand side. Its
        `location` is that of the rule's first token, or for an empty rule, of
        the token that follows it. Its `value` is the rule's value, which is, in
        order of precedence:

        - what the callback registered for the rule returns, called with one
          token per right-hand side symbol, in order;
        - the result of the rule's primitive (`Grammar.primitives`): a binary
          operation gets the values of the tokens at `Grammar.operands`, `None`
          gives None, and any other primitive converts its single token's value;
        - the value of the rule's token, if it has exactly one;
        - None.

        On accept the starting rule's value is computed the same way, from its
        right-hand side tokens except the trailing EOF, and returned. So a
        starting rule with neither a callback nor a primitive returns the start
        symbol's value.

        Raises `syntactes.parser.PrimitiveError` if a primitive raises, with the
        original exception as its cause. Exceptions raised by callbacks
        propagate unchanged.

        Raises `syntactes.parser.UnexpectedTokenError` if an unexpected token is
        received.

        Raises `syntactes.parser.NotAcceptedError` if the stream of tokens ends
        before the parser receives an accept action.
        """
        states: list[LR0State] = [self._table.initial_state]
        tokens: list[Token] = []

        tokens_in = iter(stream)
        token = next(tokens_in, None)

        while token is not None:
            action = self._get_action(states[-1], token)

            if action.action_type == ActionType.SHIFT:
                tokens.append(token)
                states.append(cast(LR0State, action.actionable))
                token = next(tokens_in, None)
            elif action.action_type == ActionType.REDUCE:
                # Reduce actions do not consume the token.
                rule = cast(Rule, action.actionable)
                rhs_len = 0 if rule.is_empty() else rule.rhs_len
                args = self._pop(tokens, rhs_len)
                self._pop(states, rhs_len)

                value = self._value(rule, args)

                if len(args) > 0:
                    loc = args[0].location
                else:
                    loc = token.location

                lhs = Token(rule.lhs, loc, value)
                tokens.append(lhs)
                shift = self._get_action(states[-1], lhs)
                states.append(cast(LR0State, shift.actionable))
            elif action.action_type == ActionType.ACCEPT:
                extra = next(tokens_in, None)
                if extra is not None:
                    raise UnexpectedTokenError(extra, [])

                starting_rule = self._table.grammar.starting_rule
                args = self._pop(tokens, starting_rule.rhs_len - 1)
                return self._value(starting_rule, args)

        raise NotAcceptedError("Expected EOF token. ")

    def _value(self, rule: Rule, tokens: list[Token]) -> object:
        """
        Computes the value of `rule` from its right-hand side tokens: with its
        callback, else its primitive, else its single token's value, else None.
        """
        executable = self._executables.get(rule)
        if executable is not None:
            return executable(*tokens)

        primitive = self._table.grammar.primitives.get(rule)
        if primitive is not None:
            return self._apply(rule, primitive, tokens)

        if len(tokens) == 1:
            return tokens[0].value

        return None

    def _apply(self, rule: Rule, primitive: Primitive, tokens: list[Token]) -> object:
        try:
            if _is_binary(primitive):
                left, right = self._table.grammar.operands[rule]
                return primitive(tokens[left - 1].value, tokens[right - 1].value)

            if primitive is NoneType:
                return None

            return primitive(tokens[0].value)
        except Exception as e:
            raise PrimitiveError(rule, primitive) from e

    @staticmethod
    def _pop[T](stack: list[T], count: int) -> list[T]:
        """
        Pops the top `count` elements of the stack and returns them in stack order.
        """
        popped = stack[len(stack) - count :]
        del stack[len(stack) - count :]
        return popped

    def _get_action(self, state: LR0State, token: Token) -> Action:
        actions = self._table.get_actions(state, token.symbol)
        if actions is None:
            raise UnexpectedTokenError(token, self._expected_symbols(state))

        return self._resolve_conflict(actions)

    def _expected_symbols(self, state: LR0State) -> list[Symbol]:
        """
        Returns the terminals that have an action in the given state, sorted.
        """
        row = self._table.get(state) or {}
        return sorted(symbol for symbol in row if symbol.is_terminal)

    def _resolve_conflict(self, actions: list[Action]) -> Action:
        """
        Picks one of the actions of a table cell. Accept wins over shift, shift
        wins over reduce, and among reduces the lowest rule number wins.
        """
        return min(actions, key=self._action_priority)

    @staticmethod
    def _action_priority(action: Action) -> tuple[int, int]:
        if action.action_type == ActionType.ACCEPT:
            return (0, 0)

        if action.action_type == ActionType.SHIFT:
            return (1, 0)

        return (2, cast(Rule, action.actionable).number)

execute_on(rule)

Decorate a function to be executed when this parser reduces by rule.

rule is a Rule or its text, as str(rule) prints it: the left-hand side, ->, then the right-hand side symbols separated by whitespace, e.g. "E -> T + E". An empty rule is "A -> ε" or "A ->", and the starting rule ends with $. Symbols are matched by name. The text can start with the rule's primitive, as in Grammar.from_text ("int % T -> x", "add(1,3) % E -> E + T"), which must then match the grammar's; without operands, "add % E -> E + T" matches any.

The function is called with one token per right-hand side symbol of the rule, and returns the value of the left-hand side token. The decorated function is returned unchanged.

Raises ValueError if rule is not a rule of the parser's grammar, if its text is malformed, matches more than one rule, or gives a primitive the rule doesn't have.

Source code in src/syntactes/parser/parser.py
def execute_on[F: Executable](self, rule: Rule | str) -> Callable[[F], F]:
    """
    Decorate a function to be executed when this parser reduces by `rule`.

    `rule` is a `Rule` or its text, as `str(rule)` prints it: the left-hand
    side, `->`, then the right-hand side symbols separated by whitespace,
    e.g. `"E -> T + E"`. An empty rule is `"A -> ε"` or `"A ->"`, and the
    starting rule ends with `$`. Symbols are matched by name. The text can
    start with the rule's primitive, as in `Grammar.from_text`
    (`"int % T -> x"`, `"add(1,3) % E -> E + T"`), which must then match
    the grammar's; without operands, `"add % E -> E + T"` matches any.

    The function is called with one token per right-hand side symbol of the
    rule, and returns the value of the left-hand side token. The decorated
    function is returned unchanged.

    Raises `ValueError` if `rule` is not a rule of the parser's grammar, if
    its text is malformed, matches more than one rule, or gives a primitive
    the rule doesn't have.
    """
    if isinstance(rule, str):
        rule = self._rule_from_text(rule)

    if rule not in self._table.grammar.rules:
        raise ValueError(f"Rule '{rule}' is not in the parser's grammar.")

    def executable_decorator(executable_fn: F) -> F:
        self._executables[rule] = executable_fn
        return executable_fn

    return executable_decorator

from_grammar(grammar) classmethod

Create a parser for the given grammar.

Source code in src/syntactes/parser/parser.py
@classmethod
def from_grammar(cls, grammar: Grammar) -> "Parser":
    """
    Create a parser for the given grammar.
    """
    generator = cls.generator_cls(grammar)
    parsing_table = generator.generate()
    parser = cls(parsing_table)
    return parser

parse(stream)

Parses the given stream of tokens. Expects a token with the EOF symbol, Token(Symbol.eof(), location), as the last one.

On each reduction the parser pushes a token for the left-hand side. Its location is that of the rule's first token, or for an empty rule, of the token that follows it. Its value is the rule's value, which is, in order of precedence:

  • what the callback registered for the rule returns, called with one token per right-hand side symbol, in order;
  • the result of the rule's primitive (Grammar.primitives): a binary operation gets the values of the tokens at Grammar.operands, None gives None, and any other primitive converts its single token's value;
  • the value of the rule's token, if it has exactly one;
  • None.

On accept the starting rule's value is computed the same way, from its right-hand side tokens except the trailing EOF, and returned. So a starting rule with neither a callback nor a primitive returns the start symbol's value.

Raises syntactes.parser.PrimitiveError if a primitive raises, with the original exception as its cause. Exceptions raised by callbacks propagate unchanged.

Raises syntactes.parser.UnexpectedTokenError if an unexpected token is received.

Raises syntactes.parser.NotAcceptedError if the stream of tokens ends before the parser receives an accept action.

Source code in src/syntactes/parser/parser.py
def parse(self, stream: Iterable[Token]) -> object:
    """
    Parses the given stream of tokens. Expects a token with the EOF symbol,
    `Token(Symbol.eof(), location)`, as the last one.

    On each reduction the parser pushes a token for the left-hand side. Its
    `location` is that of the rule's first token, or for an empty rule, of
    the token that follows it. Its `value` is the rule's value, which is, in
    order of precedence:

    - what the callback registered for the rule returns, called with one
      token per right-hand side symbol, in order;
    - the result of the rule's primitive (`Grammar.primitives`): a binary
      operation gets the values of the tokens at `Grammar.operands`, `None`
      gives None, and any other primitive converts its single token's value;
    - the value of the rule's token, if it has exactly one;
    - None.

    On accept the starting rule's value is computed the same way, from its
    right-hand side tokens except the trailing EOF, and returned. So a
    starting rule with neither a callback nor a primitive returns the start
    symbol's value.

    Raises `syntactes.parser.PrimitiveError` if a primitive raises, with the
    original exception as its cause. Exceptions raised by callbacks
    propagate unchanged.

    Raises `syntactes.parser.UnexpectedTokenError` if an unexpected token is
    received.

    Raises `syntactes.parser.NotAcceptedError` if the stream of tokens ends
    before the parser receives an accept action.
    """
    states: list[LR0State] = [self._table.initial_state]
    tokens: list[Token] = []

    tokens_in = iter(stream)
    token = next(tokens_in, None)

    while token is not None:
        action = self._get_action(states[-1], token)

        if action.action_type == ActionType.SHIFT:
            tokens.append(token)
            states.append(cast(LR0State, action.actionable))
            token = next(tokens_in, None)
        elif action.action_type == ActionType.REDUCE:
            # Reduce actions do not consume the token.
            rule = cast(Rule, action.actionable)
            rhs_len = 0 if rule.is_empty() else rule.rhs_len
            args = self._pop(tokens, rhs_len)
            self._pop(states, rhs_len)

            value = self._value(rule, args)

            if len(args) > 0:
                loc = args[0].location
            else:
                loc = token.location

            lhs = Token(rule.lhs, loc, value)
            tokens.append(lhs)
            shift = self._get_action(states[-1], lhs)
            states.append(cast(LR0State, shift.actionable))
        elif action.action_type == ActionType.ACCEPT:
            extra = next(tokens_in, None)
            if extra is not None:
                raise UnexpectedTokenError(extra, [])

            starting_rule = self._table.grammar.starting_rule
            args = self._pop(tokens, starting_rule.rhs_len - 1)
            return self._value(starting_rule, args)

    raise NotAcceptedError("Expected EOF token. ")

SLRParser

Bases: Parser

Parser that uses an SLR parsing table.

Source code in src/syntactes/parser/parser.py
class SLRParser(Parser):
    """
    Parser that uses an SLR parsing table.
    """

    generator_cls = SLRGenerator

LocationObjectError

Bases: ParserError

Location.from_object received an object it can't build a location from: it lacks offset, line or column, or one of them isn't an integer. In the latter case the original exception is available as __cause__.

Source code in src/syntactes/parser/exception.py
class LocationObjectError(ParserError):
    """
    `Location.from_object` received an object it can't build a location from:
    it lacks `offset`, `line` or `column`, or one of them isn't an integer. In
    the latter case the original exception is available as `__cause__`.
    """

NotAcceptedError

Bases: ParserError

The parser did not receive an accept action. The stream of tokens is syntactically invalid.

Source code in src/syntactes/parser/exception.py
class NotAcceptedError(ParserError):
    """
    The parser did not receive an accept action. The stream of tokens is
    syntactically invalid.
    """

ParserError

Bases: Exception

Base class of the errors raised by parse().

Source code in src/syntactes/parser/exception.py
5
6
7
8
class ParserError(Exception):
    """
    Base class of the errors raised by `parse()`.
    """

PrimitiveError

Bases: ParserError

A rule's primitive raised while the parser applied it, e.g. int on a token whose value isn't a number. The rule and primitive are available as rule and primitive, and the original exception as __cause__.

Source code in src/syntactes/parser/exception.py
class PrimitiveError(ParserError):
    """
    A rule's primitive raised while the parser applied it, e.g. `int` on a
    token whose value isn't a number. The rule and primitive are available as
    `rule` and `primitive`, and the original exception as `__cause__`.
    """

    def __init__(self, rule: Rule, primitive: Primitive) -> None:
        self.rule = rule
        self.primitive = primitive
        super().__init__(f"Primitive {primitive.string()} of rule '{rule}' failed.")

UnexpectedTokenError

Bases: ParserError

A token was received that does not map to an action. The stream of tokens is syntactically invalid. The token is received_token, and the terminals that would have been valid are expected_symbols.

Source code in src/syntactes/parser/exception.py
class UnexpectedTokenError(ParserError):
    """
    A token was received that does not map to an action. The stream of tokens
    is syntactically invalid. The token is `received_token`, and the terminals
    that would have been valid are `expected_symbols`.
    """

    def __init__(self, received_token, expected_symbols):
        self.received_token = received_token
        self.expected_symbols = expected_symbols
        msg = f"Received token: {received_token}; expected one of: {[str(e) for e in expected_symbols]}"
        super().__init__(msg)