use parsec_base::Span;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Token {
pub kind: Kind,
pub flags: Flags,
pub span: Span,
}
impl Token {
pub fn text(self, src: &str) -> &str {
self.span.text(src)
}
pub fn newline_before(self) -> bool {
self.flags.contains(Flags::NEWLINE_BEFORE)
}
pub fn is_trivia(self) -> bool {
self.kind.is_trivia()
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Flags(u8);
impl Flags {
pub const NEWLINE_BEFORE: Flags = Flags(1);
pub const ESCAPED: Flags = Flags(2);
pub const LEGACY_OCTAL: Flags = Flags(4);
pub const INVALID_ESCAPE: Flags = Flags(8);
pub const fn empty() -> Flags {
Flags(0)
}
pub const fn contains(self, other: Flags) -> bool {
self.0 & other.0 == other.0
}
pub const fn union(self, other: Flags) -> Flags {
Flags(self.0 | other.0)
}
pub fn insert(&mut self, other: Flags) {
self.0 |= other.0;
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Kind {
Eof,
Hashbang,
LineComment,
BlockComment,
HtmlOpenComment,
HtmlCloseComment,
Ident,
Keyword(Keyword),
PrivateName,
Number,
BigInt,
String,
Template,
TemplateHead,
TemplateMiddle,
TemplateTail,
RegExp,
Punct(Punct),
Invalid,
}
impl Kind {
pub const fn is_trivia(self) -> bool {
matches!(
self,
Kind::Hashbang
| Kind::LineComment
| Kind::BlockComment
| Kind::HtmlOpenComment
| Kind::HtmlCloseComment
)
}
}
macro_rules! words {
($(#[$m:meta])* $name:ident { $($variant:ident = $text:literal,)* }) => {
$(#[$m])*
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum $name {
$($variant,)*
}
impl $name {
#[allow(dead_code)] pub(crate) const ALL: &'static [$name] = &[$($name::$variant,)*];
pub const fn as_str(self) -> &'static str {
match self {
$($name::$variant => $text,)*
}
}
#[allow(clippy::should_implement_trait)]
pub fn from_str(text: &str) -> Option<$name> {
Some(match text {
$($text => $name::$variant,)*
_ => return None,
})
}
}
};
}
words! {
Keyword {
Await = "await",
Break = "break",
Case = "case",
Catch = "catch",
Class = "class",
Const = "const",
Continue = "continue",
Debugger = "debugger",
Default = "default",
Delete = "delete",
Do = "do",
Else = "else",
Enum = "enum",
Export = "export",
Extends = "extends",
False = "false",
Finally = "finally",
For = "for",
Function = "function",
If = "if",
Import = "import",
In = "in",
Instanceof = "instanceof",
New = "new",
Null = "null",
Return = "return",
Super = "super",
Switch = "switch",
This = "this",
Throw = "throw",
True = "true",
Try = "try",
Typeof = "typeof",
Var = "var",
Void = "void",
While = "while",
With = "with",
Yield = "yield",
Let = "let",
Static = "static",
Implements = "implements",
Interface = "interface",
Package = "package",
Private = "private",
Protected = "protected",
Public = "public",
As = "as",
Async = "async",
From = "from",
Get = "get",
Meta = "meta",
Of = "of",
Set = "set",
Target = "target",
}
}
impl Keyword {
pub const fn is_reserved(self) -> bool {
(self as u8) <= (Keyword::Yield as u8)
}
pub(crate) fn from_bytes(b: &[u8]) -> Option<Keyword> {
if !(2..=10).contains(&b.len()) {
return None;
}
let k = KEYWORDS[keyword_hash(b)]?;
(k.as_str().as_bytes() == b).then_some(k)
}
#[inline(always)]
pub(crate) fn from_prefix(rest: &[u8], len: usize) -> Option<Keyword> {
let word = rest.get(..len)?;
if !(2..=10).contains(&len) {
return None;
}
let h = keyword_hash(word);
let k = KEYWORDS[h]?;
let same = match rest.first_chunk::<16>() {
Some(chunk) => {
u128::from_le_bytes(*chunk) & (u128::MAX >> (128 - 8 * len)) == SPELLINGS[h]
}
None => {
let text = k.as_bytes();
text.len() == len && text.iter().zip(word).all(|(x, y)| x == y)
}
};
same.then_some(k)
}
fn as_bytes(self) -> &'static [u8] {
TEXT[self as usize]
}
pub const fn is_strict_reserved(self) -> bool {
(self as u8) > (Keyword::Yield as u8) && (self as u8) <= (Keyword::Public as u8)
}
}
const fn keyword_hash(b: &[u8]) -> usize {
(b[0] as usize + b[1] as usize * 6 + b[b.len() - 1] as usize * 21 + b.len()) & 255
}
static KEYWORDS: [Option<Keyword>; 256] = {
let mut table = [None; 256];
let mut i = 0;
while i < Keyword::ALL.len() {
let k = Keyword::ALL[i];
let h = keyword_hash(k.as_str().as_bytes());
assert!(table[h].is_none(), "two keywords share a hash");
table[h] = Some(k);
i += 1;
}
table
};
static TEXT: [&[u8]; Keyword::ALL.len()] = {
let mut table: [&[u8]; Keyword::ALL.len()] = [&[]; Keyword::ALL.len()];
let mut i = 0;
while i < Keyword::ALL.len() {
table[i] = Keyword::ALL[i].as_str().as_bytes();
i += 1;
}
table
};
static SPELLINGS: [u128; 256] = {
let mut table = [0; 256];
let mut i = 0;
while i < 256 {
if let Some(k) = KEYWORDS[i] {
let b = k.as_str().as_bytes();
let mut j = 0;
while j < b.len() {
table[i] |= (b[j] as u128) << (8 * j);
j += 1;
}
}
i += 1;
}
table
};
words! {
Punct {
LBrace = "{",
RBrace = "}",
LParen = "(",
RParen = ")",
LBracket = "[",
RBracket = "]",
Dot = ".",
Ellipsis = "...",
Semicolon = ";",
Comma = ",",
Lt = "<",
Gt = ">",
LtEq = "<=",
GtEq = ">=",
EqEq = "==",
NotEq = "!=",
EqEqEq = "===",
NotEqEq = "!==",
Plus = "+",
Minus = "-",
Star = "*",
Slash = "/",
Percent = "%",
StarStar = "**",
PlusPlus = "++",
MinusMinus = "--",
Shl = "<<",
Shr = ">>",
UShr = ">>>",
Amp = "&",
Pipe = "|",
Caret = "^",
Bang = "!",
Tilde = "~",
AmpAmp = "&&",
PipePipe = "||",
QuestionQuestion = "??",
Question = "?",
QuestionDot = "?.",
Colon = ":",
Eq = "=",
PlusEq = "+=",
MinusEq = "-=",
StarEq = "*=",
SlashEq = "/=",
PercentEq = "%=",
StarStarEq = "**=",
ShlEq = "<<=",
ShrEq = ">>=",
UShrEq = ">>>=",
AmpEq = "&=",
PipeEq = "|=",
CaretEq = "^=",
AmpAmpEq = "&&=",
PipePipeEq = "||=",
QuestionQuestionEq = "??=",
Arrow = "=>",
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keywords_by_hash() {
for &k in Keyword::ALL {
assert_eq!(Keyword::from_bytes(k.as_str().as_bytes()), Some(k));
assert_eq!(k.as_bytes(), k.as_str().as_bytes());
for after in ["", " ", "(", "x", " "] {
for pad in ["", " "] {
let s = format!("{}{after}{pad}", k.as_str());
let len = k.as_str().len();
assert_eq!(Keyword::from_prefix(s.as_bytes(), len), Some(k), "{s:?}");
}
}
}
for word in [
"",
"a",
"x",
"lets",
"yiel",
"constructor",
"Await",
"awaiT",
"of_",
"ofs",
] {
assert_eq!(
Keyword::from_bytes(word.as_bytes()),
Keyword::from_str(word),
"{word}"
);
for pad in ["", " ", " "] {
let s = format!("{word}{pad}");
assert_eq!(
Keyword::from_prefix(s.as_bytes(), word.len()),
Keyword::from_str(word),
"{s:?}"
);
}
}
}
}