Skip to main content

Parser

Struct Parser 

Source
pub struct Parser<'a> { /* private fields */ }
Expand description

Push-based LR parser. Call maybe_reduce in a loop, then shift each token. Rule 0 signals acceptance.

Implementations§

Source§

impl<'a> Parser<'a>

Source

pub fn new(table: ParseTable<'a>) -> Self

Create a new parser with the given parse table.

Source

pub fn maybe_reduce( &mut self, lookahead: Option<Token>, ) -> Result<Option<(usize, usize, usize)>, ParseError>

Check if a reduction should happen for the given lookahead.

Returns Ok(Some((rule, len, start_idx))) if a reduction should occur. The start_idx together with token_count() forms the half-open range [start_idx, token_count()). Returns Ok(None) if should shift or if accepted. Returns Err(ParseError) on parse error.

Source

pub fn shift(&mut self, token: Token)

Shift a token onto the stack.

Call this only after maybe_reduce returns Ok(None), meaning no more reductions apply for the current lookahead.

Source

pub fn restore_checkpoint(&mut self)

Restore parser state to before the current reduction sequence.

When using a runtime grammar, call this after maybe_reduce returns a reduction you want to handle yourself, to undo the speculative stack modifications before continuing.

Source

pub fn state(&self) -> usize

Get the current LR automaton state (an opaque index into the parse table).

Source

pub fn token_count(&self) -> usize

Get the count of tokens shifted so far.

Source

pub fn state_at(&self, depth: usize) -> usize

Get the LR automaton state at a given stack depth (0 = bottom of stack).

Source

pub fn format_error( &self, terminal: SymbolId, ctx: &impl ErrorContext, display_names: Option<&[(&str, &str)]>, tokens: Option<&[&str]>, ) -> String

Format a parse error into a detailed message.

Call this after maybe_reduce returns an error.

  • display_names: optional map from grammar names to user-friendly names (e.g., "SEMI""';'").
  • tokens: optional token texts by index (must include the error token at index token_count()).
§Adding source locations

The parser is push-based, so the lexer knows the source position when each token is pushed. Capture the location before pushing and use it when formatting the error:

loop {
    let (line, col) = src.line_col();
    let tok = lex_one_token(&mut src);
    if let Err(ParseError::Syntax { terminal }) = parser.push(tok, &mut actions) {
        let msg = parser.format_error(terminal, ctx, None, None);
        return Err(format!("{line}:{col}: {msg}"));
    }
}
Source

pub fn recover(&mut self, buffer: &[Token]) -> Vec<RecoveryInfo>

Recover from parse errors by finding minimum-cost repairs.

Takes the remaining token buffer (starting from the error token). Returns a list of errors found, each with the repairs applied. An empty result means no viable recovery was found within the search budget. On success the parser state is advanced past the repaired region and parsing can continue.

Trait Implementations§

Source§

impl<'a> Clone for Parser<'a>

Source§

fn clone(&self) -> Parser<'a>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl<'a> Freeze for Parser<'a>

§

impl<'a> RefUnwindSafe for Parser<'a>

§

impl<'a> Send for Parser<'a>

§

impl<'a> Sync for Parser<'a>

§

impl<'a> Unpin for Parser<'a>

§

impl<'a> UnsafeUnpin for Parser<'a>

§

impl<'a> UnwindSafe for Parser<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.