pub trait Parse: Sized {
type Token: Clone;
type Error;
// Required method
fn parse<S>(stream: &mut S) -> Result<Self, Self::Error>
where S: TokenStream<Token = Self::Token>;
}Expand description
Trait for types that can be parsed from a token stream.
This is the primary trait for defining how AST nodes are constructed from tokens. Implementations consume tokens from the stream and return either a parsed value or an error.
§Associated Types
Token: The token type this parser consumes (e.g.,MyTok)Error: The error type for parse failures (e.g.,MyParseError)
§Implementation Guidelines
- Use
stream.peek::<T>()to check token types without consuming - Use
stream.parse::<T>()to recursively parse nested structures - Use
stream.fork()for backtracking lookahead - Return errors early with
?operator
§Example
ⓘ
use synkit::{Parse, Peek, TokenStream};
struct BinaryExpr {
left: Box<Expr>,
op: Operator,
right: Box<Expr>,
}
impl Parse for BinaryExpr {
type Token = MyTok;
type Error = ParseError;
fn parse<S>(stream: &mut S) -> Result<Self, Self::Error>
where
S: TokenStream<Token = Self::Token>,
{
let left = stream.parse()?;
let op = stream.parse()?;
let right = stream.parse()?;
Ok(BinaryExpr { left, op, right })
}
}§Blanket Implementations
Option<T>: ParsesSome(T)ifT::peek()succeeds, elseNoneBox<T>: Delegates toT::parse()and boxes the result
Required Associated Types§
Required 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.