use std::cell::Cell;
use tabnas::{Context, ImperativeLexMatcher, Lexer, Options, Rule, Token, Value, TIN_ST};
const UNKNOWN_ESCAPE: char = '\u{1b}';
pub(crate) fn make_toml_string_matcher(_options: &Options) -> Option<ImperativeLexMatcher> {
Some(std::sync::Arc::new(toml_string_matcher))
}
fn escape_char(escape: char) -> Option<char> {
match escape {
'b' => Some('\u{8}'),
't' => Some('\t'),
'n' => Some('\n'),
'f' => Some('\u{c}'),
'r' => Some('\r'),
'"' => Some('"'),
'\\' => Some('\\'),
_ => None,
}
}
fn is_control_other_than_tab(character: char) -> bool {
(character < '\u{20}' && character != '\t') || character == '\u{7f}'
}
fn is_hexadecimal_lax(character: char) -> bool {
character.is_ascii_alphanumeric()
}
fn hex_prefix(text: &str) -> Option<u32> {
let mut value: u64 = 0;
let mut seen = false;
for character in text.chars() {
let Some(digit) = character.to_digit(16) else {
break;
};
seen = true;
value = (value * 16 + u64::from(digit)).min(u64::from(u32::MAX));
}
#[allow(clippy::cast_possible_truncation)]
seen.then_some(value as u32)
}
fn two_hex(text: &str) -> Option<u32> {
let digits: Vec<char> = text.chars().take(2).collect();
(2 == digits.len() && digits.iter().all(char::is_ascii_hexdigit))
.then(|| u32::from_str_radix(&digits.iter().collect::<String>(), 16).ok())
.flatten()
}
const FIRST_WINDOW: usize = 256;
fn toml_string_matcher(
lexer: &mut Lexer<'_>,
_rule: &mut Rule,
_context: &mut Context,
) -> Option<Token> {
lexer.fill(1);
let delimiter = lexer.window().chars().next()?;
if '\'' != delimiter && '"' != delimiter {
return None;
}
let origin = lexer.point().site.pos;
let mut want = FIRST_WINDOW;
loop {
lexer.fill(want);
let window = Window::new(lexer.forward(want), want);
let scanned = scan(&window, delimiter, origin);
if window.short.get() {
want = want.saturating_mul(2);
continue;
}
return Some(match scanned {
Scan::Bad { why, start, end } => lexer.bad_span(why, start, end),
Scan::String {
value,
text,
advance,
} => {
lexer.advance_chars(advance);
lexer.token("#ST", TIN_ST, Value::String(value), text, end(lexer))
}
});
}
}
struct Window {
chars: Vec<char>,
whole: bool,
short: Cell<bool>,
}
impl Window {
fn new(text: &str, want: usize) -> Window {
let chars: Vec<char> = text.chars().collect();
let whole = chars.len() < want;
Window {
chars,
whole,
short: Cell::new(false),
}
}
fn get(&self, index: usize) -> Option<char> {
let found = self.chars.get(index).copied();
if found.is_none() && !self.whole {
self.short.set(true);
}
found
}
fn len(&self) -> usize {
if self.whole {
self.chars.len()
} else {
usize::MAX
}
}
fn text(&self, begin: usize, end: usize) -> String {
if end > self.chars.len() && !self.whole {
self.short.set(true);
}
let end = end.min(self.chars.len());
self.chars[begin.min(end)..end].iter().collect()
}
}
enum Scan {
Bad {
why: &'static str,
start: usize,
end: usize,
},
String {
value: String,
text: String,
advance: usize,
},
}
#[allow(clippy::too_many_lines)]
fn scan(source: &Window, delimiter: char, origin: usize) -> Scan {
let length = source.len();
let span = |why: &'static str, start: usize, end: usize| Scan::Bad {
why,
start: origin + start,
end: origin + end,
};
let begin = 0_usize;
let mut index = 0_usize;
let mut is_multiline = false;
if Some(delimiter) == source.get(1) {
if Some(delimiter) != source.get(2) {
return Scan::String {
value: String::new(),
text: source.text(0, 2),
advance: 2,
};
}
index += 2;
is_multiline = true;
}
if is_multiline && Some('\n') == source.get(index + 1) {
index += 1;
}
let mut value = String::new();
let mut closed = false;
while index < length {
index += 1;
let Some(character) = source.get(index) else {
return span("unterminated_string", begin, index);
};
if '\n' == character {
if !is_multiline {
return span("unprintable", index, index + 1);
}
value.push('\n');
continue;
}
if delimiter == character {
if is_multiline {
if Some(delimiter) != source.get(index + 1) {
value.push(delimiter);
continue;
}
if Some(delimiter) != source.get(index + 2) {
value.push(delimiter);
value.push(delimiter);
index += 1;
continue;
}
index += 2;
if Some(delimiter) == source.get(index + 1) {
value.push(delimiter);
index += 1;
}
if Some(delimiter) == source.get(index + 1) {
value.push(delimiter);
index += 1;
}
}
index += 1;
closed = true;
break;
}
if is_control_other_than_tab(character) {
return span("unprintable", index, index + 1);
}
if '\'' == delimiter {
value.push(character);
continue;
}
if '\\' != character {
value.push(character);
continue;
}
index += 1;
let escape = source.get(index);
if let Some(replacement) = escape.and_then(escape_char) {
value.push(replacement);
continue;
}
match escape {
Some('x') => {
index += 1;
let rest: String = (index..index + 2).map_while(|at| source.get(at)).collect();
let Some(code) = two_hex(&rest) else {
return span("invalid_ascii", index.saturating_sub(2), index + 2);
};
value.push(char::from_u32(code).unwrap_or(char::REPLACEMENT_CHARACTER));
index += 1;
}
Some(marker @ ('u' | 'U')) => {
let begin_unicode = index;
let size = if 'u' == marker { 4 } else { 8 };
let mut digits = String::new();
for _ in 0..size {
index += 1;
match source.get(index) {
Some(digit) if is_hexadecimal_lax(digit) => digits.push(digit),
_ => return span("invalid_unicode", begin_unicode, index),
}
}
let code = hex_prefix(&digits);
let Some(code) = code.filter(|code| *code <= 0x0010_FFFF) else {
return span("invalid_unicode", begin_unicode, index);
};
value.push(char::from_u32(code).unwrap_or(char::REPLACEMENT_CHARACTER));
}
Some(' ' | '\t' | '\n' | '\r') if is_multiline => {
loop {
match source.get(index + 1) {
Some(' ' | '\t' | '\n') => index += 1,
Some('\r') if Some('\n') == source.get(index + 2) => index += 2,
_ => break,
}
}
}
_ => value.push(UNKNOWN_ESCAPE),
}
}
if !closed {
return span("unterminated_string", begin, index);
}
let advance = index.min(length);
Scan::String {
value,
text: source.text(begin, advance),
advance,
}
}
fn end(lexer: &Lexer<'_>) -> tabnas::Point {
lexer.point()
}