Skip to content

Commit 6a535df

Browse files
committed
Also inline integer literals into format_args!().
1 parent df8c14c commit 6a535df

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

compiler/rustc_ast_lowering/src/format.rs

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -97,30 +97,43 @@ fn flatten_format_args(mut fmt: Cow<'_, FormatArgs>) -> Cow<'_, FormatArgs> {
9797
///
9898
/// Turns
9999
///
100-
/// `format_args!("Hello, {}! {}", "World", 123)`
100+
/// `format_args!("Hello, {}! {} {}", "World", 123, x)`
101101
///
102102
/// into
103103
///
104-
/// `format_args!("Hello, World! {}", 123)`.
104+
/// `format_args!("Hello, World! 123 {}", x)`.
105105
fn inline_literals(mut fmt: Cow<'_, FormatArgs>) -> Cow<'_, FormatArgs> {
106106
let mut was_inlined = vec![false; fmt.arguments.all_args().len()];
107107
let mut inlined_anything = false;
108108

109109
for i in 0..fmt.template.len() {
110110
let FormatArgsPiece::Placeholder(placeholder) = &fmt.template[i] else { continue };
111111
let Ok(arg_index) = placeholder.argument.index else { continue };
112+
113+
let mut literal = None;
114+
112115
if let FormatTrait::Display = placeholder.format_trait
113116
&& placeholder.format_options == Default::default()
114117
&& let arg = fmt.arguments.all_args()[arg_index].expr.peel_parens_and_refs()
115118
&& let ExprKind::Lit(lit) = arg.kind
116-
&& let token::LitKind::Str | token::LitKind::StrRaw(_) = lit.kind
117-
&& let Ok(LitKind::Str(s, _)) = LitKind::from_token_lit(lit)
118119
{
120+
if let token::LitKind::Str | token::LitKind::StrRaw(_) = lit.kind
121+
&& let Ok(LitKind::Str(s, _)) = LitKind::from_token_lit(lit)
122+
{
123+
literal = Some(s);
124+
} else if let token::LitKind::Integer = lit.kind
125+
&& let Ok(LitKind::Int(n, _)) = LitKind::from_token_lit(lit)
126+
{
127+
literal = Some(Symbol::intern(&n.to_string()));
128+
}
129+
}
130+
131+
if let Some(literal) = literal {
119132
// Now we need to mutate the outer FormatArgs.
120133
// If this is the first time, this clones the outer FormatArgs.
121134
let fmt = fmt.to_mut();
122135
// Replace the placeholder with the literal.
123-
fmt.template[i] = FormatArgsPiece::Literal(s);
136+
fmt.template[i] = FormatArgsPiece::Literal(literal);
124137
was_inlined[arg_index] = true;
125138
inlined_anything = true;
126139
}

0 commit comments

Comments
 (0)