rust/crates/parser/src/token_set.rs

43 lines
987 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
pub(crate) const fn singleton(kind: SyntaxKind) -> TokenSet {
2019-01-18 02:02:30 -06:00
TokenSet(mask(kind))
}
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
pub(crate) 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
}
#[macro_export]
2019-01-18 02:02:30 -06:00
macro_rules! token_set {
2019-12-19 10:13:08 -06:00
($($t:expr),*) => { TokenSet::EMPTY$(.union(TokenSet::singleton($t)))* };
2019-11-14 08:36:27 -06:00
($($t:expr),* ,) => { token_set!($($t),*) };
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::*;
2019-02-21 03:05:52 -06:00
let ts = token_set![EOF, SHEBANG];
2018-09-06 08:54:54 -05:00
assert!(ts.contains(EOF));
assert!(ts.contains(SHEBANG));
assert!(!ts.contains(PLUS));
}