2019-02-21 10:37:32 +00:00
|
|
|
use ra_parser::TokenSource;
|
|
|
|
|
2019-02-20 12:47:32 +00:00
|
|
|
use crate::{
|
|
|
|
SyntaxKind, SyntaxKind::EOF, TextRange, TextUnit,
|
2019-02-21 10:37:32 +00:00
|
|
|
parsing::lexer::Token,
|
2019-02-20 12:47:32 +00:00
|
|
|
};
|
2018-02-04 11:35:59 +00:00
|
|
|
|
2019-02-21 12:24:42 +00:00
|
|
|
pub(crate) struct ParserInput<'t> {
|
|
|
|
text: &'t str,
|
|
|
|
/// start position of each token(expect whitespace and comment)
|
|
|
|
/// ```non-rust
|
|
|
|
/// struct Foo;
|
|
|
|
/// ^------^---
|
|
|
|
/// | | ^-
|
|
|
|
/// 0 7 10
|
|
|
|
/// ```
|
|
|
|
/// (token, start_offset): `[(struct, 0), (Foo, 7), (;, 10)]`
|
|
|
|
start_offsets: Vec<TextUnit>,
|
|
|
|
/// non-whitespace/comment tokens
|
|
|
|
/// ```non-rust
|
|
|
|
/// struct Foo {}
|
|
|
|
/// ^^^^^^ ^^^ ^^
|
|
|
|
/// ```
|
|
|
|
/// tokens: `[struct, Foo, {, }]`
|
|
|
|
tokens: Vec<Token>,
|
|
|
|
}
|
|
|
|
|
2019-02-20 18:50:07 +00:00
|
|
|
impl<'t> TokenSource for ParserInput<'t> {
|
2019-02-20 19:58:56 +00:00
|
|
|
fn token_kind(&self, pos: usize) -> SyntaxKind {
|
|
|
|
if !(pos < self.tokens.len()) {
|
2019-02-20 18:50:07 +00:00
|
|
|
return EOF;
|
|
|
|
}
|
2019-02-20 19:58:56 +00:00
|
|
|
self.tokens[pos].kind
|
2019-02-20 18:50:07 +00:00
|
|
|
}
|
2019-02-20 19:58:56 +00:00
|
|
|
fn is_token_joint_to_next(&self, pos: usize) -> bool {
|
|
|
|
if !(pos + 1 < self.tokens.len()) {
|
2019-02-20 18:50:07 +00:00
|
|
|
return true;
|
|
|
|
}
|
2019-02-20 19:58:56 +00:00
|
|
|
self.start_offsets[pos] + self.tokens[pos].len == self.start_offsets[pos + 1]
|
2019-02-20 18:50:07 +00:00
|
|
|
}
|
2019-02-20 19:58:56 +00:00
|
|
|
fn is_keyword(&self, pos: usize, kw: &str) -> bool {
|
|
|
|
if !(pos < self.tokens.len()) {
|
2019-02-20 18:50:07 +00:00
|
|
|
return false;
|
|
|
|
}
|
2019-02-20 19:58:56 +00:00
|
|
|
let range = TextRange::offset_len(self.start_offsets[pos], self.tokens[pos].len);
|
2019-02-20 18:50:07 +00:00
|
|
|
|
|
|
|
self.text[range] == *kw
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-04 11:35:59 +00:00
|
|
|
impl<'t> ParserInput<'t> {
|
2018-12-31 13:30:37 +00:00
|
|
|
/// Generate input from tokens(expect comment and whitespace).
|
2018-02-04 11:35:59 +00:00
|
|
|
pub fn new(text: &'t str, raw_tokens: &'t [Token]) -> ParserInput<'t> {
|
|
|
|
let mut tokens = Vec::new();
|
|
|
|
let mut start_offsets = Vec::new();
|
2018-07-28 10:07:10 +00:00
|
|
|
let mut len = 0.into();
|
2018-02-04 11:35:59 +00:00
|
|
|
for &token in raw_tokens.iter() {
|
2018-07-29 12:16:07 +00:00
|
|
|
if !token.kind.is_trivia() {
|
2018-02-04 11:35:59 +00:00
|
|
|
tokens.push(token);
|
|
|
|
start_offsets.push(len);
|
|
|
|
}
|
|
|
|
len += token.len;
|
|
|
|
}
|
|
|
|
|
2019-02-08 11:49:43 +00:00
|
|
|
ParserInput { text, start_offsets, tokens }
|
2018-02-04 11:35:59 +00:00
|
|
|
}
|
|
|
|
}
|