use std::cmp::max;
use oxc_str::{JSStr, JSStrBuilder};
use crate::{config::LexerConfig as Config, diagnostics};
use super::{
FinishTokenMode, Kind, Lexer, SourcePosition, Span, Token, cold_branch,
search::{SafeByteMatchTable, byte_search, safe_byte_match_table},
};
const MIN_ESCAPED_STR_LEN: usize = 16;
static DOUBLE_QUOTE_STRING_END_TABLE: SafeByteMatchTable =
safe_byte_match_table!(|b| matches!(b, b'"' | b'\r' | b'\n' | b'\\'));
static SINGLE_QUOTE_STRING_END_TABLE: SafeByteMatchTable =
safe_byte_match_table!(|b| matches!(b, b'\'' | b'\r' | b'\n' | b'\\'));
#[inline(always)]
fn find_string_chunk_end<const DELIMITER: u8>(
bytes: &[u8],
table: &SafeByteMatchTable,
) -> Option<usize> {
const PREFIX_LEN: usize = 16;
let Some(prefix) = bytes.get(..PREFIX_LEN) else {
return bytes.iter().position(|&byte| table.matches(byte));
};
for (index, &byte) in prefix.iter().enumerate() {
if table.matches(byte) {
return Some(index);
}
}
let remaining = &bytes[PREFIX_LEN..];
let end = memchr::memchr3(DELIMITER, b'\\', b'\n', remaining);
memchr::memchr(b'\r', &remaining[..end.unwrap_or(remaining.len())])
.or(end)
.map(|index| PREFIX_LEN + index)
}
macro_rules! handle_string_literal {
($lexer:ident, $delimiter:literal, $table:ident) => {{
let pos = $lexer.source.position();
match handle_plain_string_literal!($lexer, pos, $delimiter, $table) {
Ok(_) => Kind::Str,
Err(next_byte) => cold_branch(|| {
handle_string_literal_rest!($lexer, pos, $delimiter, $table, next_byte)
}),
}
}};
}
macro_rules! handle_plain_string_literal {
($lexer:ident, $pos:ident, $delimiter:literal, $table:ident) => {{
debug_assert!($delimiter.is_ascii());
let after_opening_quote = $pos.add(1);
let next_byte = byte_search! {
lexer: $lexer,
table: $table,
start: after_opening_quote,
handle_eof: 0,
};
if next_byte == $delimiter {
let end = $lexer.source.position().add(1);
$lexer.source.set_position(end);
Ok(end)
} else {
Err(next_byte)
}
}};
}
macro_rules! handle_string_literal_rest {
($lexer:ident, $pos:ident, $delimiter:literal, $table:ident, $next_byte:ident) => {{
match $next_byte {
b'\\' => {
let after_opening_quote = $pos.add(1);
handle_string_literal_escape!($lexer, $delimiter, $table, after_opening_quote)
}
0 => {
$lexer.error(diagnostics::unterminated_string($lexer.unterminated_range()));
Kind::Undetermined
}
_ => {
debug_assert!(matches!($next_byte, b'\r' | b'\n'));
$lexer.consume_char();
$lexer.error(diagnostics::unterminated_string($lexer.unterminated_range()));
Kind::Undetermined
}
}
}};
}
macro_rules! handle_string_literal_escape {
($lexer:ident, $delimiter:literal, $table:ident, $after_opening_quote:ident) => {{
let so_far = $lexer.source.str_from_pos_to_current($after_opening_quote);
if so_far.is_empty() && $lexer.read_single_character_escape::<$delimiter>() {
return Kind::Str;
}
let escape_start_offset = $lexer.offset();
$lexer.consume_char();
let after_backslash = $lexer.source.position();
let mut is_valid_escape_sequence = true;
let first = $lexer.decode_string_escape_sequence(false, &mut is_valid_escape_sequence);
if !is_valid_escape_sequence {
let range = Span::new(escape_start_offset, $lexer.offset());
$lexer.error(diagnostics::invalid_escape_sequence(range));
}
let chunk_start = $lexer.source.position();
let remaining = $lexer.source.remaining().as_bytes();
let Some(end) = find_string_chunk_end::<$delimiter>(remaining, &$table) else {
$lexer.source.advance_to_end();
$lexer.error(diagnostics::unterminated_string($lexer.unterminated_range()));
return Kind::Undetermined;
};
let b = remaining[end];
$lexer.source.set_position(chunk_start.add(end));
let chunk = $lexer.source.str_from_pos_to_current(chunk_start);
if b != $delimiter && b != b'\\' {
return cold_branch(|| {
debug_assert!(matches!(b, b'\r' | b'\n'));
$lexer.consume_char();
$lexer.error(diagnostics::unterminated_string($lexer.unterminated_range()));
Kind::Undetermined
});
}
if b == $delimiter && is_valid_escape_sequence {
let borrowed = match first {
None if so_far.is_empty() => Some(chunk),
None if chunk.is_empty() => Some(so_far),
Some(value) if so_far.is_empty() => value.to_char().and_then(|c| {
let source_value = $lexer.source.str_from_pos_to_current(after_backslash);
let escape_len = source_value.len() - chunk.len();
(escape_len == c.len_utf8() && source_value.starts_with(c))
.then_some(source_value)
}),
_ => None,
};
if let Some(value) = borrowed {
$lexer.source.next_byte_unchecked();
$lexer.save_js_string(value.into());
return Kind::Str;
}
}
let capacity = if b == $delimiter {
so_far.len() + first.map_or(0, |c| c.len_bytes()) + chunk.len()
} else {
max(so_far.len() * 2, MIN_ESCAPED_STR_LEN)
};
let mut str = JSStrBuilder::with_capacity_in(capacity, &$lexer.allocator);
str.push_str(so_far);
if let Some(first) = first {
if let Some(c) = first.to_char() {
str.push(c);
} else {
str.push_js_char(first);
}
}
str.push_str(chunk);
if b == $delimiter {
$lexer.source.next_byte_unchecked();
$lexer.save_js_string(str.into_js_str());
return Kind::Str;
}
loop {
let escape_start_offset = $lexer.offset();
$lexer.consume_char();
let mut is_valid_escape_sequence = true;
$lexer.read_string_escape_sequence(&mut str, false, &mut is_valid_escape_sequence);
if !is_valid_escape_sequence {
let range = Span::new(escape_start_offset, $lexer.offset());
$lexer.error(diagnostics::invalid_escape_sequence(range));
}
let chunk_start = $lexer.source.position();
let remaining = $lexer.source.remaining().as_bytes();
let Some(end) = find_string_chunk_end::<$delimiter>(remaining, &$table) else {
$lexer.source.advance_to_end();
$lexer.error(diagnostics::unterminated_string($lexer.unterminated_range()));
return Kind::Undetermined;
};
let b = remaining[end];
$lexer.source.set_position(chunk_start.add(end));
match b {
$delimiter => {
let chunk = $lexer.source.str_from_pos_to_current(chunk_start);
str.push_str(chunk);
$lexer.source.next_byte_unchecked();
break;
}
b'\\' => {
let chunk = $lexer.source.str_from_pos_to_current(chunk_start);
str.push_str(chunk);
}
_ => {
return cold_branch(|| {
debug_assert!(matches!(b, b'\r' | b'\n'));
$lexer.consume_char();
$lexer.error(diagnostics::unterminated_string($lexer.unterminated_range()));
Kind::Undetermined
});
}
}
}
$lexer.save_js_string(str.into_js_str());
Kind::Str
}};
}
impl<'a, C: Config> Lexer<'a, C> {
#[inline]
fn read_single_character_escape<const DELIMITER: u8>(&mut self) -> bool {
let remaining = self.source.remaining();
let [b'\\', escape, delimiter, ..] = remaining.as_bytes() else {
return false;
};
if *delimiter != DELIMITER {
return false;
}
let value = match escape {
b'\'' => "'",
b'\"' => "\"",
b'\\' => "\\",
b'b' => "\u{8}",
b'f' => "\u{c}",
b'n' => "\n",
b'r' => "\r",
b't' => "\t",
b'v' => "\u{b}",
b'0' => "\0",
_ => return false,
};
let value = if matches!(escape, b'\'' | b'"' | b'\\') {
JSStr::from(&remaining[1..2])
} else {
JSStr::from_str_in(value, &self.allocator)
};
let end = unsafe { self.source.position().add(3) };
self.source.set_position(end);
self.save_js_string(value);
true
}
pub(super) unsafe fn read_string_literal_double_quote(&mut self) -> Kind {
unsafe { handle_string_literal!(self, b'"', DOUBLE_QUOTE_STRING_END_TABLE) }
}
pub(super) unsafe fn read_string_literal_single_quote(&mut self) -> Kind {
unsafe { handle_string_literal!(self, b'\'', SINGLE_QUOTE_STRING_END_TABLE) }
}
#[expect(clippy::inline_always)]
#[inline(always)]
pub(super) unsafe fn read_plain_string_literal_double_quote(
&mut self,
pos: SourcePosition<'a>,
) -> Result<SourcePosition<'a>, u8> {
unsafe { handle_plain_string_literal!(self, pos, b'"', DOUBLE_QUOTE_STRING_END_TABLE) }
}
#[expect(clippy::inline_always)]
#[inline(always)]
pub(super) unsafe fn read_plain_string_literal_single_quote(
&mut self,
pos: SourcePosition<'a>,
) -> Result<SourcePosition<'a>, u8> {
unsafe { handle_plain_string_literal!(self, pos, b'\'', SINGLE_QUOTE_STRING_END_TABLE) }
}
#[cold]
#[inline(never)]
pub(super) unsafe fn string_token_rest_double_quote(
&mut self,
pos: SourcePosition<'a>,
next_byte: u8,
) -> Token {
self.token_start = self.source.offset_of(pos);
let kind = cold_branch(|| unsafe {
handle_string_literal_rest!(self, pos, b'"', DOUBLE_QUOTE_STRING_END_TABLE, next_byte)
});
self.finish_next_inner(kind, self.source.position(), FinishTokenMode::Push)
}
#[cold]
#[inline(never)]
pub(super) unsafe fn string_token_rest_single_quote(
&mut self,
pos: SourcePosition<'a>,
next_byte: u8,
) -> Token {
self.token_start = self.source.offset_of(pos);
let kind = cold_branch(|| unsafe {
handle_string_literal_rest!(self, pos, b'\'', SINGLE_QUOTE_STRING_END_TABLE, next_byte)
});
self.finish_next_inner(kind, self.source.position(), FinishTokenMode::Push)
}
fn save_js_string(&mut self, value: JSStr<'a>) {
self.escaped_strings.insert(self.token_start, value);
self.pending.set_escaped();
}
pub(crate) fn get_js_string(&self, token: Token) -> JSStr<'a> {
debug_assert_eq!(token.kind(), Kind::Str);
if token.escaped() {
self.escaped_strings[&token.start()]
} else {
let start = (token.start() + 1) as usize;
let end = (token.end() - 1) as usize;
JSStr::from(&self.source.whole()[start..end])
}
}
pub(super) fn save_string(&mut self, has_escape: bool, s: &'a str) {
if has_escape {
self.save_escaped_string(s);
}
}
#[cold]
fn save_escaped_string(&mut self, s: &'a str) {
self.escaped_strings.insert(self.token_start, s.into());
self.pending.set_escaped();
}
pub(crate) fn get_string(&self, token: Token) -> &'a str {
if token.escaped() {
return self.escaped_strings[&token.start()]
.as_str()
.expect("identifier escape must be valid UTF-8");
}
let source_text = self.source.whole();
let mut start = token.start() as usize;
let mut end = token.end() as usize;
match token.kind() {
Kind::Str => {
start += 1;
end -= 1;
}
Kind::PrivateIdentifier => {
start += 1;
}
_ => {}
}
&source_text[start..end]
}
}