aboutsummaryrefslogtreecommitdiff
path: root/src/parser/input.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/parser/input.rs')
-rw-r--r--src/parser/input.rs77
1 files changed, 77 insertions, 0 deletions
diff --git a/src/parser/input.rs b/src/parser/input.rs
new file mode 100644
index 000000000..162b9ef5f
--- /dev/null
+++ b/src/parser/input.rs
@@ -0,0 +1,77 @@
1use {SyntaxKind, TextRange, TextUnit, Token};
2use syntax_kinds::EOF;
3use super::is_insignificant;
4
5use std::ops::{Add, AddAssign};
6
7pub(crate) struct ParserInput<'t> {
8 #[allow(unused)]
9 text: &'t str,
10 #[allow(unused)]
11 start_offsets: Vec<TextUnit>,
12 tokens: Vec<Token>, // non-whitespace tokens
13}
14
15impl<'t> ParserInput<'t> {
16 pub fn new(text: &'t str, raw_tokens: &'t [Token]) -> ParserInput<'t> {
17 let mut tokens = Vec::new();
18 let mut start_offsets = Vec::new();
19 let mut len = TextUnit::new(0);
20 for &token in raw_tokens.iter() {
21 if !is_insignificant(token.kind) {
22 tokens.push(token);
23 start_offsets.push(len);
24 }
25 len += token.len;
26 }
27
28 ParserInput {
29 text,
30 start_offsets,
31 tokens,
32 }
33 }
34
35 pub fn kind(&self, pos: InputPosition) -> SyntaxKind {
36 let idx = pos.0 as usize;
37 if !(idx < self.tokens.len()) {
38 return EOF;
39 }
40 self.tokens[idx].kind
41 }
42
43 #[allow(unused)]
44 pub fn text(&self, pos: InputPosition) -> &'t str {
45 let idx = pos.0 as usize;
46 if !(idx < self.tokens.len()) {
47 return "";
48 }
49 let start_offset = self.start_offsets[idx];
50 let end_offset = self.tokens[idx].len;
51 let range = TextRange::from_to(start_offset, end_offset);
52 &self.text[range]
53 }
54}
55
56#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
57pub(crate) struct InputPosition(u32);
58
59impl InputPosition {
60 pub fn new() -> Self {
61 InputPosition(0)
62 }
63}
64
65impl Add<u32> for InputPosition {
66 type Output = InputPosition;
67
68 fn add(self, rhs: u32) -> InputPosition {
69 InputPosition(self.0 + rhs)
70 }
71}
72
73impl AddAssign<u32> for InputPosition {
74 fn add_assign(&mut self, rhs: u32) {
75 self.0 += rhs
76 }
77}