diff options
Diffstat (limited to 'crates/ra_mbe/src/tt_cursor.rs')
-rw-r--r-- | crates/ra_mbe/src/tt_cursor.rs | 91 |
1 files changed, 91 insertions, 0 deletions
diff --git a/crates/ra_mbe/src/tt_cursor.rs b/crates/ra_mbe/src/tt_cursor.rs new file mode 100644 index 000000000..30c8eda67 --- /dev/null +++ b/crates/ra_mbe/src/tt_cursor.rs | |||
@@ -0,0 +1,91 @@ | |||
1 | #[derive(Clone)] | ||
2 | pub(crate) struct TtCursor<'a> { | ||
3 | subtree: &'a tt::Subtree, | ||
4 | pos: usize, | ||
5 | } | ||
6 | |||
7 | impl<'a> TtCursor<'a> { | ||
8 | pub(crate) fn new(subtree: &'a tt::Subtree) -> TtCursor<'a> { | ||
9 | TtCursor { subtree, pos: 0 } | ||
10 | } | ||
11 | |||
12 | pub(crate) fn is_eof(&self) -> bool { | ||
13 | self.pos == self.subtree.token_trees.len() | ||
14 | } | ||
15 | |||
16 | pub(crate) fn current(&self) -> Option<&'a tt::TokenTree> { | ||
17 | self.subtree.token_trees.get(self.pos) | ||
18 | } | ||
19 | |||
20 | pub(crate) fn at_punct(&self) -> Option<&'a tt::Punct> { | ||
21 | match self.current() { | ||
22 | Some(tt::TokenTree::Leaf(tt::Leaf::Punct(it))) => Some(it), | ||
23 | _ => None, | ||
24 | } | ||
25 | } | ||
26 | |||
27 | pub(crate) fn at_char(&self, char: char) -> bool { | ||
28 | match self.at_punct() { | ||
29 | Some(tt::Punct { char: c, .. }) if *c == char => true, | ||
30 | _ => false, | ||
31 | } | ||
32 | } | ||
33 | |||
34 | pub(crate) fn at_ident(&mut self) -> Option<&'a tt::Ident> { | ||
35 | match self.current() { | ||
36 | Some(tt::TokenTree::Leaf(tt::Leaf::Ident(i))) => Some(i), | ||
37 | _ => None, | ||
38 | } | ||
39 | } | ||
40 | |||
41 | pub(crate) fn bump(&mut self) { | ||
42 | self.pos += 1; | ||
43 | } | ||
44 | pub(crate) fn rev_bump(&mut self) { | ||
45 | self.pos -= 1; | ||
46 | } | ||
47 | |||
48 | pub(crate) fn eat(&mut self) -> Option<&'a tt::TokenTree> { | ||
49 | match self.current() { | ||
50 | Some(it) => { | ||
51 | self.bump(); | ||
52 | Some(it) | ||
53 | } | ||
54 | None => None, | ||
55 | } | ||
56 | } | ||
57 | |||
58 | pub(crate) fn eat_subtree(&mut self) -> Option<&'a tt::Subtree> { | ||
59 | match self.current()? { | ||
60 | tt::TokenTree::Subtree(sub) => { | ||
61 | self.bump(); | ||
62 | Some(sub) | ||
63 | } | ||
64 | _ => return None, | ||
65 | } | ||
66 | } | ||
67 | |||
68 | pub(crate) fn eat_punct(&mut self) -> Option<&'a tt::Punct> { | ||
69 | if let Some(it) = self.at_punct() { | ||
70 | self.bump(); | ||
71 | return Some(it); | ||
72 | } | ||
73 | None | ||
74 | } | ||
75 | |||
76 | pub(crate) fn eat_ident(&mut self) -> Option<&'a tt::Ident> { | ||
77 | if let Some(i) = self.at_ident() { | ||
78 | self.bump(); | ||
79 | return Some(i); | ||
80 | } | ||
81 | None | ||
82 | } | ||
83 | |||
84 | pub(crate) fn expect_char(&mut self, char: char) -> Option<()> { | ||
85 | if self.at_char(char) { | ||
86 | self.bump(); | ||
87 | return Some(()); | ||
88 | } | ||
89 | None | ||
90 | } | ||
91 | } | ||