use std::borrow::Cow;
use crate::diagnostic::Diagnostic;
use crate::span::{FileId, Span};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TokenKind {
Ident,
Int,
Float,
Str,
Char,
Punct(Punct),
Other,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(missing_docs)]
#[non_exhaustive]
pub enum Punct {
LParen,
RParen,
LBracket,
RBracket,
LBrace,
RBrace,
Semi,
Comma,
Dot,
Colon,
Question,
Tilde,
Bang,
Plus,
Minus,
Star,
Slash,
Percent,
Caret,
Amp,
Pipe,
Eq,
Lt,
Gt,
PlusPlus,
MinusMinus,
PlusEq,
MinusEq,
StarEq,
SlashEq,
PercentEq,
CaretEq,
AmpEq,
PipeEq,
ShlEq,
ShrEq,
Shl,
Shr,
EqEq,
NotEq,
LtEq,
GtEq,
AndAnd,
OrOr,
Hash,
HashHash,
ColonColon,
Arrow,
Ellipsis,
}
const PUNCTS: [(&str, Punct); 49] = [
("<<=", Punct::ShlEq),
("...", Punct::Ellipsis),
(">>=", Punct::ShrEq),
("##", Punct::HashHash),
("::", Punct::ColonColon),
("->", Punct::Arrow),
("++", Punct::PlusPlus),
("--", Punct::MinusMinus),
("+=", Punct::PlusEq),
("-=", Punct::MinusEq),
("*=", Punct::StarEq),
("/=", Punct::SlashEq),
("%=", Punct::PercentEq),
("^=", Punct::CaretEq),
("&=", Punct::AmpEq),
("|=", Punct::PipeEq),
("<<", Punct::Shl),
(">>", Punct::Shr),
("==", Punct::EqEq),
("!=", Punct::NotEq),
("<=", Punct::LtEq),
(">=", Punct::GtEq),
("&&", Punct::AndAnd),
("||", Punct::OrOr),
("(", Punct::LParen),
(")", Punct::RParen),
("[", Punct::LBracket),
("]", Punct::RBracket),
("{", Punct::LBrace),
("}", Punct::RBrace),
(";", Punct::Semi),
(",", Punct::Comma),
(".", Punct::Dot),
(":", Punct::Colon),
("?", Punct::Question),
("~", Punct::Tilde),
("!", Punct::Bang),
("+", Punct::Plus),
("-", Punct::Minus),
("*", Punct::Star),
("/", Punct::Slash),
("%", Punct::Percent),
("^", Punct::Caret),
("&", Punct::Amp),
("|", Punct::Pipe),
("=", Punct::Eq),
("<", Punct::Lt),
(">", Punct::Gt),
("#", Punct::Hash),
];
impl Punct {
pub fn as_str(self) -> &'static str {
PUNCTS
.iter()
.find(|(_, p)| *p == self)
.map_or("", |(s, _)| s)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Token {
pub kind: TokenKind,
pub text: String,
pub span: Span,
pub space_before: bool,
pub line_start: bool,
pub expanded_from: Option<Span>,
}
impl Token {
pub fn site(&self) -> Span {
self.expanded_from.unwrap_or(self.span)
}
pub fn is(&self, punct: Punct) -> bool {
self.kind == TokenKind::Punct(punct)
}
pub fn is_word(&self, word: &str) -> bool {
self.kind == TokenKind::Ident && self.text == word
}
}
pub fn lex(file: FileId, text: &str, diagnostics: &mut Vec<Diagnostic>) -> Vec<Token> {
let spliced = Spliced::new(text);
let span = |start: usize, end: usize| spliced.span(file, start, end);
let text: &str = &spliced.text;
let bytes = text.as_bytes();
let mut tokens = Vec::new();
let mut i = if text.starts_with('\u{FEFF}') { 3 } else { 0 };
let mut space = false;
let mut line_start = true;
while i < bytes.len() {
let b = bytes[i];
let next = bytes.get(i + 1).copied();
match b {
b'\n' => {
line_start = true;
space = true;
i += 1;
continue;
}
b' ' | b'\t' | b'\r' | 0x0b | 0x0c => {
space = true;
i += 1;
continue;
}
b'/' if next == Some(b'/') => {
while i < bytes.len() && bytes[i] != b'\n' {
i += 1;
}
space = true;
continue;
}
b'/' if next == Some(b'*') => {
match text[i + 2..].find("*/") {
Some(end) => i += end + 4,
None => {
diagnostics.push(Diagnostic::error(
span(i, i + 2),
"this comment has no closing `*/`",
));
i = bytes.len();
}
}
space = true;
continue;
}
_ => {}
}
let start = i;
let kind = if is_ident_start(b) {
while i < bytes.len() && is_ident_continue(bytes[i]) {
i += 1;
}
TokenKind::Ident
} else if b.is_ascii_digit() || (b == b'.' && next.is_some_and(|n| n.is_ascii_digit())) {
let (end, float) = scan_number(bytes, i);
i = end;
if float {
TokenKind::Float
} else {
TokenKind::Int
}
} else if b == b'"' {
i = scan_string(bytes, i);
if i <= start + 1 || bytes[i - 1] != b'"' {
diagnostics.push(Diagnostic::error(
span(start, i),
"this string has no closing quote",
));
}
TokenKind::Str
} else if let Some(end) = (b == b'\'').then(|| scan_char(bytes, i)).flatten() {
i = end;
TokenKind::Char
} else if let Some((s, punct)) = PUNCTS
.iter()
.find(|(s, _)| bytes[i..].starts_with(s.as_bytes()))
{
i += s.len();
TokenKind::Punct(*punct)
} else {
i += text[i..].chars().next().map_or(1, char::len_utf8);
TokenKind::Other
};
tokens.push(Token {
kind,
text: text[start..i].to_string(),
span: span(start, i),
space_before: space,
line_start,
expanded_from: None,
});
space = false;
line_start = false;
}
tokens
}
struct Spliced<'a> {
text: Cow<'a, str>,
marks: Vec<(usize, usize)>,
}
impl Spliced<'_> {
fn new(text: &str) -> Spliced<'_> {
let bytes = text.as_bytes();
let mut out = String::new();
let mut marks = Vec::new();
let mut copied = 0;
let mut i = 0;
while i < bytes.len() {
let len = match (bytes[i], bytes.get(i + 1), bytes.get(i + 2)) {
(b'\\', Some(b'\n'), _) => 2,
(b'\\', Some(b'\r'), Some(b'\n')) => 3,
_ => 0,
};
if len == 0 {
i += 1;
continue;
}
out.push_str(&text[copied..i]);
i += len;
copied = i;
marks.push((out.len(), i - out.len()));
}
if marks.is_empty() {
return Spliced {
text: Cow::Borrowed(text),
marks,
};
}
out.push_str(&text[copied..]);
Spliced {
text: Cow::Owned(out),
marks,
}
}
fn original(&self, offset: usize) -> usize {
let n = self.marks.partition_point(|(at, _)| *at <= offset);
offset + n.checked_sub(1).map_or(0, |n| self.marks[n].1)
}
fn span(&self, file: FileId, start: usize, end: usize) -> Span {
let end = if end > start {
self.original(end - 1) + 1
} else {
self.original(end)
};
Span::new(file, self.original(start), end)
}
}
fn is_ident_start(b: u8) -> bool {
b.is_ascii_alphabetic() || b == b'_'
}
fn is_ident_continue(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
}
fn scan_number(b: &[u8], mut i: usize) -> (usize, bool) {
let at = |i: usize| b.get(i).copied().unwrap_or(0);
if at(i) == b'0' && matches!(at(i + 1), b'b' | b'B') && at(i + 2).is_ascii_digit() {
i += 2;
while is_ident_continue(at(i)) {
i += 1;
}
return (i, false);
}
if at(i) == b'0' && matches!(at(i + 1), b'x' | b'X') && at(i + 2).is_ascii_hexdigit() {
i += 2;
while at(i).is_ascii_hexdigit() {
i += 1;
}
let mut exponent = i;
if at(exponent) == b'.' {
exponent += 1;
while at(exponent).is_ascii_hexdigit() {
exponent += 1;
}
}
if matches!(at(exponent), b'p' | b'P') {
i = exponent + 1;
if matches!(at(i), b'+' | b'-') {
i += 1;
}
while is_ident_continue(at(i)) {
i += 1;
}
return (i, true);
}
while matches!(at(i), b'u' | b'U' | b'l' | b'L') {
i += 1;
}
return (i, false);
}
let mut float = false;
while at(i).is_ascii_digit() {
i += 1;
}
if at(i) == b'.' {
float = true;
i += 1;
while at(i).is_ascii_digit() {
i += 1;
}
}
if matches!(at(i), b'e' | b'E') {
let digits = if matches!(at(i + 1), b'+' | b'-') {
i + 2
} else {
i + 1
};
float = true;
i = digits;
if at(i).is_ascii_digit() {
while at(i).is_ascii_digit() {
i += 1;
}
} else {
while is_ident_continue(at(i)) {
i += 1;
}
return (i, float);
}
}
while matches!(at(i), b'f' | b'F' | b'h' | b'H' | b'l' | b'L' | b'u' | b'U') {
float |= matches!(at(i), b'f' | b'F' | b'h' | b'H');
i += 1;
}
(i, float)
}
pub(crate) fn is_valid_number(text: &str) -> bool {
let int_suffix = |s: &str| matches!(s, "" | "u" | "l" | "ul" | "lu" | "ll" | "ull" | "llu");
let lower = text.to_ascii_lowercase();
if lower.starts_with("0b") {
return false;
}
if let Some(hex) = lower.strip_prefix("0x") {
let digits = hex.trim_end_matches(['u', 'l']);
return digits.bytes().all(|b| b.is_ascii_hexdigit()) && int_suffix(&hex[digits.len()..]);
}
let body = lower.trim_end_matches(['f', 'h', 'l', 'u']);
let suffix = &lower[body.len()..];
if let Some((_, exponent)) = body.split_once('e') {
let digits = exponent.strip_prefix(['+', '-']).unwrap_or(exponent);
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
return false;
}
}
if body.contains(['.', 'e']) || suffix.contains(['f', 'h']) {
matches!(suffix, "" | "f" | "h" | "l")
} else {
int_suffix(suffix)
}
}
fn scan_string(b: &[u8], mut i: usize) -> usize {
i += 1;
while i < b.len() && b[i] != b'\n' {
match b[i] {
b'"' => return i + 1,
b'\\' if i + 1 < b.len() && b[i + 1] != b'\n' => i += 2,
_ => i += 1,
}
}
i
}
fn scan_char(b: &[u8], i: usize) -> Option<usize> {
let mut j = i + 1;
while j < b.len() && b[j] != b'\n' {
match b[j] {
b'\'' => return (j > i + 1).then_some(j + 1),
b'\\' if j + 1 < b.len() && b[j + 1] != b'\n' => j += 2,
_ => j += 1,
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
fn kinds(text: &str) -> Vec<(TokenKind, String)> {
let mut d = Vec::new();
let tokens = lex(FileId(0), text, &mut d);
assert!(d.is_empty(), "{d:?}");
tokens.into_iter().map(|t| (t.kind, t.text)).collect()
}
#[test]
fn numbers_keep_their_suffixes_and_kinds() {
let k = kinds("1 1.0 .5 2. 1e3 1e-3f 0x1Fu 10u 1.0h 3f 1.5L");
let expected = [
(TokenKind::Int, "1"),
(TokenKind::Float, "1.0"),
(TokenKind::Float, ".5"),
(TokenKind::Float, "2."),
(TokenKind::Float, "1e3"),
(TokenKind::Float, "1e-3f"),
(TokenKind::Int, "0x1Fu"),
(TokenKind::Int, "10u"),
(TokenKind::Float, "1.0h"),
(TokenKind::Float, "3f"),
(TokenKind::Float, "1.5L"),
];
let expected: Vec<_> = expected.iter().map(|(k, s)| (*k, s.to_string())).collect();
assert_eq!(k, expected);
}
#[test]
fn a_malformed_exponent_stays_in_the_number() {
let k = kinds("1e+x 2e 3E-;");
let expected = [
(TokenKind::Float, "1e+x"),
(TokenKind::Float, "2e"),
(TokenKind::Float, "3E-"),
(TokenKind::Punct(Punct::Semi), ";"),
];
let expected: Vec<_> = expected.iter().map(|(k, s)| (*k, s.to_string())).collect();
assert_eq!(k, expected);
assert!(!is_valid_number("1e+x") && is_valid_number("1e-3f"));
}
#[test]
fn hex_floats_and_binary_literals_are_one_token_but_not_valid_numbers() {
let k = kinds("0x1.8p3 0x1p-4 0X1P+4f 0x1p 0b1010 0B11u 0x1.b");
let expected = [
(TokenKind::Float, "0x1.8p3"),
(TokenKind::Float, "0x1p-4"),
(TokenKind::Float, "0X1P+4f"),
(TokenKind::Float, "0x1p"),
(TokenKind::Int, "0b1010"),
(TokenKind::Int, "0B11u"),
(TokenKind::Int, "0x1"),
(TokenKind::Punct(Punct::Dot), "."),
(TokenKind::Ident, "b"),
];
let expected: Vec<_> = expected.iter().map(|(k, s)| (*k, s.to_string())).collect();
assert_eq!(k, expected);
for (_, text) in &k[..6] {
assert!(!is_valid_number(text), "{text}");
}
for text in [
"0x1F", "0x1Ful", "10lu", "5ll", "5ull", "1.5L", "2h", "1e-3f",
] {
assert!(is_valid_number(text), "{text}");
}
}
#[test]
fn longest_punctuation_wins() {
let k = kinds("a<<=b>>c##d->e::f...g");
let texts: Vec<_> = k.iter().map(|(_, s)| s.as_str()).collect();
assert_eq!(
texts,
[
"a", "<<=", "b", ">>", "c", "##", "d", "->", "e", "::", "f", "...", "g"
]
);
}
#[test]
fn comments_are_space_and_block_comments_do_not_end_a_line() {
let mut d = Vec::new();
let t = lex(FileId(0), "a // x\nb/* y\n z */c", &mut d);
assert!(d.is_empty());
let flags: Vec<_> = t
.iter()
.map(|t| (t.text.as_str(), t.line_start, t.space_before))
.collect();
assert_eq!(
flags,
[("a", true, false), ("b", true, true), ("c", false, true)]
);
}
#[test]
fn a_continuation_joins_lines() {
let mut d = Vec::new();
let t = lex(FileId(0), "#define A 1 \\\r\n + 2\nB", &mut d);
let starts: Vec<_> = t
.iter()
.filter(|t| t.line_start)
.map(|t| t.text.as_str())
.collect();
assert_eq!(starts, ["#", "B"]);
}
#[test]
fn a_continuation_extends_a_line_comment() {
let mut d = Vec::new();
let t = lex(FileId(0), "// note \\\n#define A 1\nA", &mut d);
let texts: Vec<_> = t.iter().map(|t| t.text.as_str()).collect();
assert_eq!(texts, ["A"]);
}
#[test]
fn a_continuation_inside_a_token_is_spliced_and_spans_keep_the_source() {
let text = "flo\\\nat4 +\\\r\n= \"ab\\\ncd\" 1.\\\n5";
let mut d = Vec::new();
let t = lex(FileId(0), text, &mut d);
assert!(d.is_empty(), "{d:?}");
let texts: Vec<_> = t.iter().map(|t| t.text.as_str()).collect();
assert_eq!(texts, ["float4", "+=", "\"abcd\"", "1.5"]);
let source: Vec<_> = t
.iter()
.map(|t| &text[t.span.start as usize..t.span.end as usize])
.collect();
assert_eq!(
source,
["flo\\\nat4", "+\\\r\n=", "\"ab\\\ncd\"", "1.\\\n5"]
);
assert!(t.iter().skip(1).all(|t| t.space_before && !t.line_start));
}
#[test]
fn a_continuation_before_a_parenthesis_adds_no_space() {
let mut d = Vec::new();
let t = lex(FileId(0), "F\\\n(x)", &mut d);
assert!(!t[1].space_before);
}
#[test]
fn strings_and_unknown_characters() {
let k = kinds(r#""a\"b" @ é"#);
assert_eq!(k[0], (TokenKind::Str, r#""a\"b""#.to_string()));
assert_eq!(k[1], (TokenKind::Other, "@".to_string()));
assert_eq!(k[2], (TokenKind::Other, "é".to_string()));
}
#[test]
fn character_literals_are_one_token_and_hide_comment_marks() {
let k = kinds(r"'a' '\n' '\'' '/*' x");
let expected = [
(TokenKind::Char, "'a'"),
(TokenKind::Char, r"'\n'"),
(TokenKind::Char, r"'\''"),
(TokenKind::Char, "'/*'"),
(TokenKind::Ident, "x"),
];
let expected: Vec<_> = expected.iter().map(|(k, s)| (*k, s.to_string())).collect();
assert_eq!(k, expected);
}
#[test]
fn a_quote_without_a_closing_quote_is_an_unknown_character() {
let k = kinds("don't\n''");
let kinds: Vec<_> = k.iter().map(|(k, _)| *k).collect();
assert_eq!(
kinds,
[
TokenKind::Ident,
TokenKind::Other,
TokenKind::Ident,
TokenKind::Other,
TokenKind::Other
]
);
}
#[test]
fn unterminated_comment_and_string_are_errors() {
let mut d = Vec::new();
lex(FileId(0), "\"abc\n/* x", &mut d);
assert_eq!(d.len(), 2);
}
#[test]
fn spans_cover_the_token_text() {
let mut d = Vec::new();
let t = lex(FileId(3), " float4", &mut d);
assert_eq!(t[0].span, Span::new(FileId(3), 2, 8));
assert_eq!(Punct::ShlEq.as_str(), "<<=");
}
}