Skip to content

Commit 5bf2ad3

Browse files
committed
syntax: Optimize some literal parsing
Currently in the `wasm-bindgen` project we have a very very large crate that's procedurally generated, `web-sys`. To generate this crate we parse all of a browser's WebIDL and we then generate bindings for all of the APIs contained within. The resulting Rust file is 18MB large (wow!) and currently takes a very long time to compile in debug mode. On the nightly compiler a *debug* build takes 90s for the crate to finish. I was curious what was taking so long and upon investigating a *massive* portion of the time was spent in the `lit_token` method of the compiler, primarily formatting strings via `format!`. Upon some more investigation it looks like the `byte_str_lit` was allocating an error message once per byte, causing a very large number of allocations to happen for large literals, of which wasm-bindgen generates quite a few (some are MB large). This commit fixes the issue by lazily allocating the error message, only doing so if the error message is actually needed (which should be never). As a result, the debug mode compilation time for our `web-sys` crate decreased from 90s to 20s, a very nice improvement! (although we've still got some work to do).
1 parent 3ac79c7 commit 5bf2ad3

File tree

1 file changed

+4
-6
lines changed

1 file changed

+4
-6
lines changed

src/libsyntax/parse/mod.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -532,7 +532,7 @@ fn byte_lit(lit: &str) -> (u8, usize) {
532532
fn byte_str_lit(lit: &str) -> Lrc<Vec<u8>> {
533533
let mut res = Vec::with_capacity(lit.len());
534534

535-
let error = |i| format!("lexer should have rejected {} at {}", lit, i);
535+
let error = |i| panic!("lexer should have rejected {} at {}", lit, i);
536536

537537
/// Eat everything up to a non-whitespace
538538
fn eat<I: Iterator<Item=(usize, u8)>>(it: &mut iter::Peekable<I>) {
@@ -551,12 +551,11 @@ fn byte_str_lit(lit: &str) -> Lrc<Vec<u8>> {
551551
loop {
552552
match chars.next() {
553553
Some((i, b'\\')) => {
554-
let em = error(i);
555-
match chars.peek().expect(&em).1 {
554+
match chars.peek().unwrap_or_else(|| error(i)).1 {
556555
b'\n' => eat(&mut chars),
557556
b'\r' => {
558557
chars.next();
559-
if chars.peek().expect(&em).1 != b'\n' {
558+
if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
560559
panic!("lexer accepted bare CR");
561560
}
562561
eat(&mut chars);
@@ -573,8 +572,7 @@ fn byte_str_lit(lit: &str) -> Lrc<Vec<u8>> {
573572
}
574573
},
575574
Some((i, b'\r')) => {
576-
let em = error(i);
577-
if chars.peek().expect(&em).1 != b'\n' {
575+
if chars.peek().unwrap_or_else(|| error(i)).1 != b'\n' {
578576
panic!("lexer accepted bare CR");
579577
}
580578
chars.next();

0 commit comments

Comments
 (0)