]> git.lizzy.rs Git - rust.git/blob - crates/parser/src/tokens.rs
use eof token pattenr
[rust.git] / crates / parser / src / tokens.rs
1 use crate::SyntaxKind;
2
3 type bits = u64;
4
5 pub type IdentKind = u8;
6
7 /// Main input to the parser.
8 ///
9 /// A sequence of tokens represented internally as a struct of arrays.
10 #[derive(Default)]
11 pub struct Tokens {
12     kind: Vec<SyntaxKind>,
13     joint: Vec<bits>,
14     ident_kind: Vec<IdentKind>,
15 }
16
17 impl Tokens {
18     pub fn push(&mut self, was_joint: bool, kind: SyntaxKind) {
19         self.push_impl(was_joint, kind, 0)
20     }
21     pub fn push_ident(&mut self, ident_kind: IdentKind) {
22         self.push_impl(false, SyntaxKind::IDENT, ident_kind)
23     }
24     fn push_impl(&mut self, was_joint: bool, kind: SyntaxKind, ctx: IdentKind) {
25         let idx = self.len();
26         if idx % (bits::BITS as usize) == 0 {
27             self.joint.push(0);
28         }
29         if was_joint && idx > 0 {
30             self.set_joint(idx - 1);
31         }
32         self.kind.push(kind);
33         self.ident_kind.push(ctx);
34     }
35     fn set_joint(&mut self, n: usize) {
36         let (idx, b_idx) = self.bit_index(n);
37         self.joint[idx] |= 1 << b_idx;
38     }
39     fn get_joint(&self, n: usize) -> bool {
40         let (idx, b_idx) = self.bit_index(n);
41         self.joint[idx] & 1 << b_idx != 0
42     }
43     fn bit_index(&self, n: usize) -> (usize, usize) {
44         let idx = n / (bits::BITS as usize);
45         let b_idx = n % (bits::BITS as usize);
46         (idx, b_idx)
47     }
48
49     pub fn len(&self) -> usize {
50         self.kind.len()
51     }
52     pub(crate) fn get(&self, idx: usize) -> (SyntaxKind, bool, IdentKind) {
53         if idx > self.len() {
54             return self.eof();
55         }
56         let kind = self.kind[idx];
57         let joint = self.get_joint(idx);
58         let ident_kind = self.ident_kind[idx];
59         (kind, joint, ident_kind)
60     }
61
62     #[cold]
63     fn eof(&self) -> (SyntaxKind, bool, IdentKind) {
64         (SyntaxKind::EOF, false, 0)
65     }
66 }