parser-lang 1.0.0

Recursive-descent + Pratt parser infrastructure with error recovery.
Documentation

Installation

[dependencies]
parser-lang = "1"

Example

A calculator that evaluates 1 + 2 * 3 to 7 with correct precedence — a Pratt grammar over a token-lang stream.

use parser_lang::{Parser, Pratt, Span, Token, TokenKind};

#[derive(Clone, Copy)]
enum K { Num(i64), Plus, Star, Eof }
impl TokenKind for K {
    fn is_eof(&self) -> bool { matches!(self, K::Eof) }
}

struct Calc;
impl<'t> Pratt<'t, K> for Calc {
    type Output = i64;
    fn prefix(&mut self, p: &mut Parser<'t, K>) -> Option<i64> {
        match p.bump()?.kind() { K::Num(n) => Some(*n), _ => None }
    }
    fn infix_binding(&self, k: &K) -> Option<(u8, u8)> {
        match k { K::Plus => Some((1, 2)), K::Star => Some((3, 4)), _ => None }
    }
    fn infix(&mut self, op: &'t Token<K>, l: i64, r: i64) -> Option<i64> {
        match op.kind() { K::Plus => Some(l + r), K::Star => Some(l * r), _ => None }
    }
}

let s = |i| Span::new(i, i + 1);
let tokens = [
    Token::new(K::Num(1), s(0)), Token::new(K::Plus, s(1)),
    Token::new(K::Num(2), s(2)), Token::new(K::Star, s(3)),
    Token::new(K::Num(3), s(4)), Token::new(K::Eof, Span::empty(5)),
];
let mut p = Parser::new(&tokens);
assert_eq!(Calc.parse(&mut p), Some(7));

Status

This is v1.0.0: the public API is stable and frozen under SemVer. The Parser cursor (with error recovery) and the Pratt precedence engine are complete and catalogued in docs/API.md.

Contributing

See dev/DIRECTIVES.md for engineering standards and the definition of done. Before a PR: cargo fmt --all, cargo clippy --all-targets --all-features -- -D warnings, and cargo test --all-features must be clean.