Parse

Trait Parse 

Source
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

  1. Use stream.peek::<T>() to check token types without consuming
  2. Use stream.parse::<T>() to recursively parse nested structures
  3. Use stream.fork() for backtracking lookahead
  4. 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>: Parses Some(T) if T::peek() succeeds, else None
  • Box<T>: Delegates to T::parse() and boxes the result

Required Associated Types§

Source

type Token: Clone

The token type consumed by this parser.

Source

type Error

The error type for parse failures.

Required Methods§

Source

fn parse<S>(stream: &mut S) -> Result<Self, Self::Error>
where S: TokenStream<Token = Self::Token>,

Parse a value from the token stream.

§Arguments
  • stream - The token stream to parse from
§Returns
  • Ok(Self) - Successfully parsed value
  • Err(Self::Error) - Parse failure with error details

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> Parse for Option<T>
where T: Parse + Peek<Token = <T as Parse>::Token>,

Source§

type Token = <T as Parse>::Token

Source§

type Error = <T as Parse>::Error

Source§

fn parse<S>(stream: &mut S) -> Result<Self, Self::Error>
where S: TokenStream<Token = Self::Token>,

Source§

impl<T: Parse> Parse for Box<T>

Source§

type Token = <T as Parse>::Token

Source§

type Error = <T as Parse>::Error

Source§

fn parse<S>(stream: &mut S) -> Result<Self, Self::Error>
where S: TokenStream<Token = Self::Token>,

Implementors§