diff options
Diffstat (limited to 'crates/ra_syntax/src/parsing/input.rs')
-rw-r--r-- | crates/ra_syntax/src/parsing/input.rs | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/crates/ra_syntax/src/parsing/input.rs b/crates/ra_syntax/src/parsing/input.rs new file mode 100644 index 000000000..96c03bb11 --- /dev/null +++ b/crates/ra_syntax/src/parsing/input.rs | |||
@@ -0,0 +1,68 @@ | |||
1 | use crate::{ | ||
2 | SyntaxKind, SyntaxKind::EOF, TextRange, TextUnit, | ||
3 | parsing::{ | ||
4 | TokenSource, | ||
5 | lexer::Token, | ||
6 | }, | ||
7 | }; | ||
8 | |||
9 | impl<'t> TokenSource for ParserInput<'t> { | ||
10 | fn token_kind(&self, pos: usize) -> SyntaxKind { | ||
11 | if !(pos < self.tokens.len()) { | ||
12 | return EOF; | ||
13 | } | ||
14 | self.tokens[pos].kind | ||
15 | } | ||
16 | fn is_token_joint_to_next(&self, pos: usize) -> bool { | ||
17 | if !(pos + 1 < self.tokens.len()) { | ||
18 | return true; | ||
19 | } | ||
20 | self.start_offsets[pos] + self.tokens[pos].len == self.start_offsets[pos + 1] | ||
21 | } | ||
22 | fn is_keyword(&self, pos: usize, kw: &str) -> bool { | ||
23 | if !(pos < self.tokens.len()) { | ||
24 | return false; | ||
25 | } | ||
26 | let range = TextRange::offset_len(self.start_offsets[pos], self.tokens[pos].len); | ||
27 | |||
28 | self.text[range] == *kw | ||
29 | } | ||
30 | } | ||
31 | |||
32 | pub(crate) struct ParserInput<'t> { | ||
33 | text: &'t str, | ||
34 | /// start position of each token(expect whitespace and comment) | ||
35 | /// ```non-rust | ||
36 | /// struct Foo; | ||
37 | /// ^------^--- | ||
38 | /// | | ^- | ||
39 | /// 0 7 10 | ||
40 | /// ``` | ||
41 | /// (token, start_offset): `[(struct, 0), (Foo, 7), (;, 10)]` | ||
42 | start_offsets: Vec<TextUnit>, | ||
43 | /// non-whitespace/comment tokens | ||
44 | /// ```non-rust | ||
45 | /// struct Foo {} | ||
46 | /// ^^^^^^ ^^^ ^^ | ||
47 | /// ``` | ||
48 | /// tokens: `[struct, Foo, {, }]` | ||
49 | tokens: Vec<Token>, | ||
50 | } | ||
51 | |||
52 | impl<'t> ParserInput<'t> { | ||
53 | /// Generate input from tokens(expect comment and whitespace). | ||
54 | pub fn new(text: &'t str, raw_tokens: &'t [Token]) -> ParserInput<'t> { | ||
55 | let mut tokens = Vec::new(); | ||
56 | let mut start_offsets = Vec::new(); | ||
57 | let mut len = 0.into(); | ||
58 | for &token in raw_tokens.iter() { | ||
59 | if !token.kind.is_trivia() { | ||
60 | tokens.push(token); | ||
61 | start_offsets.push(len); | ||
62 | } | ||
63 | len += token.len; | ||
64 | } | ||
65 | |||
66 | ParserInput { text, start_offsets, tokens } | ||
67 | } | ||
68 | } | ||