use core::ops::Range;
pub const JOINT_NEXT: u8 = 1 << 0;
pub const HAS_ERROR: u8 = 1 << 1;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Token {
pub kind: TokenKind,
pub flags: u8,
pub start: u32,
pub end: u32,
}
const _: () = assert!(core::mem::size_of::<Token>() == 12);
impl Token {
#[inline]
pub const fn new(kind: TokenKind, flags: u8, start: u32, end: u32) -> Self {
Self { kind, flags, start, end }
}
#[inline]
pub const fn len(self) -> u32 {
self.end - self.start
}
#[inline]
pub const fn is_empty(self) -> bool {
self.start == self.end
}
#[inline]
pub const fn is_trivia(self) -> bool {
self.kind.is_trivia()
}
#[inline]
pub const fn is_joint(self) -> bool {
(self.flags & JOINT_NEXT) != 0
}
#[inline]
pub const fn has_error(self) -> bool {
(self.flags & HAS_ERROR) != 0
}
#[inline]
pub const fn range(self) -> Range<usize> {
(self.start as usize)..(self.end as usize)
}
#[inline]
pub fn text(self, src: &str) -> &str {
&src[self.range()]
}
}
#[inline]
pub fn token_at(tokens: &[Token], byte: u32) -> Option<usize> {
let idx = tokens.partition_point(|t| t.end <= byte);
if idx < tokens.len() && tokens[idx].start <= byte {
Some(idx)
} else {
None
}
}
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TokenKind {
Whitespace,
LineComment,
BlockComment,
Shebang,
Ident,
RawIdent,
Lifetime,
Int,
Float,
Char,
Byte,
Str,
RawStr,
ByteStr,
RawByteStr,
CStr,
RawCStr,
As,
Async,
Await,
Break,
Const,
Continue,
Crate,
Dyn,
Else,
Enum,
Extern,
False,
Fn,
For,
If,
Impl,
In,
Let,
Loop,
Match,
Mod,
Move,
Mut,
Pub,
Ref,
Return,
SelfKw,
SelfType,
Static,
Struct,
Super,
Trait,
True,
Type,
Unsafe,
Use,
Where,
While,
Underscore,
LParen,
RParen,
LBrace,
RBrace,
LBracket,
RBracket,
Bang,
Hash,
Dollar,
Percent,
Amp,
Star,
Plus,
Comma,
Minus,
Dot,
Slash,
Colon,
Semi,
Lt,
Eq,
Gt,
Question,
At,
Caret,
Pipe,
Tilde,
Unknown,
}
impl TokenKind {
#[inline]
pub const fn is_trivia(self) -> bool {
(self as u8) <= (Self::Shebang as u8)
}
#[inline]
pub const fn is_punct(self) -> bool {
let v = self as u8;
v >= (Self::Bang as u8) && v <= (Self::Tilde as u8)
}
#[inline]
pub const fn is_delimiter(self) -> bool {
let v = self as u8;
v >= (Self::LParen as u8) && v <= (Self::RBracket as u8)
}
#[inline]
pub const fn is_keyword(self) -> bool {
let v = self as u8;
v >= (Self::As as u8) && v <= (Self::While as u8)
}
#[inline]
pub const fn is_literal(self) -> bool {
let v = self as u8;
v >= (Self::Int as u8) && v <= (Self::RawCStr as u8)
}
#[inline]
pub const fn punct_byte(self) -> Option<u8> {
const BYTES: [u8; 21] = *b"!#$%&*+,-./:;<=>?@^|~";
let idx = (self as u8).wrapping_sub(Self::Bang as u8) as usize;
if idx < BYTES.len() {
Some(BYTES[idx])
} else {
None
}
}
}