use crate::span::ByteSpan;
#[must_use]
pub const fn is_whitespace(b: u8) -> bool {
matches!(b, 0x00 | 0x09 | 0x0A | 0x0C | 0x0D | 0x20)
}
#[must_use]
pub const fn is_delimiter(b: u8) -> bool {
matches!(
b,
b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%'
)
}
#[must_use]
pub const fn is_regular(b: u8) -> bool {
!is_whitespace(b) && !is_delimiter(b)
}
pub const MAX_TOKEN_LEN: usize = 1024 * 1024;
pub const MAX_STRING_LEN: usize = 16 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq)]
pub struct Token {
pub kind: TokenKind,
pub span: ByteSpan,
}
impl Token {
#[must_use]
pub fn lexeme<'a>(&self, buf: &'a [u8]) -> Option<&'a [u8]> {
self.span.slice(buf)
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum TokenKind {
Integer(i64),
Real(f64),
String(Vec<u8>),
Name(Vec<u8>),
ArrayOpen,
ArrayClose,
DictOpen,
DictClose,
BraceOpen,
BraceClose,
Keyword,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("lex error at byte {offset}: {kind}")]
pub struct LexError {
pub offset: usize,
pub kind: LexErrorKind,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum LexErrorKind {
#[error("unterminated literal string")]
UnterminatedString,
#[error("unterminated hexadecimal string")]
UnterminatedHexString,
#[error("invalid byte 0x{0:02X} in hexadecimal string")]
InvalidHexStringByte(u8),
#[error("malformed #-escape in name")]
MalformedNameEscape,
#[error("#00 (NUL) escape in name")]
NulInName,
#[error("unexpected delimiter byte 0x{0:02X}")]
UnexpectedByte(u8),
#[error("integer token overflows i64")]
IntegerOverflow,
#[error("token exceeds MAX_TOKEN_LEN ({MAX_TOKEN_LEN} bytes)")]
TokenTooLong,
#[error("string exceeds MAX_STRING_LEN ({MAX_STRING_LEN} bytes)")]
StringTooLong,
}
#[derive(Debug, Clone)]
pub struct Lexer<'a> {
buf: &'a [u8],
pos: usize,
}
impl<'a> Lexer<'a> {
#[must_use]
pub const fn new(buf: &'a [u8]) -> Self {
Self { buf, pos: 0 }
}
#[must_use]
pub const fn at(buf: &'a [u8], pos: usize) -> Self {
Self { buf, pos }
}
#[must_use]
pub const fn pos(&self) -> usize {
self.pos
}
pub fn next_token(&mut self) -> Result<Option<Token>, LexError> {
self.skip_ws_and_comments();
let start = self.pos;
let Some(b) = self.peek() else {
return Ok(None);
};
let kind = match b {
b'[' => {
self.bump();
TokenKind::ArrayOpen
}
b']' => {
self.bump();
TokenKind::ArrayClose
}
b'{' => {
self.bump();
TokenKind::BraceOpen
}
b'}' => {
self.bump();
TokenKind::BraceClose
}
b'<' => {
if self.peek_at(1) == Some(b'<') {
self.bump();
self.bump();
TokenKind::DictOpen
} else {
self.bump();
TokenKind::String(self.scan_hex_string_body()?)
}
}
b'>' => {
if self.peek_at(1) == Some(b'>') {
self.bump();
self.bump();
TokenKind::DictClose
} else {
return Err(self.err_at(start, LexErrorKind::UnexpectedByte(b'>')));
}
}
b'(' => {
self.bump();
TokenKind::String(self.scan_literal_string_body()?)
}
b')' => {
return Err(self.err_at(start, LexErrorKind::UnexpectedByte(b')')));
}
b'/' => {
self.bump();
TokenKind::Name(self.scan_name_body()?)
}
_ => {
debug_assert!(is_regular(b));
self.scan_regular_run(start)?
}
};
Ok(Some(Token {
kind,
span: ByteSpan::from_range(start..self.pos),
}))
}
fn peek(&self) -> Option<u8> {
self.buf.get(self.pos).copied()
}
fn peek_at(&self, ahead: usize) -> Option<u8> {
self.buf.get(self.pos.saturating_add(ahead)).copied()
}
fn bump(&mut self) {
self.pos = self.pos.saturating_add(1);
}
fn err_here(&self, kind: LexErrorKind) -> LexError {
LexError {
offset: self.pos,
kind,
}
}
fn err_at(&self, offset: usize, kind: LexErrorKind) -> LexError {
LexError { offset, kind }
}
fn skip_ws_and_comments(&mut self) {
while let Some(b) = self.peek() {
if is_whitespace(b) {
self.bump();
} else if b == b'%' {
self.bump();
while let Some(c) = self.peek() {
if c == b'\r' || c == b'\n' {
break;
}
self.bump();
}
} else {
break;
}
}
}
fn scan_literal_string_body(&mut self) -> Result<Vec<u8>, LexError> {
let mut out = Vec::new();
let mut depth: usize = 1;
loop {
if out.len() > MAX_STRING_LEN {
return Err(self.err_here(LexErrorKind::StringTooLong));
}
let Some(b) = self.peek() else {
return Err(self.err_here(LexErrorKind::UnterminatedString));
};
self.bump();
match b {
b'(' => {
depth += 1;
out.push(b'(');
}
b')' => {
depth -= 1;
if depth == 0 {
return Ok(out);
}
out.push(b')');
}
b'\\' => {
let Some(e) = self.peek() else {
return Err(self.err_here(LexErrorKind::UnterminatedString));
};
match e {
b'n' => {
self.bump();
out.push(0x0A);
}
b'r' => {
self.bump();
out.push(0x0D);
}
b't' => {
self.bump();
out.push(0x09);
}
b'b' => {
self.bump();
out.push(0x08);
}
b'f' => {
self.bump();
out.push(0x0C);
}
b'(' | b')' | b'\\' => {
self.bump();
out.push(e);
}
b'0'..=b'7' => {
let mut value: u32 = 0;
let mut digits = 0;
while digits < 3 {
match self.peek() {
Some(d @ b'0'..=b'7') => {
self.bump();
value = (value << 3) | u32::from(d - b'0');
digits += 1;
}
_ => break,
}
}
#[allow(clippy::cast_possible_truncation)] out.push((value & 0xFF) as u8);
}
b'\r' => {
self.bump();
if self.peek() == Some(b'\n') {
self.bump();
}
}
b'\n' => {
self.bump();
}
_ => {
self.bump();
out.push(e);
}
}
}
b'\r' => {
if self.peek() == Some(b'\n') {
self.bump();
}
out.push(0x0A);
}
_ => out.push(b),
}
}
}
fn scan_hex_string_body(&mut self) -> Result<Vec<u8>, LexError> {
let mut out = Vec::new();
let mut pending: Option<u8> = None;
loop {
if out.len() > MAX_STRING_LEN {
return Err(self.err_here(LexErrorKind::StringTooLong));
}
let Some(b) = self.peek() else {
return Err(self.err_here(LexErrorKind::UnterminatedHexString));
};
if b == b'>' {
self.bump();
if let Some(hi) = pending {
out.push(hi << 4);
}
return Ok(out);
}
if is_whitespace(b) {
self.bump();
continue;
}
let Some(nibble) = hex_value(b) else {
return Err(self.err_here(LexErrorKind::InvalidHexStringByte(b)));
};
self.bump();
match pending.take() {
Some(hi) => out.push((hi << 4) | nibble),
None => pending = Some(nibble),
}
}
}
fn scan_name_body(&mut self) -> Result<Vec<u8>, LexError> {
let mut out = Vec::new();
while let Some(b) = self.peek() {
if !is_regular(b) {
break;
}
if out.len() > MAX_TOKEN_LEN {
return Err(self.err_here(LexErrorKind::TokenTooLong));
}
self.bump();
if b == b'#' {
let hi = self.peek().and_then(hex_value);
let lo = self.peek_at(1).and_then(hex_value);
match (hi, lo) {
(Some(hi), Some(lo)) => {
self.bump();
self.bump();
let decoded = (hi << 4) | lo;
if decoded == 0 {
return Err(self.err_here(LexErrorKind::NulInName));
}
out.push(decoded);
}
_ => return Err(self.err_here(LexErrorKind::MalformedNameEscape)),
}
} else {
out.push(b);
}
}
Ok(out)
}
fn scan_regular_run(&mut self, start: usize) -> Result<TokenKind, LexError> {
while let Some(b) = self.peek() {
if !is_regular(b) {
break;
}
if self.pos.saturating_sub(start) > MAX_TOKEN_LEN {
return Err(self.err_here(LexErrorKind::TokenTooLong));
}
self.bump();
}
let run = self.buf.get(start..self.pos).unwrap_or(&[]);
Ok(match classify_number(run) {
NumberClass::Integer => TokenKind::Integer(parse_i64(run).ok_or(LexError {
offset: start,
kind: LexErrorKind::IntegerOverflow,
})?),
NumberClass::Real => {
let text = String::from_utf8_lossy(run);
text.parse::<f64>()
.map_or(TokenKind::Keyword, TokenKind::Real)
}
NumberClass::NotANumber => TokenKind::Keyword,
})
}
}
const fn hex_value(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'A'..=b'F' => Some(b - b'A' + 10),
b'a'..=b'f' => Some(b - b'a' + 10),
_ => None,
}
}
enum NumberClass {
Integer,
Real,
NotANumber,
}
fn classify_number(run: &[u8]) -> NumberClass {
let mut digits = 0usize;
let mut periods = 0usize;
for (i, &b) in run.iter().enumerate() {
match b {
b'+' | b'-' if i == 0 => {}
b'0'..=b'9' => digits += 1,
b'.' => periods += 1,
_ => return NumberClass::NotANumber,
}
}
match (digits, periods) {
(0, _) => NumberClass::NotANumber, (_, 0) => NumberClass::Integer,
(_, 1) => NumberClass::Real,
_ => NumberClass::NotANumber, }
}
fn parse_i64(run: &[u8]) -> Option<i64> {
let (neg, digits) = match run.split_first() {
Some((b'-', rest)) => (true, rest),
Some((b'+', rest)) => (false, rest),
_ => (false, run),
};
let mut value: i64 = 0;
for &b in digits {
let d = i64::from(b.checked_sub(b'0')?);
if d > 9 {
return None;
}
value = value.checked_mul(10)?.checked_add(d)?;
}
Some(if neg { -value } else { value })
}