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): Returnstrueif 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§
Required Methods§
Provided Methods§
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.