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

222 lines
6.4 KiB
Rust
Raw Normal View History

2019-05-25 12:31:53 +00:00
use ra_parser::{TokenSource, Token};
2019-05-15 12:35:47 +00:00
use ra_syntax::{classify_literal, SmolStr, SyntaxKind, SyntaxKind::*, T};
2019-05-22 18:00:34 +00:00
use std::cell::{RefCell, Cell};
use tt::buffer::{TokenBuffer, Cursor};
2019-04-07 13:42:53 +00:00
#[derive(Debug, Clone, Eq, PartialEq)]
2019-04-07 13:42:53 +00:00
struct TtToken {
pub kind: SyntaxKind,
pub is_joint_to_next: bool,
pub text: SmolStr,
}
2019-05-27 14:56:21 +00:00
pub(crate) struct SubtreeTokenSource<'a> {
2019-05-22 18:00:34 +00:00
start: Cursor<'a>,
cursor: Cell<Cursor<'a>>,
2019-04-22 14:46:39 +00:00
cached: RefCell<Vec<Option<TtToken>>>,
2019-05-27 14:56:21 +00:00
curr: (Token, usize),
}
impl<'a> SubtreeTokenSource<'a> {
// Helper function used in test
#[allow(unused)]
pub fn text(&self) -> SmolStr {
match self.get(self.curr.1) {
Some(tt) => tt.text,
_ => SmolStr::new(""),
}
}
}
2019-05-27 14:56:21 +00:00
impl<'a> SubtreeTokenSource<'a> {
pub fn new(buffer: &'a TokenBuffer) -> SubtreeTokenSource<'a> {
let cursor = buffer.begin();
let mut res = SubtreeTokenSource {
curr: (Token { kind: EOF, is_jointed_to_next: false }, 0),
2019-05-22 18:00:34 +00:00
start: cursor,
cursor: Cell::new(cursor),
2019-04-22 14:46:39 +00:00
cached: RefCell::new(Vec::with_capacity(10)),
2019-05-27 14:56:21 +00:00
};
res.curr = (res.mk_token(0), 0);
res
}
pub(crate) fn bump_n(&mut self, parsed_tokens: usize) -> Vec<tt::TokenTree> {
let res = self.collect_token_trees(parsed_tokens);
res
}
fn mk_token(&self, pos: usize) -> Token {
match self.get(pos) {
Some(tt) => Token { kind: tt.kind, is_jointed_to_next: tt.is_joint_to_next },
None => Token { kind: EOF, is_jointed_to_next: false },
2019-04-22 14:46:39 +00:00
}
2019-04-08 12:32:21 +00:00
}
2019-05-22 18:00:34 +00:00
fn get(&self, pos: usize) -> Option<TtToken> {
2019-04-22 14:46:39 +00:00
let mut cached = self.cached.borrow_mut();
if pos < cached.len() {
return cached[pos].clone();
}
while pos >= cached.len() {
2019-05-22 18:00:34 +00:00
let cursor = self.cursor.get();
if cursor.eof() {
cached.push(None);
continue;
}
2019-05-23 01:31:36 +00:00
2019-05-22 18:00:34 +00:00
match cursor.token_tree() {
Some(tt::TokenTree::Leaf(leaf)) => {
cached.push(Some(convert_leaf(&leaf)));
self.cursor.set(cursor.bump());
}
Some(tt::TokenTree::Subtree(subtree)) => {
self.cursor.set(cursor.subtree().unwrap());
cached.push(Some(convert_delim(subtree.delimiter, false)));
}
None => {
if let Some(subtree) = cursor.end() {
cached.push(Some(convert_delim(subtree.delimiter, true)));
self.cursor.set(cursor.bump());
}
}
}
2019-04-22 14:46:39 +00:00
}
return cached[pos].clone();
2019-04-07 13:42:53 +00:00
}
2019-05-25 12:31:53 +00:00
fn collect_token_trees(&self, n: usize) -> Vec<tt::TokenTree> {
2019-05-22 18:00:34 +00:00
let mut res = vec![];
2019-05-02 02:19:12 +00:00
2019-05-22 18:00:34 +00:00
let mut pos = 0;
let mut cursor = self.start;
let mut level = 0;
2019-04-07 13:42:53 +00:00
2019-05-22 18:00:34 +00:00
while pos < n {
if cursor.eof() {
break;
}
2019-05-22 18:00:34 +00:00
match cursor.token_tree() {
Some(tt::TokenTree::Leaf(leaf)) => {
if level == 0 {
res.push(leaf.into());
}
2019-05-22 18:00:34 +00:00
cursor = cursor.bump();
pos += 1;
2019-05-02 02:19:12 +00:00
}
2019-05-22 18:00:34 +00:00
Some(tt::TokenTree::Subtree(subtree)) => {
if level == 0 {
res.push(subtree.into());
}
2019-05-22 18:00:34 +00:00
pos += 1;
level += 1;
cursor = cursor.subtree().unwrap();
}
2019-05-22 18:00:34 +00:00
None => {
if let Some(_) = cursor.end() {
level -= 1;
pos += 1;
cursor = cursor.bump();
}
}
}
2019-04-07 13:42:53 +00:00
}
res
}
}
2019-04-07 13:42:53 +00:00
impl<'a> TokenSource for SubtreeTokenSource<'a> {
2019-05-25 12:31:53 +00:00
fn current(&self) -> Token {
self.curr.0
2019-04-07 13:42:53 +00:00
}
2019-05-25 12:31:53 +00:00
/// Lookahead n token
fn lookahead_nth(&self, n: usize) -> Token {
self.mk_token(self.curr.1 + n)
}
/// bump cursor to next token
fn bump(&mut self) {
if self.current().kind == EOF {
return;
}
2019-05-25 12:31:53 +00:00
self.curr = (self.mk_token(self.curr.1 + 1), self.curr.1 + 1)
2019-04-07 13:42:53 +00:00
}
2019-05-25 12:31:53 +00:00
/// Is the current token a specified keyword?
fn is_keyword(&self, kw: &str) -> bool {
2019-05-27 14:56:21 +00:00
match self.get(self.curr.1) {
Some(t) => t.text == *kw,
_ => false,
}
2019-04-07 13:42:53 +00:00
}
}
fn convert_delim(d: tt::Delimiter, closing: bool) -> TtToken {
let (kinds, texts) = match d {
2019-05-15 12:35:47 +00:00
tt::Delimiter::Parenthesis => ([T!['('], T![')']], "()"),
tt::Delimiter::Brace => ([T!['{'], T!['}']], "{}"),
tt::Delimiter::Bracket => ([T!['['], T![']']], "[]"),
tt::Delimiter::None => ([L_DOLLAR, R_DOLLAR], ""),
};
let idx = closing as usize;
let kind = kinds[idx];
let text = if texts.len() > 0 { &texts[idx..texts.len() - (1 - idx)] } else { "" };
2019-05-02 02:19:12 +00:00
TtToken { kind, is_joint_to_next: false, text: SmolStr::new(text) }
}
2019-04-07 13:42:53 +00:00
fn convert_literal(l: &tt::Literal) -> TtToken {
2019-04-25 18:56:44 +00:00
let kind =
classify_literal(&l.text).map(|tkn| tkn.kind).unwrap_or_else(|| match l.text.as_ref() {
2019-05-15 12:35:47 +00:00
"true" => T![true],
"false" => T![false],
2019-04-25 18:56:44 +00:00
_ => panic!("Fail to convert given literal {:#?}", &l),
});
2019-04-24 15:01:32 +00:00
2019-05-02 02:19:12 +00:00
TtToken { kind, is_joint_to_next: false, text: l.text.clone() }
}
2019-04-07 13:42:53 +00:00
fn convert_ident(ident: &tt::Ident) -> TtToken {
let kind = if let Some('\'') = ident.text.chars().next() {
LIFETIME
} else {
SyntaxKind::from_keyword(ident.text.as_str()).unwrap_or(IDENT)
};
2019-05-02 02:19:12 +00:00
TtToken { kind, is_joint_to_next: false, text: ident.text.clone() }
}
2019-04-07 13:42:53 +00:00
2019-05-02 02:19:12 +00:00
fn convert_punct(p: &tt::Punct) -> TtToken {
let kind = match p.char {
// lexer may produce compound tokens for these ones
2019-05-15 12:35:47 +00:00
'.' => T![.],
':' => T![:],
'=' => T![=],
'!' => T![!],
'-' => T![-],
2019-05-02 02:19:12 +00:00
c => SyntaxKind::from_char(c).unwrap(),
};
let text = {
let mut buf = [0u8; 4];
let s: &str = p.char.encode_utf8(&mut buf);
SmolStr::new(s)
};
TtToken { kind, is_joint_to_next: p.spacing == tt::Spacing::Joint, text }
2019-04-07 13:42:53 +00:00
}
2019-05-02 02:19:12 +00:00
fn convert_leaf(leaf: &tt::Leaf) -> TtToken {
match leaf {
tt::Leaf::Literal(l) => convert_literal(l),
tt::Leaf::Ident(ident) => convert_ident(ident),
2019-05-02 02:19:12 +00:00
tt::Leaf::Punct(punct) => convert_punct(punct),
}
}