rust/crates/parser/src/token_set.rs

43 lines
968 B
Rust
Raw Normal View History

2019-12-19 17:13:08 +01:00
//! A bit-set of `SyntaxKind`s.
2018-10-15 19:55:32 +03:00
use crate::SyntaxKind;
2018-09-06 21:54:54 +08:00
2019-02-21 15:24:42 +03:00
/// A bit-set of `SyntaxKind`s
2018-09-06 21:54:54 +08:00
#[derive(Clone, Copy)]
2019-01-18 11:02:30 +03:00
pub(crate) struct TokenSet(u128);
2018-09-06 21:54:54 +08:00
impl TokenSet {
2019-12-19 17:13:08 +01:00
pub(crate) const EMPTY: TokenSet = TokenSet(0);
2019-01-18 11:02:30 +03:00
2020-08-27 18:11:33 +02:00
pub(crate) const fn new(kinds: &[SyntaxKind]) -> TokenSet {
let mut res = 0u128;
let mut i = 0;
while i < kinds.len() {
res |= mask(kinds[i]);
i += 1;
2020-08-27 18:11:33 +02:00
}
TokenSet(res)
2019-01-18 11:02:30 +03:00
}
pub(crate) const fn union(self, other: TokenSet) -> TokenSet {
2019-01-18 11:02:30 +03:00
TokenSet(self.0 | other.0)
}
2018-09-06 21:54:54 +08:00
2020-08-27 18:11:33 +02:00
pub(crate) const fn contains(&self, kind: SyntaxKind) -> bool {
2018-09-06 21:54:54 +08:00
self.0 & mask(kind) != 0
}
}
2019-01-18 11:02:30 +03:00
const fn mask(kind: SyntaxKind) -> u128 {
1u128 << (kind as usize)
2018-09-06 21:54:54 +08:00
}
#[test]
fn token_set_works_for_tokens() {
2018-10-15 19:55:32 +03:00
use crate::SyntaxKind::*;
2020-08-27 18:11:33 +02:00
let ts = TokenSet::new(&[EOF, SHEBANG]);
2018-09-06 21:54:54 +08:00
assert!(ts.contains(EOF));
assert!(ts.contains(SHEBANG));
assert!(!ts.contains(PLUS));
}