Skip to content

Commit

Permalink
perf(es/parser): Optimize lexing of template literals, again (#9037)
Browse files Browse the repository at this point in the history
**Description:**

Applies same trick as #9036, but for `cooked`
  • Loading branch information
kdy1 committed Jun 12, 2024
1 parent 9d2e1ce commit 5bffd0f
Showing 1 changed file with 33 additions and 24 deletions.
57 changes: 33 additions & 24 deletions crates/swc_ecma_parser/src/lexer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1159,9 +1159,34 @@ impl<'a> Lexer<'a> {
let start = self.cur_pos();

let mut cooked = Ok(String::new());
let mut cooked_slice_start = start;
let mut raw = SmartString::new();
let mut raw_slice_start = start;

macro_rules! consume_raw {
() => {{
let last_pos = self.cur_pos();
raw.push_str(unsafe {
// Safety: Both of start and last_pos are valid position because we got them
// from `self.input`
self.input.slice(raw_slice_start, last_pos)
});
}};
}

macro_rules! consume_cooked {
() => {{
if let Ok(cooked) = &mut cooked {
let last_pos = self.cur_pos();
cooked.push_str(unsafe {
// Safety: Both of start and last_pos are valid position because we got them
// from `self.input`
self.input.slice(cooked_slice_start, last_pos)
});
}
}};
}

while let Some(c) = self.cur() {
if c == '`' || (c == '$' && self.peek() == Some('{')) {
if start == self.cur_pos() && self.state.last_was_tpl_element() {
Expand All @@ -1175,12 +1200,8 @@ impl<'a> Lexer<'a> {
}
}

let last_pos = self.cur_pos();
raw.push_str(unsafe {
// Safety: Both of start and last_pos are valid position because we got them
// from `self.input`
self.input.slice(raw_slice_start, last_pos)
});
consume_cooked!();
consume_raw!();

// TODO: Handle error
return Ok(Token::Template {
Expand All @@ -1190,12 +1211,8 @@ impl<'a> Lexer<'a> {
}

if c == '\\' {
let last_pos = self.cur_pos();
raw.push_str(unsafe {
// Safety: Both of start and last_pos are valid position because we got them
// from `self.input`
self.input.slice(raw_slice_start, last_pos)
});
consume_cooked!();
consume_raw!();

raw.push('\\');
let mut wrapped = Raw(Some(raw));
Expand All @@ -1216,17 +1233,12 @@ impl<'a> Lexer<'a> {

raw = wrapped.0.unwrap();
raw_slice_start = self.cur_pos();
cooked_slice_start = self.cur_pos();
} else if c.is_line_terminator() {
self.state.had_line_break = true;

{
let last_pos = self.cur_pos();
raw.push_str(unsafe {
// Safety: Both of start and last_pos are valid position because we got them
// from `self.input`
self.input.slice(raw_slice_start, last_pos)
});
}
consume_cooked!();
consume_raw!();

let c = if c == '\r' && self.peek() == Some('\n') {
raw.push('\r');
Expand All @@ -1249,12 +1261,9 @@ impl<'a> Lexer<'a> {
}
raw.push(c);
raw_slice_start = self.cur_pos();
cooked_slice_start = self.cur_pos();
} else {
self.bump();

if let Ok(ref mut cooked) = cooked {
cooked.push(c);
}
}
}

Expand Down

0 comments on commit 5bffd0f

Please sign in to comment.