Skip to content

Commit f071cbc

Browse files
committed
feat: added peek_(n_)?_keyword to TokenParser
1 parent 5a1e640 commit f071cbc

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

src/parser.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,50 @@ where
369369
})
370370
}
371371

372+
/// Returns the next ident if it matches the specified keyword without
373+
/// advancing the parser.
374+
///
375+
/// While this is called `peek_keyword` it is not restricted to rust
376+
/// keywords, it can be used with any ident.
377+
/// ```
378+
/// # use proc_macro_utils::TokenParser;
379+
/// # use quote::quote;
380+
/// let mut parser = TokenParser::new(quote!( in out ));
381+
/// assert_eq!(parser.peek_keyword("in").unwrap().to_string(), "in");
382+
/// assert_eq!(parser.peek_keyword("in").unwrap().to_string(), "in");
383+
/// assert!(parser.peek_keyword("out").is_none());
384+
/// parser.next().unwrap();
385+
/// assert_eq!(parser.peek_keyword("out").unwrap().to_string(), "out");
386+
/// ```
387+
#[must_use]
388+
pub fn peek_keyword<K: ?Sized>(&mut self, keyword: &K) -> Option<&Ident>
389+
where
390+
Ident: PartialEq<K>,
391+
{
392+
self.peek_n_keyword(0, keyword)
393+
}
394+
395+
/// Returns the nth token if it matches the specified keyword without
396+
/// advancing the parser.
397+
///
398+
/// While this is called `peek_n_keyword` it is not restricted to rust
399+
/// keywords, it can be used with any ident.
400+
/// ```
401+
/// # use proc_macro_utils::TokenParser;
402+
/// # use quote::quote;
403+
/// let mut parser = TokenParser::new(quote!( in out ));
404+
/// assert_eq!(parser.peek_keyword("in").unwrap().to_string(), "in");
405+
/// assert_eq!(parser.peek_n_keyword(1, "out").unwrap().to_string(), "out");
406+
/// assert!(parser.peek_keyword("out").is_none());
407+
/// ```
408+
#[must_use]
409+
pub fn peek_n_keyword<K: ?Sized>(&mut self, n: usize, keyword: &K) -> Option<&Ident>
410+
where
411+
Ident: PartialEq<K>,
412+
{
413+
self.peek_n_ident(n).filter(|&ident| ident == keyword)
414+
}
415+
372416
/// Returns the next ident if it matches the specified keyword.
373417
///
374418
/// While this is called `next_keyword` it is not restricted to rust

0 commit comments

Comments
 (0)