Skip to content

Commit

Permalink
Add a real-world example for ParseBuffer::cursor
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Dec 20, 2023
1 parent bdd0645 commit 12ff3d1
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1096,6 +1096,58 @@ impl<'a> ParseBuffer<'a> {
///
/// Cursors are immutable so no operations you perform against the cursor
/// will affect the state of this parse stream.
///
/// # Example
///
/// ```
/// use proc_macro2::TokenStream;
/// use syn::buffer::Cursor;
/// use syn::parse::{ParseStream, Result};
///
/// // Run a parser that returns T, but get its output as TokenStream instead of T.
/// // This works without T needing to implement ToTokens.
/// fn recognize_token_stream<T>(
/// recognizer: fn(ParseStream) -> Result<T>,
/// ) -> impl Fn(ParseStream) -> Result<TokenStream> {
/// move |input| {
/// let begin = input.cursor();
/// recognizer(input)?;
/// let end = input.cursor();
/// Ok(tokens_between(begin, end))
/// }
/// }
///
/// // Collect tokens between two cursors as a TokenStream.
/// fn tokens_between(begin: Cursor, end: Cursor) -> TokenStream {
/// assert!(begin <= end);
///
/// let mut cursor = begin;
/// let mut tokens = TokenStream::new();
/// while cursor < end {
/// let (token, next) = cursor.token_tree().unwrap();
/// tokens.extend(std::iter::once(token));
/// cursor = next;
/// }
/// tokens
/// }
///
/// fn main() {
/// use quote::quote;
/// use syn::parse::{Parse, Parser};
/// use syn::Token;
///
/// // Parse syn::Type as a TokenStream, surrounded by angle brackets.
/// fn example(input: ParseStream) -> Result<TokenStream> {
/// let _langle: Token![<] = input.parse()?;
/// let ty = recognize_token_stream(syn::Type::parse)(input)?;
/// let _rangle: Token![>] = input.parse()?;
/// Ok(ty)
/// }
///
/// let tokens = quote! { <fn() -> u8> };
/// println!("{}", example.parse2(tokens).unwrap());
/// }
/// ```
pub fn cursor(&self) -> Cursor<'a> {
self.cell.get()
}
Expand Down

0 comments on commit 12ff3d1

Please sign in to comment.