Peek

Trait Peek 

Source
pub trait Peek: Sized {
    type Token: Clone;

    // Required method
    fn is(token: &Self::Token) -> bool;

    // Provided method
    fn peek<S>(stream: &S) -> bool
       where S: TokenStream<Token = Self::Token> { ... }
}
Expand description

Trait for lookahead without consuming tokens.

Peek enables the parser to inspect the next token to decide which production to use, without consuming it. This is essential for implementing LL(1) and similar parsing strategies.

§Associated Types

  • Token: The token type to peek at (e.g., MyTok)

§Required Methods

  • is(token): Returns true if the token matches this type

§Provided Methods

  • peek(stream): Checks if the next token in the stream matches

§Example

use synkit::{Peek, TokenStream};

struct IfKeyword;

impl Peek for IfKeyword {
    type Token = MyTok;

    fn is(token: &Self::Token) -> bool {
        matches!(token, MyTok::If)
    }
}

// In parser:
fn parse_statement(stream: &mut impl TokenStream<Token = MyTok>) {
    if stream.peek::<IfKeyword>() {
        parse_if_statement(stream)
    } else {
        parse_expression_statement(stream)
    }
}

§Usage Patterns

§Simple Token Matching

if stream.peek::<Comma>() {
    stream.parse::<Comma>()?;
}

§Alternative Productions

if stream.peek::<NumberLiteral>() {
    Expr::Number(stream.parse()?)
} else if stream.peek::<StringLiteral>() {
    Expr::String(stream.parse()?)
} else {
    return Err(Error::unexpected());
}

Required Associated Types§

Source

type Token: Clone

The token type to peek at.

Required Methods§

Source

fn is(token: &Self::Token) -> bool

Check if a token matches this type.

§Arguments
  • token - The token to check
§Returns

true if the token matches this type

Provided Methods§

Source

fn peek<S>(stream: &S) -> bool
where S: TokenStream<Token = Self::Token>,

Peek at stream without consuming tokens.

Default implementation calls is() on the next token.

§Arguments
  • stream - The token stream to peek into
§Returns

true if the next token matches, false if no match or stream empty

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<T> Peek for Box<T>
where T: Peek,

Source§

type Token = <T as Peek>::Token

Source§

fn is(token: &<Box<T> as Peek>::Token) -> bool

Implementors§