Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(es/parser): Optimize lexing of template literals #9036

Merged
merged 3 commits into from
Jun 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions crates/swc_ecma_parser/src/lexer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1160,6 +1160,7 @@ impl<'a> Lexer<'a> {

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

while let Some(c) = self.cur() {
if c == '`' || (c == '$' && self.peek() == Some('{')) {
Expand All @@ -1174,6 +1175,13 @@ 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)
});

// TODO: Handle error
return Ok(Token::Template {
cooked: cooked.map(Atom::from),
Expand All @@ -1182,8 +1190,14 @@ impl<'a> Lexer<'a> {
}

if c == '\\' {
raw.push('\\');
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)
});

raw.push('\\');
let mut wrapped = Raw(Some(raw));

match self.read_escaped_char(&mut wrapped, true) {
Expand All @@ -1201,9 +1215,19 @@ impl<'a> Lexer<'a> {
}

raw = wrapped.0.unwrap();
raw_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)
});
}

let c = if c == '\r' && self.peek() == Some('\n') {
raw.push('\r');
self.bump(); // '\r'
Expand All @@ -1223,16 +1247,14 @@ impl<'a> Lexer<'a> {
if let Ok(ref mut cooked) = cooked {
cooked.push(c);
}

raw.push(c);
raw_slice_start = self.cur_pos();
} else {
self.bump();

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should cooked have the same optimization?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think so. I'll patch it tomorrow.

}

raw.push(c);
}
}

Expand Down
Loading