Skip to content

Commit 69fe457

Browse files
committed
internal: simplify TokenSet implementation
1 parent 8e45912 commit 69fe457

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

crates/parser/src/token_set.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ use crate::SyntaxKind;
66
#[derive(Clone, Copy)]
77
pub(crate) struct TokenSet([u64; 3]);
88

9+
/// `TokenSet`s should only include token `SyntaxKind`s, so the discriminant of any passed/included
10+
/// `SyntaxKind` must *not* be greater than that of the last token `SyntaxKind`.
11+
/// See #17037.
912
const LAST_TOKEN_KIND_DISCRIMINANT: usize = SyntaxKind::SHEBANG as usize;
1013

1114
impl TokenSet {
@@ -15,13 +18,13 @@ impl TokenSet {
1518
let mut res = [0; 3];
1619
let mut i = 0;
1720
while i < kinds.len() {
18-
let kind = kinds[i];
21+
let discriminant = kinds[i] as usize;
1922
debug_assert!(
20-
kind as usize <= LAST_TOKEN_KIND_DISCRIMINANT,
23+
discriminant <= LAST_TOKEN_KIND_DISCRIMINANT,
2124
"Expected a token `SyntaxKind`"
2225
);
23-
let idx = kind as usize / 64;
24-
res[idx] |= mask(kind);
26+
let idx = discriminant / 64;
27+
res[idx] |= 1 << (discriminant % 64);
2528
i += 1;
2629
}
2730
TokenSet(res)
@@ -32,20 +35,17 @@ impl TokenSet {
3235
}
3336

3437
pub(crate) const fn contains(&self, kind: SyntaxKind) -> bool {
38+
let discriminant = kind as usize;
3539
debug_assert!(
36-
kind as usize <= LAST_TOKEN_KIND_DISCRIMINANT,
40+
discriminant <= LAST_TOKEN_KIND_DISCRIMINANT,
3741
"Expected a token `SyntaxKind`"
3842
);
39-
let idx = kind as usize / 64;
40-
self.0[idx] & mask(kind) != 0
43+
let idx = discriminant / 64;
44+
let mask = 1 << (discriminant % 64);
45+
self.0[idx] & mask != 0
4146
}
4247
}
4348

44-
const fn mask(kind: SyntaxKind) -> u64 {
45-
debug_assert!(kind as usize <= LAST_TOKEN_KIND_DISCRIMINANT, "Expected a token `SyntaxKind`");
46-
1 << (kind as usize % 64)
47-
}
48-
4949
#[test]
5050
fn token_set_works_for_tokens() {
5151
use crate::SyntaxKind::*;

0 commit comments

Comments
 (0)