use std::borrow::Cow;
use std::ops::Range;
#[derive(Debug, Clone, PartialEq)]
pub(super) struct Token<'a> {
pub(super) tok: Tok<'a>,
pub(super) span: Range<usize>,
}
#[derive(Debug, Clone, PartialEq)]
pub(super) enum Tok<'a> {
Ident(&'a str),
Str(Cow<'a, str>),
Bytes,
Int(i64),
Uint(u64),
Double(f64),
OrOr,
AndAnd,
Not,
EqEq,
Ne,
Lt,
Le,
Gt,
Ge,
Minus,
Dot,
Comma,
LParen,
RParen,
LBracket,
RBracket,
Question,
Colon,
Plus,
Other,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct LexError {
pub(super) span: Range<usize>,
pub(super) why: &'static str,
}
pub(super) fn tokens(text: &str) -> Result<Vec<Token<'_>>, LexError> {
let bytes = text.as_bytes();
let mut out = Vec::new();
let mut i = 0;
while i < bytes.len() {
let b = bytes[i];
let start = i;
if b.is_ascii_whitespace() {
i += 1;
continue;
}
if bytes[i..].starts_with(b"//") {
i = memchr::memchr(b'\n', &bytes[i..]).map_or(bytes.len(), |n| i + n);
continue;
}
let tok = if is_quote(b) {
let (tok, end) = string(text, i, Quoting::Escaped, Kind::Text)?;
i = end;
tok
} else if b.is_ascii_digit()
|| (b == b'.' && bytes.get(i + 1).is_some_and(u8::is_ascii_digit))
{
let (tok, end) = number(text, i)?;
i = end;
tok
} else if is_ident_start(b) {
while i < bytes.len() && is_ident_char(bytes[i]) {
i += 1;
}
let word = &text[start..i];
match bytes.get(i) {
Some(&q) if is_quote(q) && is_literal_prefix(word.as_bytes()) => {
let has = |c: u8| word.bytes().any(|w| w.eq_ignore_ascii_case(&c));
let quoting = if has(b'r') {
Quoting::Raw
} else {
Quoting::Escaped
};
let kind = if has(b'b') { Kind::Bytes } else { Kind::Text };
let (tok, end) = string(text, i, quoting, kind)?;
i = end;
tok
}
_ => Tok::Ident(word),
}
} else if b == b'`' {
let body = bytes[i + 1..]
.iter()
.take_while(|c| is_escaped_ident_byte(**c))
.count();
if body == 0 || bytes.get(i + 1 + body) != Some(&b'`') {
return Err(LexError {
span: i..i + 1,
why: "a backtick that opens no quoted identifier",
});
}
i += body + 2;
Tok::Ident(&text[start + 1..i - 1])
} else {
let (tok, n) = punct(&bytes[i..]);
i += if tok == Tok::Other {
text[i..].chars().next().map_or(1, char::len_utf8)
} else {
n
};
tok
};
out.push(Token {
tok,
span: start..i,
});
}
Ok(out)
}
fn punct(rest: &[u8]) -> (Tok<'static>, usize) {
match rest.get(..2).unwrap_or_default() {
b"||" => return (Tok::OrOr, 2),
b"&&" => return (Tok::AndAnd, 2),
b"==" => return (Tok::EqEq, 2),
b"!=" => return (Tok::Ne, 2),
b"<=" => return (Tok::Le, 2),
b">=" => return (Tok::Ge, 2),
_ => {}
}
let tok = match rest.first() {
Some(b'!') => Tok::Not,
Some(b'<') => Tok::Lt,
Some(b'>') => Tok::Gt,
Some(b'-') => Tok::Minus,
Some(b'.') => Tok::Dot,
Some(b',') => Tok::Comma,
Some(b'(') => Tok::LParen,
Some(b')') => Tok::RParen,
Some(b'[') => Tok::LBracket,
Some(b']') => Tok::RBracket,
Some(b'?') => Tok::Question,
Some(b':') => Tok::Colon,
Some(b'+') => Tok::Plus,
_ => Tok::Other,
};
(tok, 1)
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Quoting {
Escaped,
Raw,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
Text,
Bytes,
}
fn string(
text: &str,
at: usize,
quoting: Quoting,
kind: Kind,
) -> Result<(Tok<'_>, usize), LexError> {
let bytes = text.as_bytes();
let quote = bytes[at];
let triple = bytes[at..].starts_with(&[quote; 3]);
let open = if triple { 3 } else { 1 };
let body_start = at + open;
let mut i = body_start;
let mut escaped = false;
let body_end = loop {
let Some(&b) = bytes.get(i) else {
return Err(LexError {
span: at..bytes.len(),
why: "a string literal with no closing quote",
});
};
if triple && bytes[i..].starts_with(&[quote; 3]) || !triple && b == quote {
break i;
}
if !triple && (b == b'\n' || b == b'\r') {
return Err(LexError {
span: at..i,
why: "a line break inside a one-line string literal",
});
}
if quoting == Quoting::Escaped && b == b'\\' {
escaped = true;
i += 2;
} else {
i += 1;
}
};
let end = body_end + open;
if kind == Kind::Bytes {
return Ok((Tok::Bytes, end));
}
let body = &text[body_start..body_end.min(bytes.len())];
if !escaped {
return Ok((Tok::Str(Cow::Borrowed(body)), end));
}
unescape(body, body_start).map(|s| (Tok::Str(Cow::Owned(s)), end))
}
fn unescape(body: &str, offset: usize) -> Result<String, LexError> {
let mut out = String::with_capacity(body.len());
let mut chars = body.char_indices();
while let Some((at, c)) = chars.next() {
if c != '\\' {
out.push(c);
continue;
}
let escaped = chars.clone().next().map_or(0, |(_, e)| e.len_utf8());
let bad = |why| LexError {
span: offset + at..offset + at + 1 + escaped,
why,
};
let Some((_, e)) = chars.next() else {
return Err(bad("a backslash at the end of a string literal"));
};
let simple = match e {
'\\' => Some('\\'),
'?' => Some('?'),
'"' => Some('"'),
'\'' => Some('\''),
'`' => Some('`'),
'a' => Some('\x07'),
'b' => Some('\x08'),
'f' => Some('\x0c'),
'n' => Some('\n'),
'r' => Some('\r'),
't' => Some('\t'),
'v' => Some('\x0b'),
_ => None,
};
if let Some(s) = simple {
out.push(s);
continue;
}
let (digits, radix, mut value) = match e {
'x' | 'X' => (2, 16, 0),
'u' => (4, 16, 0),
'U' => (8, 16, 0),
'0'..='3' => (2, 8, e.to_digit(8).unwrap_or(0)),
_ => return Err(bad("an escape CEL doesn't define")),
};
for _ in 0..digits {
let Some(d) = chars.next().and_then(|(_, d)| d.to_digit(radix)) else {
return Err(bad("an escape with too few digits"));
};
value = value * radix + d;
}
let Some(ch) = char::from_u32(value) else {
return Err(bad("an escape naming no Unicode scalar value"));
};
out.push(ch);
}
Ok(out)
}
fn number(text: &str, at: usize) -> Result<(Tok<'_>, usize), LexError> {
let bytes = text.as_bytes();
let bad = |end: usize, why| LexError { span: at..end, why };
if bytes[at..].starts_with(b"0x") || bytes[at..].starts_with(b"0X") {
let digits = bytes[at + 2..]
.iter()
.take_while(|b| b.is_ascii_hexdigit())
.count();
let end = at + 2 + digits;
let v = u64::from_str_radix(&text[at + 2..end], 16)
.map_err(|_| bad(end, "a hex literal with no digits or out of range"))?;
return int_token(v, bytes.get(end), end)
.ok_or_else(|| bad(end, "an int literal out of range"));
}
let digits = |mut i: usize| {
while bytes.get(i).is_some_and(u8::is_ascii_digit) {
i += 1;
}
i
};
let mut i = digits(at);
let mut double = false;
if bytes.get(i) == Some(&b'.') && bytes.get(i + 1).is_some_and(u8::is_ascii_digit) {
double = true;
i = digits(i + 1);
}
if matches!(bytes.get(i), Some(b'e' | b'E')) {
let sign = usize::from(matches!(bytes.get(i + 1), Some(b'+' | b'-')));
if bytes.get(i + 1 + sign).is_some_and(u8::is_ascii_digit) {
double = true;
i = digits(i + 1 + sign);
}
}
if double {
let v: f64 = text[at..i]
.parse()
.map_err(|_| bad(i, "a malformed double literal"))?;
return Ok((Tok::Double(v), i));
}
let v: u64 = text[at..i]
.parse()
.map_err(|_| bad(i, "an int literal out of range"))?;
int_token(v, bytes.get(i), i).ok_or_else(|| bad(i, "an int literal out of range"))
}
fn int_token(v: u64, next: Option<&u8>, end: usize) -> Option<(Tok<'static>, usize)> {
if matches!(next, Some(b'u' | b'U')) {
return Some((Tok::Uint(v), end + 1));
}
i64::try_from(v).ok().map(|n| (Tok::Int(n), end))
}
const fn is_quote(b: u8) -> bool {
b == b'"' || b == b'\''
}
fn is_literal_prefix(word: &[u8]) -> bool {
matches!(word.len(), 1 | 2)
&& word
.iter()
.all(|c| matches!(c.to_ascii_lowercase(), b'r' | b'b'))
&& !(word.len() == 2 && word[0].eq_ignore_ascii_case(&word[1]))
}
const fn is_ident_start(b: u8) -> bool {
b.is_ascii_alphabetic() || b == b'_'
}
const fn is_ident_char(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
}
const fn is_escaped_ident_byte(b: u8) -> bool {
b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-' | b'/' | b' ')
}