diff options
Diffstat (limited to 'crates/mbe/src/tt_iter.rs')
-rw-r--r-- | crates/mbe/src/tt_iter.rs | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/crates/mbe/src/tt_iter.rs b/crates/mbe/src/tt_iter.rs new file mode 100644 index 000000000..46c420718 --- /dev/null +++ b/crates/mbe/src/tt_iter.rs | |||
@@ -0,0 +1,75 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | #[derive(Debug, Clone)] | ||
4 | pub(crate) struct TtIter<'a> { | ||
5 | pub(crate) inner: std::slice::Iter<'a, tt::TokenTree>, | ||
6 | } | ||
7 | |||
8 | impl<'a> TtIter<'a> { | ||
9 | pub(crate) fn new(subtree: &'a tt::Subtree) -> TtIter<'a> { | ||
10 | TtIter { inner: subtree.token_trees.iter() } | ||
11 | } | ||
12 | |||
13 | pub(crate) fn expect_char(&mut self, char: char) -> Result<(), ()> { | ||
14 | match self.next() { | ||
15 | Some(tt::TokenTree::Leaf(tt::Leaf::Punct(tt::Punct { char: c, .. }))) if *c == char => { | ||
16 | Ok(()) | ||
17 | } | ||
18 | _ => Err(()), | ||
19 | } | ||
20 | } | ||
21 | |||
22 | pub(crate) fn expect_subtree(&mut self) -> Result<&'a tt::Subtree, ()> { | ||
23 | match self.next() { | ||
24 | Some(tt::TokenTree::Subtree(it)) => Ok(it), | ||
25 | _ => Err(()), | ||
26 | } | ||
27 | } | ||
28 | |||
29 | pub(crate) fn expect_leaf(&mut self) -> Result<&'a tt::Leaf, ()> { | ||
30 | match self.next() { | ||
31 | Some(tt::TokenTree::Leaf(it)) => Ok(it), | ||
32 | _ => Err(()), | ||
33 | } | ||
34 | } | ||
35 | |||
36 | pub(crate) fn expect_ident(&mut self) -> Result<&'a tt::Ident, ()> { | ||
37 | match self.expect_leaf()? { | ||
38 | tt::Leaf::Ident(it) => Ok(it), | ||
39 | _ => Err(()), | ||
40 | } | ||
41 | } | ||
42 | |||
43 | pub(crate) fn expect_literal(&mut self) -> Result<&'a tt::Leaf, ()> { | ||
44 | let it = self.expect_leaf()?; | ||
45 | match it { | ||
46 | tt::Leaf::Literal(_) => Ok(it), | ||
47 | tt::Leaf::Ident(ident) if ident.text == "true" || ident.text == "false" => Ok(it), | ||
48 | _ => Err(()), | ||
49 | } | ||
50 | } | ||
51 | |||
52 | pub(crate) fn expect_punct(&mut self) -> Result<&'a tt::Punct, ()> { | ||
53 | match self.expect_leaf()? { | ||
54 | tt::Leaf::Punct(it) => Ok(it), | ||
55 | _ => Err(()), | ||
56 | } | ||
57 | } | ||
58 | |||
59 | pub(crate) fn peek_n(&self, n: usize) -> Option<&tt::TokenTree> { | ||
60 | self.inner.as_slice().get(n) | ||
61 | } | ||
62 | } | ||
63 | |||
64 | impl<'a> Iterator for TtIter<'a> { | ||
65 | type Item = &'a tt::TokenTree; | ||
66 | fn next(&mut self) -> Option<Self::Item> { | ||
67 | self.inner.next() | ||
68 | } | ||
69 | |||
70 | fn size_hint(&self) -> (usize, Option<usize>) { | ||
71 | self.inner.size_hint() | ||
72 | } | ||
73 | } | ||
74 | |||
75 | impl<'a> std::iter::ExactSizeIterator for TtIter<'a> {} | ||