rust-analyzer/crates/ra_mbe/src/tt_cursor.rs

90 lines
2.2 KiB
Rust
Raw Normal View History

2019-03-03 09:40:03 +00:00
use crate::ParseError;
2019-03-02 19:20:26 +00:00
2019-01-31 14:16:02 +00:00
#[derive(Clone)]
2019-01-31 12:26:01 +00:00
pub(crate) struct TtCursor<'a> {
subtree: &'a tt::Subtree,
pos: usize,
}
impl<'a> TtCursor<'a> {
pub(crate) fn new(subtree: &'a tt::Subtree) -> TtCursor<'a> {
TtCursor { subtree, pos: 0 }
}
pub(crate) fn is_eof(&self) -> bool {
self.pos == self.subtree.token_trees.len()
}
pub(crate) fn current(&self) -> Option<&'a tt::TokenTree> {
self.subtree.token_trees.get(self.pos)
}
2019-03-03 09:40:03 +00:00
pub(crate) fn at_punct(&self) -> Option<&'a tt::Punct> {
2019-01-31 12:26:01 +00:00
match self.current() {
2019-03-03 09:40:03 +00:00
Some(tt::TokenTree::Leaf(tt::Leaf::Punct(it))) => Some(it),
_ => None,
2019-01-31 12:26:01 +00:00
}
}
pub(crate) fn at_char(&self, char: char) -> bool {
match self.at_punct() {
2019-03-03 09:40:03 +00:00
Some(tt::Punct { char: c, .. }) if *c == char => true,
2019-01-31 12:26:01 +00:00
_ => false,
}
}
2019-03-03 09:40:03 +00:00
pub(crate) fn at_ident(&mut self) -> Option<&'a tt::Ident> {
2019-01-31 12:26:01 +00:00
match self.current() {
2019-03-03 09:40:03 +00:00
Some(tt::TokenTree::Leaf(tt::Leaf::Ident(i))) => Some(i),
_ => None,
2019-01-31 12:26:01 +00:00
}
}
pub(crate) fn bump(&mut self) {
self.pos += 1;
}
pub(crate) fn rev_bump(&mut self) {
self.pos -= 1;
}
2019-03-03 09:40:03 +00:00
pub(crate) fn eat(&mut self) -> Option<&'a tt::TokenTree> {
self.current().map(|it| {
self.bump();
it
})
2019-01-31 12:26:01 +00:00
}
2019-03-03 09:40:03 +00:00
pub(crate) fn eat_subtree(&mut self) -> Result<&'a tt::Subtree, ParseError> {
2019-03-02 19:20:26 +00:00
match self.current() {
Some(tt::TokenTree::Subtree(sub)) => {
2019-01-31 12:26:01 +00:00
self.bump();
2019-03-02 19:20:26 +00:00
Ok(sub)
2019-01-31 12:26:01 +00:00
}
2019-03-03 09:40:03 +00:00
_ => Err(ParseError::ParseError),
2019-01-31 12:26:01 +00:00
}
}
2019-03-03 09:40:03 +00:00
pub(crate) fn eat_punct(&mut self) -> Option<&'a tt::Punct> {
2019-03-02 19:20:26 +00:00
self.at_punct().map(|it| {
2019-01-31 12:26:01 +00:00
self.bump();
2019-03-02 19:20:26 +00:00
it
})
2019-01-31 12:26:01 +00:00
}
2019-03-03 09:40:03 +00:00
pub(crate) fn eat_ident(&mut self) -> Option<&'a tt::Ident> {
2019-03-02 19:20:26 +00:00
self.at_ident().map(|i| {
2019-01-31 12:26:01 +00:00
self.bump();
2019-03-02 19:20:26 +00:00
i
})
2019-01-31 12:26:01 +00:00
}
2019-03-03 09:40:03 +00:00
pub(crate) fn expect_char(&mut self, char: char) -> Result<(), ParseError> {
2019-01-31 12:26:01 +00:00
if self.at_char(char) {
self.bump();
2019-03-03 09:40:03 +00:00
Ok(())
} else {
Err(ParseError::ParseError)
2019-01-31 12:26:01 +00:00
}
}
}