Trait timrs_macro_utils::parse::LookaheadToken
source · pub trait LookaheadToken: Parse {
const SIZE: usize;
// Provided method
fn lookahead(cursor: Cursor<'_>) -> SynResult<(Self, Cursor<'_>)> { ... }
}
Expand description
Trait defining a token that can be consumed by syn::parse::ParseBuffer::step
.
Required Associated Constants§
Provided Methods§
sourcefn lookahead(cursor: Cursor<'_>) -> SynResult<(Self, Cursor<'_>)>
fn lookahead(cursor: Cursor<'_>) -> SynResult<(Self, Cursor<'_>)>
Looks ahead in the provided syn::buffer::Cursor
for Self
returning a tuple containing the parsed Self
and a syn::buffer::Cursor
positioned after the parsed token if it is found.
§Examples
use core::str::FromStr;
use proc_macro2::TokenStream;
use syn::{
parse::{Parse, ParseStream},
parse2, Ident, Result as SynResult, Token,
};
use timrs_macro_utils::parse::LookaheadToken;
#[derive(Debug, PartialEq)]
struct TestToken;
impl Parse for TestToken {
fn parse(input: ParseStream) -> SynResult<Self> {
input.parse::<Token![<]>()?;
input.parse::<Token![|]>()?;
input.parse::<Token![>]>()?;
SynResult::Ok(Self {})
}
}
impl LookaheadToken for TestToken { const SIZE: usize = 3; }
#[derive(Debug, PartialEq)]
struct Test { first: String, token: TestToken, second: String }
impl Parse for Test {
fn parse(input: ParseStream) -> SynResult<Self> {
SynResult::Ok(Self {
first: input.parse::<Ident>()?.to_string(),
token: input.step(|cursor| TestToken::lookahead (*cursor))?,
second: input.parse::<Ident>()?.to_string(),
})
}
}
assert_eq!(
parse2::<Test>(
TokenStream::from_str("first <|> second").map_err(|error| error.to_string()).unwrap()
).map_err(|error| error.to_string()).unwrap(),
Test { first: "first".to_owned(), token: TestToken, second: "second".to_owned() }
);
§Errors
Returns the syn::Error
for the attempted lookahead if the Self
can’t be parsed.
Object Safety§
This trait is not object safe.