#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CodeTokenKind {
Accent,
Comment,
Keyword,
String,
Symbol,
Type,
}
impl CodeTokenKind {
pub(crate) fn class_name(self) -> &'static str {
match self {
Self::Accent => "ui-code__token--accent",
Self::Comment => "ui-code__token--comment",
Self::Keyword => "ui-code__token--keyword",
Self::String => "ui-code__token--string",
Self::Symbol => "ui-code__token--symbol",
Self::Type => "ui-code__token--type",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct CodeToken {
pub(crate) kind: Option<CodeTokenKind>,
pub(crate) value: String,
}
pub(crate) fn normalize_code(code: &str) -> String {
let unified = code.replace("\r\n", "\n").replace('\r', "\n");
let lines: Vec<&str> = unified.split('\n').collect();
let Some(first) = lines.iter().position(|line| !is_blank(line)) else {
return String::new();
};
let last = lines
.iter()
.rposition(|line| !is_blank(line))
.unwrap_or(first);
let kept = lines.get(first..=last).unwrap_or_default();
let indent = kept
.iter()
.filter(|line| !is_blank(line))
.map(|line| leading_indent(line))
.min()
.unwrap_or(0);
kept.iter()
.map(|line| drop_chars(line, indent))
.collect::<Vec<_>>()
.join("\n")
}
pub(crate) fn tokenize_code(code: &str, language: &str) -> Vec<CodeToken> {
let source = normalize_code(code);
match language_family(language) {
Family::Markdown => tokenize_markdown(&source),
Family::Scanned(grammar) => tokenize_scanned(&source, grammar),
Family::Plain if source.is_empty() => Vec::new(),
Family::Plain => vec![CodeToken {
kind: None,
value: source,
}],
}
}
const JAVASCRIPT_KEYWORDS: &[&str] = &[
"as",
"async",
"await",
"break",
"case",
"catch",
"class",
"const",
"continue",
"default",
"else",
"export",
"extends",
"false",
"finally",
"for",
"from",
"function",
"if",
"import",
"in",
"interface",
"let",
"new",
"null",
"of",
"return",
"throw",
"true",
"try",
"type",
"undefined",
"var",
"while",
];
const JAVASCRIPT_TYPES: &[&str] = &[
"Array", "Boolean", "Date", "Map", "Number", "Promise", "Record", "Set", "String", "boolean",
"number", "string", "unknown", "void",
];
const BASH_KEYWORDS: &[&str] = &[
"case", "do", "done", "elif", "else", "esac", "export", "fi", "for", "function", "if", "in",
"local", "readonly", "set", "then", "unset", "while",
];
const JSON_KEYWORDS: &[&str] = &["false", "null", "true"];
const LUA_KEYWORDS: &[&str] = &[
"and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in",
"local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while",
];
const SQL_KEYWORDS: &[&str] = &[
"alter", "and", "as", "asc", "by", "create", "delete", "desc", "distinct", "drop", "from",
"group", "having", "insert", "into", "join", "limit", "not", "null", "on", "or", "order",
"select", "set", "table", "union", "update", "values", "where",
];
const YAML_KEYWORDS: &[&str] = &["false", "no", "null", "off", "on", "true", "yes"];
#[derive(Clone, Copy)]
enum Family {
Markdown,
Scanned(Grammar),
Plain,
}
#[derive(Clone, Copy)]
enum Grammar {
Bash,
Javascript,
Json,
Lua,
Markup,
Sql,
Yaml,
}
fn language_family(language: &str) -> Family {
match language
.trim_matches(is_js_whitespace)
.to_lowercase()
.as_str()
{
"md" | "markdown" | "mdx" => Family::Markdown,
"astro" | "html" | "markup" | "svg" | "vue" | "xml" => Family::Scanned(Grammar::Markup),
"js" | "jsx" | "javascript" | "mjs" | "ts" | "tsx" | "typescript" => {
Family::Scanned(Grammar::Javascript)
}
"bash" | "console" | "shell" | "sh" | "terminal" | "zsh" => Family::Scanned(Grammar::Bash),
"json" | "json5" | "jsonc" => Family::Scanned(Grammar::Json),
"lua" => Family::Scanned(Grammar::Lua),
"sql" => Family::Scanned(Grammar::Sql),
"yaml" | "yml" => Family::Scanned(Grammar::Yaml),
_ => Family::Plain,
}
}
fn is_js_whitespace(character: char) -> bool {
matches!(
character,
'\t' | '\n' | '\u{b}' | '\u{c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'
..='\u{200a}'
| '\u{2028}'
| '\u{2029}'
| '\u{202f}'
| '\u{205f}'
| '\u{3000}'
| '\u{feff}'
)
}
fn is_line_terminator(character: char) -> bool {
matches!(character, '\n' | '\r' | '\u{2028}' | '\u{2029}')
}
fn is_horizontal_whitespace(character: char) -> bool {
is_js_whitespace(character) && !is_line_terminator(character)
}
fn is_blank(line: &str) -> bool {
line.chars().all(is_js_whitespace)
}
fn leading_indent(line: &str) -> usize {
line.bytes()
.take_while(|byte| matches!(byte, b'\t' | b' '))
.count()
}
fn drop_chars(line: &str, count: usize) -> &str {
line.char_indices()
.nth(count)
.and_then(|(index, _)| line.get(index..))
.unwrap_or_default()
}
fn byte_at(bytes: &[u8], index: usize) -> Option<u8> {
bytes.get(index).copied()
}
fn char_at(source: &str, index: usize) -> Option<char> {
source.get(index..)?.chars().next()
}
fn slice(source: &str, start: usize, end: usize) -> &str {
source.get(start..end).unwrap_or_default()
}
fn starts_with_at(bytes: &[u8], index: usize, prefix: &[u8]) -> bool {
bytes
.get(index..)
.is_some_and(|rest| rest.starts_with(prefix))
}
fn is_digit(byte: u8) -> bool {
byte.is_ascii_digit()
}
fn is_word(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_'
}
fn is_identifier_start(byte: u8) -> bool {
byte.is_ascii_alphabetic() || byte == b'_'
}
fn is_boundary(bytes: &[u8], index: usize) -> bool {
let before = index
.checked_sub(1)
.and_then(|previous| byte_at(bytes, previous))
.is_some_and(is_word);
before != byte_at(bytes, index).is_some_and(is_word)
}
fn scan_while(bytes: &[u8], start: usize, predicate: impl Fn(u8) -> bool) -> usize {
bytes.get(start..).map_or(bytes.len(), |rest| {
start
+ rest
.iter()
.position(|&byte| !predicate(byte))
.unwrap_or(rest.len())
})
}
fn find_byte(bytes: &[u8], start: usize, needle: u8) -> Option<usize> {
bytes
.get(start..)?
.iter()
.position(|&byte| byte == needle)
.map(|offset| start + offset)
}
fn line_end(bytes: &[u8], start: usize) -> usize {
find_byte(bytes, start, b'\n').unwrap_or(bytes.len())
}
fn symbol_run(bytes: &[u8], start: usize, is_symbol: impl Fn(u8) -> bool) -> Option<usize> {
byte_at(bytes, start)
.is_some_and(&is_symbol)
.then(|| scan_while(bytes, start + 1, is_symbol))
}
fn bounded_run(
bytes: &[u8],
start: usize,
first: impl Fn(u8) -> bool,
rest: impl Fn(u8) -> bool,
) -> Option<usize> {
if !byte_at(bytes, start).is_some_and(first) || !is_boundary(bytes, start) {
return None;
}
let run_end = scan_while(bytes, start + 1, rest);
(start + 1..=run_end)
.rev()
.find(|&end| is_boundary(bytes, end))
}
fn fraction_end(bytes: &[u8], start: usize) -> Option<usize> {
(byte_at(bytes, start) == Some(b'.') && byte_at(bytes, start + 1).is_some_and(is_digit))
.then(|| scan_while(bytes, start + 2, is_digit))
}
fn decimal_number(bytes: &[u8], start: usize) -> Option<usize> {
if !byte_at(bytes, start).is_some_and(is_digit) || !is_boundary(bytes, start) {
return None;
}
let integer_end = scan_while(bytes, start + 1, is_digit);
if let Some(end) = fraction_end(bytes, integer_end)
&& is_boundary(bytes, end)
{
return Some(end);
}
is_boundary(bytes, integer_end).then_some(integer_end)
}
fn exponent_end(bytes: &[u8], start: usize) -> Option<usize> {
if !matches!(byte_at(bytes, start), Some(b'e' | b'E')) {
return None;
}
let digits_start = if matches!(byte_at(bytes, start + 1), Some(b'+' | b'-')) {
start + 2
} else {
start + 1
};
byte_at(bytes, digits_start)
.is_some_and(is_digit)
.then(|| scan_while(bytes, digits_start + 1, is_digit))
}
fn json_number(bytes: &[u8], start: usize) -> Option<usize> {
let digits_start = if byte_at(bytes, start) == Some(b'-') {
start + 1
} else {
start
};
if !byte_at(bytes, digits_start).is_some_and(is_digit) || !is_boundary(bytes, digits_start) {
return None;
}
let integer_end = scan_while(bytes, digits_start + 1, is_digit);
fraction_end(bytes, integer_end)
.into_iter()
.chain([integer_end])
.find_map(|mantissa_end| {
exponent_end(bytes, mantissa_end)
.filter(|&end| is_boundary(bytes, end))
.or_else(|| is_boundary(bytes, mantissa_end).then_some(mantissa_end))
})
}
fn json_literal(bytes: &[u8], start: usize) -> Option<usize> {
if !is_boundary(bytes, start) {
return None;
}
JSON_KEYWORDS.iter().find_map(|literal| {
let end = start + literal.len();
let matches_literal = bytes
.get(start..end)
.is_some_and(|candidate| candidate.eq_ignore_ascii_case(literal.as_bytes()));
(matches_literal && is_boundary(bytes, end)).then_some(end)
})
}
fn doubled_quote_string(bytes: &[u8], start: usize) -> Option<usize> {
let mut cursor = start + 1;
let mut last_pair = None;
while let Some(byte) = byte_at(bytes, cursor) {
if byte != b'\'' {
cursor += 1;
} else if byte_at(bytes, cursor + 1) == Some(b'\'') {
last_pair = Some(cursor);
cursor += 2;
} else {
return Some(cursor + 1);
}
}
last_pair.map(|pair| pair + 1)
}
fn yaml_identifier(bytes: &[u8], start: usize) -> Option<usize> {
(byte_at(bytes, start).is_some_and(is_identifier_start) && is_boundary(bytes, start)).then(
|| {
scan_while(bytes, start + 1, |byte| {
is_word(byte) || matches!(byte, b'.' | b'-')
})
},
)
}
fn bash_variable(bytes: &[u8], start: usize) -> Option<usize> {
let braced = byte_at(bytes, start + 1) == Some(b'{')
&& byte_at(bytes, start + 2).is_some_and(is_identifier_start);
let name_start = if braced { start + 2 } else { start + 1 };
if !byte_at(bytes, name_start).is_some_and(is_identifier_start) {
return None;
}
let name_end = scan_while(bytes, name_start + 1, is_word);
Some(if byte_at(bytes, name_end) == Some(b'}') {
name_end + 1
} else {
name_end
})
}
fn bash_flag(bytes: &[u8], start: usize) -> Option<usize> {
let letter = if byte_at(bytes, start + 1) == Some(b'-') {
start + 2
} else {
start + 1
};
byte_at(bytes, letter)
.is_some_and(|byte| byte.is_ascii_alphabetic())
.then(|| scan_while(bytes, letter + 1, |byte| is_word(byte) || byte == b'-'))
}
#[derive(Clone, Copy)]
enum RawMatch {
Token(usize),
Quote(u8),
BlockComment,
MarkupComment,
LuaBlockComment,
}
impl RawMatch {
fn raw_end(self, start: usize) -> usize {
match self {
Self::Token(end) => end,
Self::Quote(_) => start + 1,
Self::BlockComment => start + 2,
Self::MarkupComment | Self::LuaBlockComment => start + 4,
}
}
}
impl Grammar {
fn match_at(self, bytes: &[u8], start: usize) -> Option<RawMatch> {
match self {
Self::Bash => bash_match(bytes, start),
Self::Javascript => javascript_match(bytes, start),
Self::Json => json_match(bytes, start),
Self::Lua => lua_match(bytes, start),
Self::Markup => markup_match(bytes, start),
Self::Sql => sql_match(bytes, start),
Self::Yaml => yaml_match(bytes, start),
}
}
}
fn bash_match(bytes: &[u8], start: usize) -> Option<RawMatch> {
let end = match byte_at(bytes, start)? {
b'#' => Some(line_end(bytes, start)),
b'"' => return Some(RawMatch::Quote(b'"')),
b'\'' => find_byte(bytes, start + 1, b'\'').map(|close| close + 1),
b'$' => bash_variable(bytes, start),
b'-' => bash_flag(bytes, start),
_ => bounded_run(bytes, start, is_identifier_start, is_word)
.or_else(|| decimal_number(bytes, start))
.or_else(|| symbol_run(bytes, start, |byte| b"|&;<>()[]{}=".contains(&byte))),
};
end.map(RawMatch::Token)
}
fn javascript_match(bytes: &[u8], start: usize) -> Option<RawMatch> {
match byte_at(bytes, start)? {
b'/' if byte_at(bytes, start + 1) == Some(b'/') => {
Some(RawMatch::Token(line_end(bytes, start)))
}
b'/' if byte_at(bytes, start + 1) == Some(b'*') => Some(RawMatch::BlockComment),
quote @ (b'"' | b'\'' | b'`') => Some(RawMatch::Quote(quote)),
_ => bounded_run(bytes, start, is_digit, |byte| {
byte.is_ascii_digit() || matches!(byte, b'.' | b'_')
})
.or_else(|| {
bounded_run(
bytes,
start,
|byte| is_identifier_start(byte) || byte == b'$',
|byte| is_word(byte) || byte == b'$',
)
})
.or_else(|| {
symbol_run(bytes, start, |byte| {
b"=+-*%<>!?:.,;()[]{}|&/".contains(&byte)
})
})
.map(RawMatch::Token),
}
}
fn json_match(bytes: &[u8], start: usize) -> Option<RawMatch> {
match byte_at(bytes, start)? {
b'/' if byte_at(bytes, start + 1) == Some(b'/') => {
Some(RawMatch::Token(line_end(bytes, start)))
}
b'/' if byte_at(bytes, start + 1) == Some(b'*') => Some(RawMatch::BlockComment),
b'"' => Some(RawMatch::Quote(b'"')),
b'{' | b'}' | b',' | b':' | b'[' | b']' => Some(RawMatch::Token(start + 1)),
_ => json_literal(bytes, start)
.or_else(|| json_number(bytes, start))
.map(RawMatch::Token),
}
}
fn lua_match(bytes: &[u8], start: usize) -> Option<RawMatch> {
match byte_at(bytes, start)? {
b'-' if starts_with_at(bytes, start, b"--[[") => Some(RawMatch::LuaBlockComment),
b'-' if byte_at(bytes, start + 1) == Some(b'-') => {
Some(RawMatch::Token(line_end(bytes, start)))
}
quote @ (b'"' | b'\'') => Some(RawMatch::Quote(quote)),
_ => bounded_run(bytes, start, is_identifier_start, is_word)
.or_else(|| decimal_number(bytes, start))
.or_else(|| symbol_run(bytes, start, |byte| b"=+-*%<>~#.,:;()[]{}".contains(&byte)))
.map(RawMatch::Token),
}
}
fn markup_match(bytes: &[u8], start: usize) -> Option<RawMatch> {
let end = match byte_at(bytes, start)? {
b'<' if starts_with_at(bytes, start, b"<!--") => return Some(RawMatch::MarkupComment),
b'-' if starts_with_at(bytes, start, b"---") => start + 3,
b'<' if byte_at(bytes, start + 1) == Some(b'/') => start + 2,
b'/' if byte_at(bytes, start + 1) == Some(b'>') => start + 2,
b'<' | b'>' | b'{' | b'}' | b'=' => start + 1,
quote @ (b'"' | b'\'') => return Some(RawMatch::Quote(quote)),
_ => bounded_run(bytes, start, is_identifier_start, |byte| {
is_word(byte) || matches!(byte, b':' | b'.' | b'-')
})?,
};
Some(RawMatch::Token(end))
}
fn sql_match(bytes: &[u8], start: usize) -> Option<RawMatch> {
match byte_at(bytes, start)? {
b'-' if byte_at(bytes, start + 1) == Some(b'-') => {
Some(RawMatch::Token(line_end(bytes, start)))
}
b'/' if byte_at(bytes, start + 1) == Some(b'*') => Some(RawMatch::BlockComment),
b'"' => Some(RawMatch::Quote(b'"')),
b'\'' => doubled_quote_string(bytes, start).map(RawMatch::Token),
_ => bounded_run(bytes, start, is_identifier_start, |byte| {
is_word(byte) || byte == b'$'
})
.or_else(|| decimal_number(bytes, start))
.or_else(|| symbol_run(bytes, start, |byte| b"=+-*%<>!.,;()[]".contains(&byte)))
.map(RawMatch::Token),
}
}
fn yaml_match(bytes: &[u8], start: usize) -> Option<RawMatch> {
let end = match byte_at(bytes, start)? {
b'#' => Some(line_end(bytes, start)),
b'"' => return Some(RawMatch::Quote(b'"')),
b'\'' => doubled_quote_string(bytes, start),
b'[' | b']' => Some(start + 1),
_ => yaml_identifier(bytes, start)
.or_else(|| decimal_number(bytes, start))
.or_else(|| symbol_run(bytes, start, |byte| b"{},:&*!?|>@`~-".contains(&byte))),
};
end.map(RawMatch::Token)
}
struct MonotonicFinder {
needle: &'static [u8],
state: FinderState,
}
#[derive(Clone, Copy)]
enum FinderState {
Pending,
Found(usize),
Exhausted,
}
impl MonotonicFinder {
fn new(needle: &'static [u8]) -> Self {
Self {
needle,
state: FinderState::Pending,
}
}
fn find(&mut self, bytes: &[u8], from: usize) -> Option<usize> {
match self.state {
FinderState::Exhausted => return None,
FinderState::Found(index) if index >= from => return Some(index),
FinderState::Pending | FinderState::Found(_) => {}
}
let found = bytes.get(from..).and_then(|rest| {
rest.windows(self.needle.len())
.position(|window| window == self.needle)
.map(|offset| from + offset)
});
self.state = found.map_or(FinderState::Exhausted, FinderState::Found);
found
}
}
#[derive(Default)]
struct QuoteMatcher {
fail_until: [usize; 3],
}
impl QuoteMatcher {
fn close(&mut self, source: &str, start: usize, quote: u8) -> Option<usize> {
let slot = match quote {
b'"' => 0,
b'\'' => 1,
_ => 2,
};
if self
.fail_until
.get(slot)
.is_some_and(|&until| start < until)
{
return None;
}
let bytes = source.as_bytes();
let mut cursor = start + 1;
while let Some(byte) = byte_at(bytes, cursor) {
if byte == quote {
return Some(cursor + 1);
}
if byte != b'\\' {
cursor += 1;
continue;
}
match char_at(source, cursor + 1) {
Some(escaped) if !is_line_terminator(escaped) => {
cursor += 1 + escaped.len_utf8();
}
_ => break,
}
}
if let Some(until) = self.fail_until.get_mut(slot) {
*until = cursor;
}
None
}
}
#[derive(Default)]
struct MarkupClassifier {
in_tag: bool,
has_tag_name: bool,
scan_index: usize,
}
impl MarkupClassifier {
fn classify(&mut self, source: &str, start: usize, value: &str) -> Option<CodeTokenKind> {
if self.in_tag
&& !self.has_tag_name
&& slice(source, self.scan_index, start)
.chars()
.any(|character| character != '/' && !is_js_whitespace(character))
{
self.has_tag_name = true;
}
self.scan_index = start + value.len();
if matches!(value, "<" | "</" | ">" | "/>") {
self.in_tag = value.starts_with('<');
self.has_tag_name = false;
return Some(CodeTokenKind::Symbol);
}
if let Some(kind) = static_markup_kind(value) {
self.has_tag_name |= self.in_tag;
return Some(kind);
}
if !self.in_tag {
return None;
}
let kind = if self.has_tag_name {
CodeTokenKind::Type
} else {
CodeTokenKind::Keyword
};
self.has_tag_name = true;
Some(kind)
}
}
struct Scanner<'a> {
source: &'a str,
grammar: Grammar,
quotes: QuoteMatcher,
block_comment_end: MonotonicFinder,
lua_comment_end: MonotonicFinder,
markup_comment_end: MonotonicFinder,
newline: MonotonicFinder,
markup: MarkupClassifier,
}
impl<'a> Scanner<'a> {
fn new(source: &'a str, grammar: Grammar) -> Self {
Self {
source,
grammar,
quotes: QuoteMatcher::default(),
block_comment_end: MonotonicFinder::new(b"*/"),
lua_comment_end: MonotonicFinder::new(b"]]"),
markup_comment_end: MonotonicFinder::new(b"-->"),
newline: MonotonicFinder::new(b"\n"),
markup: MarkupClassifier::default(),
}
}
fn resolve(&mut self, start: usize, raw: RawMatch) -> Option<usize> {
let bytes = self.source.as_bytes();
match raw {
RawMatch::Token(end) => Some(end),
RawMatch::Quote(quote) => self.quotes.close(self.source, start, quote),
RawMatch::BlockComment => self
.block_comment_end
.find(bytes, start + 2)
.map(|close| close + 2),
RawMatch::MarkupComment => self
.markup_comment_end
.find(bytes, start + 4)
.map(|close| close + 3),
RawMatch::LuaBlockComment => {
if let Some(close) = self.lua_comment_end.find(bytes, start + 4) {
return Some(close + 2);
}
Some(self.newline.find(bytes, start + 4).unwrap_or(bytes.len()))
}
}
}
fn classify(&mut self, start: usize, value: &str) -> Option<CodeTokenKind> {
match self.grammar {
Grammar::Bash => bash_kind(value),
Grammar::Javascript => javascript_kind(value),
Grammar::Json => Some(json_kind(self.source, start, value)),
Grammar::Lua => lua_kind(value),
Grammar::Markup => self.markup.classify(self.source, start, value),
Grammar::Sql => sql_kind(value),
Grammar::Yaml => yaml_kind(self.source, start, value),
}
}
}
fn push_token(tokens: &mut Vec<CodeToken>, value: &str, kind: Option<CodeTokenKind>) {
if !value.is_empty() {
tokens.push(CodeToken {
kind,
value: value.to_owned(),
});
}
}
fn tokenize_scanned(source: &str, grammar: Grammar) -> Vec<CodeToken> {
let bytes = source.as_bytes();
let mut scanner = Scanner::new(source, grammar);
let mut tokens = Vec::new();
let mut offset = 0;
let mut search_from = 0;
while let Some((start, raw)) = (search_from..bytes.len())
.find_map(|index| grammar.match_at(bytes, index).map(|raw| (index, raw)))
{
let Some(end) = scanner.resolve(start, raw) else {
search_from = raw.raw_end(start);
continue;
};
let value = slice(source, start, end);
let kind = scanner.classify(start, value);
push_token(&mut tokens, slice(source, offset, start), None);
push_token(&mut tokens, value, kind);
offset = end;
search_from = end;
}
push_token(&mut tokens, slice(source, offset, bytes.len()), None);
tokens
}
fn starts_with_comment(value: &str) -> bool {
["#", "--", "//", "/*", "<!--"]
.iter()
.any(|prefix| value.starts_with(prefix))
}
fn first_byte(value: &str) -> Option<u8> {
value.as_bytes().first().copied()
}
fn starts_with_quote(value: &str) -> bool {
matches!(first_byte(value), Some(b'"' | b'\'' | b'`'))
}
fn starts_with_digit(value: &str) -> bool {
first_byte(value).is_some_and(is_digit)
}
fn starts_with_identifier(value: &str) -> bool {
first_byte(value).is_some_and(|byte| is_identifier_start(byte) || byte == b'$')
}
fn contains_ignore_case(keywords: &[&str], value: &str) -> bool {
keywords
.iter()
.any(|keyword| keyword.eq_ignore_ascii_case(value))
}
fn is_followed_by_colon(source: &str, from: usize) -> bool {
source
.get(from..)
.and_then(|rest| rest.chars().find(|&character| !is_js_whitespace(character)))
== Some(':')
}
fn javascript_kind(value: &str) -> Option<CodeTokenKind> {
if starts_with_comment(value) {
Some(CodeTokenKind::Comment)
} else if starts_with_quote(value) {
Some(CodeTokenKind::String)
} else if starts_with_digit(value) {
Some(CodeTokenKind::Accent)
} else if !starts_with_identifier(value) {
Some(CodeTokenKind::Symbol)
} else if JAVASCRIPT_KEYWORDS.contains(&value) {
Some(CodeTokenKind::Keyword)
} else if JAVASCRIPT_TYPES.contains(&value) {
Some(CodeTokenKind::Type)
} else {
None
}
}
fn bash_kind(value: &str) -> Option<CodeTokenKind> {
match first_byte(value) {
Some(b'#') => Some(CodeTokenKind::Comment),
Some(b'"' | b'\'' | b'`') => Some(CodeTokenKind::String),
Some(b'$' | b'0'..=b'9') => Some(CodeTokenKind::Accent),
Some(b'-') => Some(CodeTokenKind::Type),
_ if BASH_KEYWORDS.contains(&value) => Some(CodeTokenKind::Keyword),
_ if starts_with_identifier(value) => None,
_ => Some(CodeTokenKind::Symbol),
}
}
fn json_kind(source: &str, start: usize, value: &str) -> CodeTokenKind {
if starts_with_comment(value) {
CodeTokenKind::Comment
} else if value.starts_with('"') {
if is_followed_by_colon(source, start + value.len()) {
CodeTokenKind::Keyword
} else {
CodeTokenKind::String
}
} else if contains_ignore_case(JSON_KEYWORDS, value) {
CodeTokenKind::Type
} else if starts_with_digit(value.strip_prefix('-').unwrap_or(value)) {
CodeTokenKind::Accent
} else {
CodeTokenKind::Symbol
}
}
fn lua_kind(value: &str) -> Option<CodeTokenKind> {
if value.starts_with("--") {
Some(CodeTokenKind::Comment)
} else if starts_with_quote(value) {
Some(CodeTokenKind::String)
} else if starts_with_digit(value) {
Some(CodeTokenKind::Accent)
} else if LUA_KEYWORDS.contains(&value) {
Some(CodeTokenKind::Keyword)
} else if starts_with_identifier(value) {
None
} else {
Some(CodeTokenKind::Symbol)
}
}
fn sql_kind(value: &str) -> Option<CodeTokenKind> {
if starts_with_comment(value) {
Some(CodeTokenKind::Comment)
} else if starts_with_quote(value) {
Some(CodeTokenKind::String)
} else if starts_with_digit(value) {
Some(CodeTokenKind::Accent)
} else if contains_ignore_case(SQL_KEYWORDS, value) {
Some(CodeTokenKind::Keyword)
} else if starts_with_identifier(value) {
None
} else {
Some(CodeTokenKind::Symbol)
}
}
fn yaml_kind(source: &str, start: usize, value: &str) -> Option<CodeTokenKind> {
if value.starts_with('#') {
Some(CodeTokenKind::Comment)
} else if starts_with_quote(value) {
Some(CodeTokenKind::String)
} else if starts_with_digit(value) {
Some(CodeTokenKind::Accent)
} else if contains_ignore_case(YAML_KEYWORDS, value) {
Some(CodeTokenKind::Type)
} else if !starts_with_identifier(value) {
Some(CodeTokenKind::Symbol)
} else if is_followed_by_colon(source, start + value.len()) {
Some(CodeTokenKind::Keyword)
} else {
None
}
}
fn static_markup_kind(value: &str) -> Option<CodeTokenKind> {
if value.starts_with("<!--") || value == "---" {
Some(CodeTokenKind::Comment)
} else if starts_with_quote(value) {
Some(CodeTokenKind::String)
} else if matches!(value, "<" | "</" | ">" | "/>" | "{" | "}" | "=") {
Some(CodeTokenKind::Symbol)
} else {
None
}
}
#[derive(Clone, Copy)]
struct MarkdownMatch {
end: usize,
kind: CodeTokenKind,
}
struct MarkdownScanner<'a> {
source: &'a str,
fence: MonotonicFinder,
backtick: MonotonicFinder,
newline: MonotonicFinder,
comment_end: MonotonicFinder,
close_bracket: MonotonicFinder,
close_paren: MonotonicFinder,
list_fail_until: usize,
}
impl<'a> MarkdownScanner<'a> {
fn new(source: &'a str) -> Self {
Self {
source,
fence: MonotonicFinder::new(b"```"),
backtick: MonotonicFinder::new(b"`"),
newline: MonotonicFinder::new(b"\n"),
comment_end: MonotonicFinder::new(b"-->"),
close_bracket: MonotonicFinder::new(b"]"),
close_paren: MonotonicFinder::new(b")"),
list_fail_until: 0,
}
}
fn match_at(&mut self, index: usize) -> Option<MarkdownMatch> {
if let Some(found) = self.code_span(index) {
return Some(found);
}
if let Some(found) = self.comment(index) {
return Some(found);
}
if self.is_line_start(index)
&& let Some(found) = self.line_start(index)
{
return Some(found);
}
markdown_emphasis(self.source.as_bytes(), index).or_else(|| self.link(index))
}
fn is_line_start(&self, index: usize) -> bool {
index == 0
|| self
.source
.get(..index)
.and_then(|before| before.chars().next_back())
.is_some_and(is_line_terminator)
}
fn code_span(&mut self, index: usize) -> Option<MarkdownMatch> {
let bytes = self.source.as_bytes();
if byte_at(bytes, index) != Some(b'`') {
return None;
}
if starts_with_at(bytes, index, b"```")
&& let Some(fence) = self.fence.find(bytes, index + 3)
{
return Some(MarkdownMatch {
end: fence + 3,
kind: CodeTokenKind::String,
});
}
if matches!(byte_at(bytes, index + 1), None | Some(b'`' | b'\n')) {
return None;
}
let close_tick = self.backtick.find(bytes, index + 1);
let newline = self.newline.find(bytes, index + 1);
close_tick
.filter(|&close| close > index + 1 && newline.is_none_or(|line| close < line))
.map(|close| MarkdownMatch {
end: close + 1,
kind: CodeTokenKind::String,
})
}
fn comment(&mut self, index: usize) -> Option<MarkdownMatch> {
let bytes = self.source.as_bytes();
if !starts_with_at(bytes, index, b"<!--") {
return None;
}
self.comment_end
.find(bytes, index + 4)
.map(|close| MarkdownMatch {
end: close + 3,
kind: CodeTokenKind::Comment,
})
}
fn line_start(&mut self, index: usize) -> Option<MarkdownMatch> {
if let Some(found) =
markdown_heading(self.source, index).or_else(|| markdown_blockquote(self.source, index))
{
return Some(found);
}
if index < self.list_fail_until {
return None;
}
let marker_start = horizontal_whitespace_end(self.source, index);
if let Some(marker_end) = list_marker_end(self.source.as_bytes(), marker_start) {
let trailing_end = horizontal_whitespace_end(self.source, marker_end);
if trailing_end > marker_end {
return Some(MarkdownMatch {
end: trailing_end,
kind: CodeTokenKind::Symbol,
});
}
}
self.list_fail_until = marker_start + 1;
None
}
fn link(&mut self, index: usize) -> Option<MarkdownMatch> {
let bytes = self.source.as_bytes();
if byte_at(bytes, index) != Some(b'[') {
return None;
}
let close_bracket = self
.close_bracket
.find(bytes, index + 1)
.filter(|&close| close > index + 1)?;
if byte_at(bytes, close_bracket + 1) != Some(b'(') {
return None;
}
self.close_paren
.find(bytes, close_bracket + 2)
.filter(|&close| close > close_bracket + 2)
.map(|close| MarkdownMatch {
end: close + 1,
kind: CodeTokenKind::Accent,
})
}
}
fn markdown_heading(source: &str, index: usize) -> Option<MarkdownMatch> {
let bytes = source.as_bytes();
if byte_at(bytes, index) != Some(b'#') {
return None;
}
let mut end = index + 1;
while end - index < 7 && byte_at(bytes, end) == Some(b'#') {
end += 1;
}
(end - index <= 6 && char_at(source, end).is_some_and(is_js_whitespace)).then_some(
MarkdownMatch {
end,
kind: CodeTokenKind::Keyword,
},
)
}
fn markdown_blockquote(source: &str, index: usize) -> Option<MarkdownMatch> {
if byte_at(source.as_bytes(), index) != Some(b'>') {
return None;
}
let end = match char_at(source, index + 1) {
Some(next) if is_horizontal_whitespace(next) => index + 1 + next.len_utf8(),
_ => index + 1,
};
Some(MarkdownMatch {
end,
kind: CodeTokenKind::Symbol,
})
}
fn markdown_emphasis(bytes: &[u8], index: usize) -> Option<MarkdownMatch> {
let marker = byte_at(bytes, index).filter(|byte| matches!(byte, b'*' | b'_'))?;
let end = if byte_at(bytes, index + 1) == Some(marker) {
index + 2
} else {
index + 1
};
Some(MarkdownMatch {
end,
kind: CodeTokenKind::Symbol,
})
}
fn horizontal_whitespace_end(source: &str, start: usize) -> usize {
source.get(start..).map_or(start, |rest| {
start + rest.len() - rest.trim_start_matches(is_horizontal_whitespace).len()
})
}
fn list_marker_end(bytes: &[u8], start: usize) -> Option<usize> {
if matches!(byte_at(bytes, start), Some(b'-' | b'+' | b'*')) {
return Some(start + 1);
}
let digits_end = scan_while(bytes, start, is_digit);
(digits_end > start && byte_at(bytes, digits_end) == Some(b'.')).then_some(digits_end + 1)
}
fn tokenize_markdown(source: &str) -> Vec<CodeToken> {
let mut scanner = MarkdownScanner::new(source);
let mut tokens = Vec::new();
let mut offset = 0;
let mut index = 0;
while index < source.len() {
let Some(found) = scanner.match_at(index) else {
index += char_at(source, index).map_or(1, char::len_utf8);
continue;
};
push_token(&mut tokens, slice(source, offset, index), None);
push_token(
&mut tokens,
slice(source, index, found.end),
Some(found.kind),
);
offset = found.end;
index = found.end;
}
push_token(&mut tokens, slice(source, offset, source.len()), None);
tokens
}
#[cfg(test)]
mod tests {
use super::*;
const PLAIN: Option<CodeTokenKind> = None;
const ACCENT: Option<CodeTokenKind> = Some(CodeTokenKind::Accent);
const COMMENT: Option<CodeTokenKind> = Some(CodeTokenKind::Comment);
const KEYWORD: Option<CodeTokenKind> = Some(CodeTokenKind::Keyword);
const STRING: Option<CodeTokenKind> = Some(CodeTokenKind::String);
const SYMBOL: Option<CodeTokenKind> = Some(CodeTokenKind::Symbol);
const TYPE: Option<CodeTokenKind> = Some(CodeTokenKind::Type);
fn assert_tokens(code: &str, language: &str, expected: &[(Option<CodeTokenKind>, &str)]) {
let tokens = tokenize_code(code, language);
let actual: Vec<(Option<CodeTokenKind>, &str)> = tokens
.iter()
.map(|token| (token.kind, token.value.as_str()))
.collect();
assert_eq!(actual, expected, "{language}: {code:?}");
}
fn joined(tokens: &[CodeToken]) -> String {
tokens.iter().map(|token| token.value.as_str()).collect()
}
#[test]
fn class_names_match_lumen_css() {
let kinds = [
(CodeTokenKind::Accent, "ui-code__token--accent"),
(CodeTokenKind::Comment, "ui-code__token--comment"),
(CodeTokenKind::Keyword, "ui-code__token--keyword"),
(CodeTokenKind::String, "ui-code__token--string"),
(CodeTokenKind::Symbol, "ui-code__token--symbol"),
(CodeTokenKind::Type, "ui-code__token--type"),
];
for (kind, class_name) in kinds {
assert_eq!(kind.class_name(), class_name);
}
}
#[test]
fn normalizes_line_endings_indent_and_blank_edges() {
let cases = [
("", ""),
("\n \t\n", ""),
("a\r\nb\rc", "a\nb\nc"),
("\r\r\n", ""),
(
"\n\n first\n second\n\n third\n\n",
"first\n second\n\nthird",
),
("\tone\n\t\ttwo", "one\n\ttwo"),
(" a\n \n\u{3000}\u{3000}\u{3000}\n b", "a\n\n\u{3000}\nb"),
("\u{a0}\n x\n\u{feff}", "x"),
];
for (code, expected) in cases {
assert_eq!(normalize_code(code), expected, "{code:?}");
}
}
#[test]
fn tokenizes_javascript() {
assert_tokens(
"import { load } from './api'\n/* setup */\nexport const total: number = 1_000 + 3.14 // sum\nconst id = `item-${n}`, $el = \"a \\\"b\\\"\"",
"ts",
&[
(KEYWORD, "import"),
(PLAIN, " "),
(SYMBOL, "{"),
(PLAIN, " "),
(PLAIN, "load"),
(PLAIN, " "),
(SYMBOL, "}"),
(PLAIN, " "),
(KEYWORD, "from"),
(PLAIN, " "),
(STRING, "'./api'"),
(PLAIN, "\n"),
(COMMENT, "/* setup */"),
(PLAIN, "\n"),
(KEYWORD, "export"),
(PLAIN, " "),
(KEYWORD, "const"),
(PLAIN, " "),
(PLAIN, "total"),
(SYMBOL, ":"),
(PLAIN, " "),
(TYPE, "number"),
(PLAIN, " "),
(SYMBOL, "="),
(PLAIN, " "),
(ACCENT, "1_000"),
(PLAIN, " "),
(SYMBOL, "+"),
(PLAIN, " "),
(ACCENT, "3.14"),
(PLAIN, " "),
(COMMENT, "// sum"),
(PLAIN, "\n"),
(KEYWORD, "const"),
(PLAIN, " "),
(PLAIN, "id"),
(PLAIN, " "),
(SYMBOL, "="),
(PLAIN, " "),
(STRING, "`item-${n}`"),
(SYMBOL, ","),
(PLAIN, " $"),
(PLAIN, "el"),
(PLAIN, " "),
(SYMBOL, "="),
(PLAIN, " "),
(STRING, "\"a \\\"b\\\"\""),
],
);
}
#[test]
fn tokenizes_bash() {
assert_tokens(
"pnpm add -D \"$PACKAGE\" # install\nif [ -f \"${HOME}/x\" ]; then echo 'ok' >> log; fi",
"bash",
&[
(PLAIN, "pnpm"),
(PLAIN, " "),
(PLAIN, "add"),
(PLAIN, " "),
(TYPE, "-D"),
(PLAIN, " "),
(STRING, "\"$PACKAGE\""),
(PLAIN, " "),
(COMMENT, "# install"),
(PLAIN, "\n"),
(KEYWORD, "if"),
(PLAIN, " "),
(SYMBOL, "["),
(PLAIN, " "),
(TYPE, "-f"),
(PLAIN, " "),
(STRING, "\"${HOME}/x\""),
(PLAIN, " "),
(SYMBOL, "];"),
(PLAIN, " "),
(KEYWORD, "then"),
(PLAIN, " "),
(PLAIN, "echo"),
(PLAIN, " "),
(STRING, "'ok'"),
(PLAIN, " "),
(SYMBOL, ">>"),
(PLAIN, " "),
(PLAIN, "log"),
(SYMBOL, ";"),
(PLAIN, " "),
(KEYWORD, "fi"),
],
);
}
#[test]
fn tokenizes_json() {
assert_tokens(
"{\n \"enabled\": true,\n \"ratio\": -0.5e+10, // note\n \"list\": [1, Null]\n}",
"json",
&[
(SYMBOL, "{"),
(PLAIN, "\n "),
(KEYWORD, "\"enabled\""),
(SYMBOL, ":"),
(PLAIN, " "),
(TYPE, "true"),
(SYMBOL, ","),
(PLAIN, "\n "),
(KEYWORD, "\"ratio\""),
(SYMBOL, ":"),
(PLAIN, " "),
(ACCENT, "-0.5e+10"),
(SYMBOL, ","),
(PLAIN, " "),
(COMMENT, "// note"),
(PLAIN, "\n "),
(KEYWORD, "\"list\""),
(SYMBOL, ":"),
(PLAIN, " "),
(SYMBOL, "["),
(ACCENT, "1"),
(SYMBOL, ","),
(PLAIN, " "),
(TYPE, "Null"),
(SYMBOL, "]"),
(PLAIN, "\n"),
(SYMBOL, "}"),
],
);
}
#[test]
fn tokenizes_lua() {
assert_tokens(
"--[[ block ]]\nlocal ok = name ~= nil and #name > 0 -- check\nprint(\"hi\", 'x', 1.5)",
"lua",
&[
(COMMENT, "--[[ block ]]"),
(PLAIN, "\n"),
(KEYWORD, "local"),
(PLAIN, " "),
(PLAIN, "ok"),
(PLAIN, " "),
(SYMBOL, "="),
(PLAIN, " "),
(PLAIN, "name"),
(PLAIN, " "),
(SYMBOL, "~="),
(PLAIN, " "),
(KEYWORD, "nil"),
(PLAIN, " "),
(KEYWORD, "and"),
(PLAIN, " "),
(SYMBOL, "#"),
(PLAIN, "name"),
(PLAIN, " "),
(SYMBOL, ">"),
(PLAIN, " "),
(ACCENT, "0"),
(PLAIN, " "),
(COMMENT, "-- check"),
(PLAIN, "\n"),
(PLAIN, "print"),
(SYMBOL, "("),
(STRING, "\"hi\""),
(SYMBOL, ","),
(PLAIN, " "),
(STRING, "'x'"),
(SYMBOL, ","),
(PLAIN, " "),
(ACCENT, "1.5"),
(SYMBOL, ")"),
],
);
}
#[test]
fn tokenizes_markdown() {
assert_tokens(
"# Lumen\n> Calm **UI**\n- Use `pnpm add` and [docs](https://santi020k.com)\n<!-- note -->",
"markdown",
&[
(KEYWORD, "#"),
(PLAIN, " Lumen\n"),
(SYMBOL, "> "),
(PLAIN, "Calm "),
(SYMBOL, "**"),
(PLAIN, "UI"),
(SYMBOL, "**"),
(PLAIN, "\n"),
(SYMBOL, "- "),
(PLAIN, "Use "),
(STRING, "`pnpm add`"),
(PLAIN, " and "),
(ACCENT, "[docs](https://santi020k.com)"),
(PLAIN, "\n"),
(COMMENT, "<!-- note -->"),
],
);
}
#[test]
fn tokenizes_markup() {
assert_tokens(
"<!-- hero -->\n<Image src=\"/hero.png\" alt='Hero' loading={lazy} />\n<p class=\"a > b\">Hi</p>",
"html",
&[
(COMMENT, "<!-- hero -->"),
(PLAIN, "\n"),
(SYMBOL, "<"),
(KEYWORD, "Image"),
(PLAIN, " "),
(TYPE, "src"),
(SYMBOL, "="),
(STRING, "\"/hero.png\""),
(PLAIN, " "),
(TYPE, "alt"),
(SYMBOL, "="),
(STRING, "'Hero'"),
(PLAIN, " "),
(TYPE, "loading"),
(SYMBOL, "="),
(SYMBOL, "{"),
(TYPE, "lazy"),
(SYMBOL, "}"),
(PLAIN, " "),
(SYMBOL, "/>"),
(PLAIN, "\n"),
(SYMBOL, "<"),
(KEYWORD, "p"),
(PLAIN, " "),
(TYPE, "class"),
(SYMBOL, "="),
(STRING, "\"a > b\""),
(SYMBOL, ">"),
(PLAIN, "Hi"),
(SYMBOL, "</"),
(KEYWORD, "p"),
(SYMBOL, ">"),
],
);
}
#[test]
fn tokenizes_sql() {
assert_tokens(
"-- active\nSELECT p.name AS \"Name\", COUNT(*) FROM projects p\nWHERE p.status = 'it''s' AND score >= 4.5;",
"sql",
&[
(COMMENT, "-- active"),
(PLAIN, "\n"),
(KEYWORD, "SELECT"),
(PLAIN, " "),
(PLAIN, "p"),
(SYMBOL, "."),
(PLAIN, "name"),
(PLAIN, " "),
(KEYWORD, "AS"),
(PLAIN, " "),
(STRING, "\"Name\""),
(SYMBOL, ","),
(PLAIN, " "),
(PLAIN, "COUNT"),
(SYMBOL, "(*)"),
(PLAIN, " "),
(KEYWORD, "FROM"),
(PLAIN, " "),
(PLAIN, "projects"),
(PLAIN, " "),
(PLAIN, "p"),
(PLAIN, "\n"),
(KEYWORD, "WHERE"),
(PLAIN, " "),
(PLAIN, "p"),
(SYMBOL, "."),
(PLAIN, "status"),
(PLAIN, " "),
(SYMBOL, "="),
(PLAIN, " "),
(STRING, "'it''s'"),
(PLAIN, " "),
(KEYWORD, "AND"),
(PLAIN, " "),
(PLAIN, "score"),
(PLAIN, " "),
(SYMBOL, ">="),
(PLAIN, " "),
(ACCENT, "4.5"),
(SYMBOL, ";"),
],
);
}
#[test]
fn tokenizes_yaml() {
assert_tokens(
"# config\nname: Lumen\nenabled: Yes\nversion: 6.0\nlist: [a, \"b\"]\nquote: 'it''s'",
"yaml",
&[
(COMMENT, "# config"),
(PLAIN, "\n"),
(KEYWORD, "name"),
(SYMBOL, ":"),
(PLAIN, " "),
(PLAIN, "Lumen"),
(PLAIN, "\n"),
(KEYWORD, "enabled"),
(SYMBOL, ":"),
(PLAIN, " "),
(TYPE, "Yes"),
(PLAIN, "\n"),
(KEYWORD, "version"),
(SYMBOL, ":"),
(PLAIN, " "),
(ACCENT, "6.0"),
(PLAIN, "\n"),
(KEYWORD, "list"),
(SYMBOL, ":"),
(PLAIN, " "),
(SYMBOL, "["),
(PLAIN, "a"),
(SYMBOL, ","),
(PLAIN, " "),
(STRING, "\"b\""),
(SYMBOL, "]"),
(PLAIN, "\n"),
(KEYWORD, "quote"),
(SYMBOL, ":"),
(PLAIN, " "),
(STRING, "'it''s'"),
],
);
}
#[test]
fn follows_regex_backtracking() {
assert_tokens(
"1.5x $foo a$ 1._1a",
"ts",
&[
(ACCENT, "1."),
(PLAIN, "5x $"),
(PLAIN, "foo"),
(PLAIN, " "),
(PLAIN, "a"),
(PLAIN, "$ "),
(ACCENT, "1."),
(PLAIN, "_1a"),
],
);
assert_tokens(
"$1 ${a} -1 --a-b 12abc",
"bash",
&[
(PLAIN, "$"),
(ACCENT, "1"),
(PLAIN, " "),
(ACCENT, "${a}"),
(PLAIN, " -"),
(ACCENT, "1"),
(PLAIN, " "),
(TYPE, "--a-b"),
(PLAIN, " 12abc"),
],
);
assert_tokens(
"1e5x -1.5e-3 TRUE",
"json",
&[
(PLAIN, "1e5x "),
(ACCENT, "-1.5e-3"),
(PLAIN, " "),
(TYPE, "TRUE"),
],
);
}
#[test]
fn leaves_unclosed_openers_as_text() {
assert_tokens("/*/", "ts", &[(PLAIN, "/*"), (SYMBOL, "/")]);
assert_tokens("\"\\\n\"", "ts", &[(PLAIN, "\"\\\n\"")]);
assert_tokens("'''", "sql", &[(STRING, "''"), (PLAIN, "'")]);
assert_tokens(
"--[[ open\nlocal x",
"lua",
&[
(COMMENT, "--[[ open"),
(PLAIN, "\n"),
(KEYWORD, "local"),
(PLAIN, " "),
(PLAIN, "x"),
],
);
assert_tokens(
"<!-- open <a b>",
"html",
&[
(PLAIN, "<!-- "),
(PLAIN, "open"),
(PLAIN, " "),
(SYMBOL, "<"),
(KEYWORD, "a"),
(PLAIN, " "),
(TYPE, "b"),
(SYMBOL, ">"),
],
);
assert_tokens(
"####### no\n1.x [a]() *_",
"markdown",
&[
(PLAIN, "####### no\n1.x [a]() "),
(SYMBOL, "*"),
(SYMBOL, "_"),
],
);
}
#[test]
fn honors_unicode_whitespace() {
assert_tokens(
"{\"enabled\"\u{a0}: true}",
"json5",
&[
(SYMBOL, "{"),
(KEYWORD, "\"enabled\""),
(PLAIN, "\u{a0}"),
(SYMBOL, ":"),
(PLAIN, " "),
(TYPE, "true"),
(SYMBOL, "}"),
],
);
assert_tokens(
"name\u{a0}: Astro",
"yaml",
&[
(KEYWORD, "name"),
(PLAIN, "\u{a0}"),
(SYMBOL, ":"),
(PLAIN, " "),
(PLAIN, "Astro"),
],
);
assert_tokens(
"##\u{a0}Heading\n-\u{a0}Item\nx\u{2028}> quote",
"markdown",
&[
(KEYWORD, "##"),
(PLAIN, "\u{a0}Heading\n"),
(SYMBOL, "-\u{a0}"),
(PLAIN, "Item\nx\u{2028}"),
(SYMBOL, "> "),
(PLAIN, "quote"),
],
);
assert_tokens(
"é \"😀\" 1",
"ts",
&[
(PLAIN, "é "),
(STRING, "\"😀\""),
(PLAIN, " "),
(ACCENT, "1"),
],
);
}
#[test]
fn falls_back_to_plain_text() {
assert_tokens("opaque source", "plaintext", &[(PLAIN, "opaque source")]);
assert_tokens("\n fn main() {}\n", "", &[(PLAIN, "fn main() {}")]);
assert_tokens("", "plaintext", &[]);
assert_tokens(" \n\t\n", "ts", &[]);
assert_tokens("", "markdown", &[]);
assert_tokens("", "html", &[]);
}
#[test]
fn matches_language_names_loosely() {
let code = "const x = 1 // note";
assert_eq!(tokenize_code(code, " TS\n"), tokenize_code(code, "ts"));
assert_eq!(
tokenize_code(code, "\u{feff}TypeScript"),
tokenize_code(code, "ts")
);
assert_eq!(
tokenize_code("**a**", "MAR\u{212a}DOWN"),
tokenize_code("**a**", "markdown")
);
assert_eq!(
tokenize_code(code, "rust"),
vec![CodeToken {
kind: None,
value: code.to_owned(),
}]
);
}
fn assert_adversarial(cases: &[(&str, String, usize, Option<CodeTokenKind>)]) {
for (language, code, count, first_kind) in cases {
let tokens = tokenize_code(code, language);
let prefix: String = code.chars().take(8).collect();
assert_eq!(tokens.len(), *count, "{language}: {prefix:?}");
assert_eq!(tokens.first().and_then(|token| token.kind), *first_kind);
assert_eq!(
joined(&tokens),
normalize_code(code),
"{language}: {prefix:?}"
);
}
}
#[test]
fn handles_adversarial_scripts() {
assert_adversarial(&[
("ts", "\"".repeat(100_000), 50_000, STRING),
("ts", "\"\\".repeat(50_000), 1, PLAIN),
("ts", "/*".repeat(50_000), 2, COMMENT),
("ts", format!("/*{}", "a".repeat(100_000)), 2, PLAIN),
("ts", "`".repeat(100_000), 50_000, STRING),
("ts", format!("'{}", "\\".repeat(100_000)), 1, PLAIN),
("ts", format!("a{}", "$".repeat(100_000)), 2, PLAIN),
("ts", format!("{}a", "1_".repeat(50_000)), 1, PLAIN),
("bash", "'".repeat(100_001), 50_001, STRING),
("bash", "\"".repeat(100_001), 50_001, STRING),
("lua", "--[[".repeat(25_000), 1, COMMENT),
("lua", "'".repeat(100_001), 50_001, STRING),
]);
}
#[test]
fn handles_adversarial_data_and_markup() {
assert_adversarial(&[
("json", "-1e".repeat(33_333), 1, PLAIN),
("html", "<".repeat(100_000), 100_000, SYMBOL),
("html", "<!--".repeat(25_000), 1, PLAIN),
("html", "<a \"".repeat(25_000), 50_000, SYMBOL),
("sql", "'".repeat(100_001), 2, STRING),
("sql", "/*".repeat(50_000), 33_333, COMMENT),
("yaml", "'".repeat(100_000), 1, STRING),
("yaml", "a ".repeat(50_000), 100_000, PLAIN),
]);
}
#[test]
fn handles_adversarial_markdown() {
assert_adversarial(&[
("markdown", "*".repeat(100_000), 50_000, SYMBOL),
("markdown", "[".repeat(100_000), 1, PLAIN),
("markdown", "`".repeat(100_001), 16_667, STRING),
("markdown", "<!--".repeat(25_000), 1, PLAIN),
("markdown", "#".repeat(100_000), 1, PLAIN),
("markdown", "- \n".repeat(33_333), 66_665, SYMBOL),
("markdown", "[a](".repeat(25_000), 1, PLAIN),
]);
}
#[test]
fn normalizes_long_indented_input() {
let code = " line\n".repeat(50_000);
let normalized = normalize_code(&code);
assert_eq!(normalized.len(), "line\n".len() * 50_000 - 1);
assert!(normalized.starts_with("line\nline"));
}
}