Skip to content

Commit 94ad7e8

Browse files
committed
Coalesce adjacent literal pieces in expand_format_args.
1 parent a769b30 commit 94ad7e8

File tree

1 file changed

+16
-16
lines changed

1 file changed

+16
-16
lines changed

compiler/rustc_ast_lowering/src/format.rs

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -75,23 +75,9 @@ fn flatten_format_args(fmt: &FormatArgs) -> Cow<'_, FormatArgs> {
7575

7676
// Now merge the placeholders:
7777

78-
let mut rest = fmt.template.split_off(i + 1);
78+
let rest = fmt.template.split_off(i + 1);
7979
fmt.template.pop(); // remove the placeholder for the nested fmt args.
8080

81-
// Coalesce adjacent literals.
82-
if let Some(FormatArgsPiece::Literal(s1)) = fmt.template.last() &&
83-
let Some(FormatArgsPiece::Literal(s2)) = fmt2.template.first_mut()
84-
{
85-
*s2 = Symbol::intern(&(s1.as_str().to_owned() + s2.as_str()));
86-
fmt.template.pop();
87-
}
88-
if let Some(FormatArgsPiece::Literal(s1)) = fmt2.template.last() &&
89-
let Some(FormatArgsPiece::Literal(s2)) = rest.first_mut()
90-
{
91-
*s2 = Symbol::intern(&(s1.as_str().to_owned() + s2.as_str()));
92-
fmt2.template.pop();
93-
}
94-
9581
for piece in fmt2.template {
9682
match piece {
9783
FormatArgsPiece::Literal(s) => fmt.template.push(FormatArgsPiece::Literal(s)),
@@ -288,10 +274,24 @@ fn expand_format_args<'hir>(
288274
macsp: Span,
289275
fmt: &FormatArgs,
290276
) -> hir::ExprKind<'hir> {
277+
let mut incomplete_lit = String::new();
291278
let lit_pieces =
292279
ctx.arena.alloc_from_iter(fmt.template.iter().enumerate().filter_map(|(i, piece)| {
293280
match piece {
294-
&FormatArgsPiece::Literal(s) => Some(ctx.expr_str(fmt.span, s)),
281+
&FormatArgsPiece::Literal(s) => {
282+
// Coalesce adjacent literal pieces.
283+
if let Some(FormatArgsPiece::Literal(_)) = fmt.template.get(i + 1) {
284+
incomplete_lit.push_str(s.as_str());
285+
None
286+
} else if !incomplete_lit.is_empty() {
287+
incomplete_lit.push_str(s.as_str());
288+
let s = Symbol::intern(&incomplete_lit);
289+
incomplete_lit.clear();
290+
Some(ctx.expr_str(fmt.span, s))
291+
} else {
292+
Some(ctx.expr_str(fmt.span, s))
293+
}
294+
}
295295
&FormatArgsPiece::Placeholder(_) => {
296296
// Inject empty string before placeholders when not already preceded by a literal piece.
297297
if i == 0 || matches!(fmt.template[i - 1], FormatArgsPiece::Placeholder(_)) {

0 commit comments

Comments
 (0)