Skip to content

Commit 65ea0ff

Browse files
committed
Optimize string handling in lit_token().
In the common case, the string value in a string literal Token is the same as the string value in a string literal LitKind. (The exception is when escapes or \r are involved.) This patch takes advantage of that to avoid calling str_lit() and re-interning the string in that case. This speeds up incremental builds for a few of the rustc-benchmarks, the best by 3%.
1 parent f9bfe84 commit 65ea0ff

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

src/libsyntax/parse/mod.rs

+17-6
Original file line numberDiff line numberDiff line change
@@ -419,13 +419,24 @@ pub fn lit_token(lit: token::Lit, suf: Option<Symbol>, diag: Option<(Span, &Hand
419419
token::Integer(s) => (false, integer_lit(&s.as_str(), suf, diag)),
420420
token::Float(s) => (false, float_lit(&s.as_str(), suf, diag)),
421421

422-
token::Str_(s) => {
423-
let s = Symbol::intern(&str_lit(&s.as_str(), diag));
424-
(true, Some(LitKind::Str(s, ast::StrStyle::Cooked)))
422+
token::Str_(mut sym) => {
423+
// If there are no characters requiring special treatment we can
424+
// reuse the symbol from the Token. Otherwise, we must generate a
425+
// new symbol because the string in the LitKind is different to the
426+
// string in the Token.
427+
let s = &sym.as_str();
428+
if s.as_bytes().iter().any(|&c| c == b'\\' || c == b'\r') {
429+
sym = Symbol::intern(&str_lit(s, diag));
430+
}
431+
(true, Some(LitKind::Str(sym, ast::StrStyle::Cooked)))
425432
}
426-
token::StrRaw(s, n) => {
427-
let s = Symbol::intern(&raw_str_lit(&s.as_str()));
428-
(true, Some(LitKind::Str(s, ast::StrStyle::Raw(n))))
433+
token::StrRaw(mut sym, n) => {
434+
// Ditto.
435+
let s = &sym.as_str();
436+
if s.contains('\r') {
437+
sym = Symbol::intern(&raw_str_lit(s));
438+
}
439+
(true, Some(LitKind::Str(sym, ast::StrStyle::Raw(n))))
429440
}
430441
token::ByteStr(i) => {
431442
(true, Some(LitKind::ByteStr(byte_str_lit(&i.as_str()))))

0 commit comments

Comments
 (0)