2023-08-19 23:02:24 -05:00
// © 2023 John Breaux
2023-08-25 03:05:42 -05:00
//! A [`Parsable`] struct (an AST node) can parse tokens from a [stream](TokenStream) into it[`self`](https://doc.rust-lang.org/stable/std/keyword.SelfTy.html)
2023-08-19 23:02:24 -05:00
use super ::* ;
/// Parses tokens from [stream](TokenStream) into Self node
pub trait Parsable {
/// Parses tokens from [TokenStream](TokenStream) into Self nodes
fn parse < ' text , T > ( p : & Parser , stream : & mut T ) -> Result < Self , Error >
where
Self : Sized ,
T : TokenStream < ' text > ;
/// Attempts to parse tokens from [stream](TokenStream) into Self nodes.
///
/// Masks failed expectations.
fn try_parse < ' text , T > ( p : & Parser , stream : & mut T ) -> Result < Option < Self > , Error >
where
Self : Sized ,
T : TokenStream < ' text > ,
{
match Self ::parse ( p , stream ) . map_err ( | e | e . bare ( ) ) {
Ok ( tt ) = > Ok ( Some ( tt ) ) ,
Err ( Error ::UnexpectedToken { .. } ) | Err ( Error ::AllExpectationsFailed { .. } ) = > Ok ( None ) ,
2023-08-23 02:15:10 -05:00
Err ( e ) = > Err ( e . context ( stream . context ( ) ) ) ,
2023-08-19 23:02:24 -05:00
}
}
fn parse_and < ' text , T , R > ( p : & Parser , stream : & mut T , f : fn ( p : & Parser , & mut T ) -> R ) -> Result < ( Self , R ) , Error >
where
Self : Sized ,
T : TokenStream < ' text > ,
{
Ok ( ( Self ::parse ( p , stream ) ? , f ( p , stream ) ) )
}
/// Attempts to parse tokens from [stream](TokenStream) into Self nodes.
///
/// Returns [`Self::default()`](Default::default()) on error
fn parse_or_default < ' text , T > ( p : & Parser , stream : & mut T ) -> Self
where
Self : Sized + Default ,
T : TokenStream < ' text > ,
{
Self ::parse ( p , stream ) . unwrap_or_default ( )
}
}