rust/crates/parser/src/token_set.rs

43 lines
967 B
Rust
Raw Normal View History

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