Skip to main content

rustc_builtin_macros/
format.rs

1use std::ops::Range;
2
3use parse::Position::ArgumentNamed;
4use rustc_ast::tokenstream::TokenStream;
5use rustc_ast::{
6    Expr, ExprKind, FormatAlignment, FormatArgPosition, FormatArgPositionKind, FormatArgs,
7    FormatArgsPiece, FormatArgument, FormatArgumentKind, FormatArguments, FormatCount,
8    FormatDebugHex, FormatOptions, FormatPlaceholder, FormatSign, FormatTrait, Recovered, StmtKind,
9    token,
10};
11use rustc_data_structures::fx::FxHashSet;
12use rustc_errors::{
13    Applicability, BufferedEarlyLint, DecorateDiagCompat, Diag, Diagnostic, MultiSpan, PResult,
14    SingleLabelManySpans, listify, pluralize,
15};
16use rustc_expand::base::*;
17use rustc_lint_defs::LintId;
18use rustc_lint_defs::builtin::NAMED_ARGUMENTS_USED_POSITIONALLY;
19use rustc_parse::exp;
20use rustc_parse_format as parse;
21use rustc_span::{BytePos, ErrorGuaranteed, Ident, InnerSpan, Span, Symbol};
22
23use crate::diagnostics;
24use crate::util::{ExprToSpannedString, expr_to_spanned_string};
25
26// The format_args!() macro is expanded in three steps:
27//  1. First, `parse_args` will parse the `(literal, arg, arg, name=arg, name=arg)` syntax,
28//     but doesn't parse the template (the literal) itself.
29//  2. Second, `make_format_args` will parse the template, the format options, resolve argument references,
30//     produce diagnostics, and turn the whole thing into a `FormatArgs` AST node.
31//  3. Much later, in AST lowering (rustc_ast_lowering), that `FormatArgs` structure will be turned
32//     into the expression of type `core::fmt::Arguments`.
33
34// See rustc_ast/src/format.rs for the FormatArgs structure and glossary.
35
36// Only used in parse_args and report_invalid_references,
37// to indicate how a referred argument was used.
38#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for PositionUsedAs { }
#[automatically_derived]
impl ::core::clone::Clone for PositionUsedAs {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Option<Span>>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for PositionUsedAs { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for PositionUsedAs {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Placeholder(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Placeholder", &__self_0),
            Self::Precision =>
                ::core::fmt::Formatter::write_str(f, "Precision"),
            Self::Width => ::core::fmt::Formatter::write_str(f, "Width"),
        }
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for PositionUsedAs { }
#[automatically_derived]
impl ::core::cmp::PartialEq for PositionUsedAs {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Placeholder(__self_0), Self::Placeholder(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for PositionUsedAs {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Option<Span>>;
    }
}Eq)]
39enum PositionUsedAs {
40    Placeholder(Option<Span>),
41    Precision,
42    Width,
43}
44use PositionUsedAs::*;
45
46#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MacroInput {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "MacroInput",
            "fmtstr", &self.fmtstr, "args", &self.args, "is_direct_literal",
            &&self.is_direct_literal)
    }
}Debug)]
47struct MacroInput {
48    fmtstr: Box<Expr>,
49    args: FormatArguments,
50    /// Whether the first argument was a string literal or a result from eager macro expansion.
51    /// If it's not a string literal, we disallow implicit argument capturing.
52    ///
53    /// This does not correspond to whether we can treat spans to the literal normally, as the whole
54    /// invocation might be the result of another macro expansion, in which case this flag may still be true.
55    ///
56    /// See [RFC 2795] for more information.
57    ///
58    /// [RFC 2795]: https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html#macro-hygiene
59    is_direct_literal: bool,
60}
61
62/// Parses the arguments from the given list of tokens, returning the diagnostic
63/// if there's a parse error so we can continue parsing other format!
64/// expressions.
65///
66/// If parsing succeeds, the return value is:
67///
68/// ```text
69/// Ok((fmtstr, parsed arguments))
70/// ```
71fn parse_args<'a>(ecx: &ExtCtxt<'a>, sp: Span, tts: TokenStream) -> PResult<'a, MacroInput> {
72    let mut p = ecx.new_parser_from_tts(tts);
73
74    // parse the format string
75    let fmtstr = match p.token.kind {
76        token::Eof => {
77            return Err(ecx.dcx().create_err(diagnostics::FormatRequiresString { span: sp }));
78        }
79        // This allows us to properly handle cases when the first comma
80        // after the format string is mistakenly replaced with any operator,
81        // which cause the expression parser to eat too much tokens.
82        token::Literal(token::Lit { kind: token::Str | token::StrRaw(_), .. }) => {
83            p.parse_literal_maybe_minus()?
84        }
85        // Otherwise, we fall back to the expression parser.
86        _ => p.parse_expr()?,
87    };
88
89    // parse comma FormatArgument pairs
90    let mut args = FormatArguments::new();
91    let mut first = true;
92    while p.token != token::Eof {
93        // parse a comma, or else report an error
94        if !p.eat(::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: ::rustc_parse::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
95            if first {
96                p.clear_expected_token_types();
97            }
98
99            match p.expect(::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: ::rustc_parse::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
100                Err(err) => {
101                    if token::TokenKind::Comma.similar_tokens().contains(&p.token.kind) {
102                        // If a similar token is found, then it may be a typo. We
103                        // consider it as a comma, and continue parsing.
104                        err.emit();
105                        p.bump();
106                    } else {
107                        // Otherwise stop the parsing and return the error.
108                        return Err(err);
109                    }
110                }
111                Ok(Recovered::Yes(_)) => (),
112                Ok(Recovered::No) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
113            }
114        }
115        first = false;
116        // accept a trailing comma
117        if p.token == token::Eof {
118            break;
119        }
120        // parse a FormatArgument
121        match p.token.ident() {
122            Some((ident, _)) if p.look_ahead(1, |t| *t == token::Eq) => {
123                p.bump();
124                p.expect(::rustc_parse::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: ::rustc_parse::parser::token_type::TokenType::Eq,
}exp!(Eq))?;
125                let expr = p.parse_expr()?;
126                if let Some((_, prev)) = args.by_name(ident.name) {
127                    ecx.dcx().emit_err(diagnostics::FormatDuplicateArg {
128                        span: ident.span,
129                        prev: prev.kind.ident().unwrap().span,
130                        duplicate: ident.span,
131                        ident,
132                    });
133                    continue;
134                }
135                args.add(FormatArgument {
136                    original_span: ident.span.to(expr.span),
137                    kind: FormatArgumentKind::Named(ident),
138                    expr,
139                });
140            }
141            _ => {
142                let expr = p.parse_expr()?;
143                if !args.named_args().is_empty() {
144                    return Err(ecx.dcx().create_err(diagnostics::PositionalAfterNamed {
145                        span: expr.span,
146                        args: args
147                            .named_args()
148                            .iter()
149                            .filter_map(|a| a.kind.ident().map(|ident| (a, ident)))
150                            .map(|(arg, n)| n.span.to(arg.expr.span))
151                            .collect(),
152                    }));
153                }
154                args.add(FormatArgument {
155                    original_span: expr.span,
156                    kind: FormatArgumentKind::Normal,
157                    expr,
158                });
159            }
160        }
161    }
162
163    // Only allow implicit captures for direct literals
164    let is_direct_literal = #[allow(non_exhaustive_omitted_patterns)] match fmtstr.kind {
    ExprKind::Lit(_) => true,
    _ => false,
}matches!(fmtstr.kind, ExprKind::Lit(_));
165
166    Ok(MacroInput { fmtstr, args, is_direct_literal })
167}
168
169fn make_format_args(
170    ecx: &mut ExtCtxt<'_>,
171    input: MacroInput,
172    append_newline: bool,
173    macro_span: Span,
174) -> ExpandResult<Result<FormatArgs, ErrorGuaranteed>, ()> {
175    let unexpanded_fmt_span = input.fmtstr.span;
176
177    let MacroInput { fmtstr: efmt, mut args, is_direct_literal } = input;
178
179    let ExprToSpannedString {
180        symbol: fmt_str,
181        span: fmt_span,
182        style: fmt_style,
183        uncooked_symbol: uncooked_fmt_str,
184    } = {
185        // Extract snippet so that we can check cases `{}`, `{:?}` and `{:#?}` and emit help for
186        // them later.
187        let snippet = if let ExprKind::Block(b, None) = &efmt.kind
188            && b.stmts.len() <= 1
189        {
190            Some(ecx.sess.source_map().span_to_snippet(unexpanded_fmt_span))
191        } else {
192            None
193        };
194
195        let ExpandResult::Ready(mac) =
196            expr_to_spanned_string(ecx, efmt.clone(), "format argument must be a string literal")
197        else {
198            return ExpandResult::Retry(());
199        };
200        match mac {
201            Ok(mut fmt) if append_newline => {
202                fmt.symbol = Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\n", fmt.symbol))
    })format!("{}\n", fmt.symbol));
203                fmt
204            }
205            Ok(fmt) => fmt,
206            Err(err) => {
207                let guar = match err {
208                    Ok((mut err, suggested)) => {
209                        if !suggested {
210                            if let ExprKind::Block(block, None) = &efmt.kind
211                                && let [stmt] = block.stmts.as_slice()
212                                && let StmtKind::Expr(expr) = &stmt.kind
213                                && let ExprKind::Path(None, path) = &expr.kind
214                                && path.segments.len() == 1
215                                && path.segments[0].args.is_none()
216                            {
217                                err.multipart_suggestion(
218                                    "quote your inlined format argument to use as string literal",
219                                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(unexpanded_fmt_span.shrink_to_hi(), "\"".to_string()),
                (unexpanded_fmt_span.shrink_to_lo(), "\"".to_string())]))vec![
220                                        (unexpanded_fmt_span.shrink_to_hi(), "\"".to_string()),
221                                        (unexpanded_fmt_span.shrink_to_lo(), "\"".to_string()),
222                                    ],
223                                    Applicability::MaybeIncorrect,
224                                );
225                            } else {
226                                // `{}` or `()`
227                                let should_suggest = |kind: &ExprKind| -> bool {
228                                    match kind {
229                                        ExprKind::Block(b, None) if b.stmts.is_empty() => true,
230                                        ExprKind::Tup(v) if v.is_empty() => true,
231                                        _ => false,
232                                    }
233                                };
234
235                                let mut sugg_fmt = String::new();
236                                for kind in std::iter::once(&efmt.kind)
237                                    .chain(args.explicit_args().iter().map(|a| &a.expr.kind))
238                                {
239                                    sugg_fmt.push_str(if should_suggest(kind) {
240                                        "{:?} "
241                                    } else {
242                                        "{} "
243                                    });
244                                }
245                                sugg_fmt = sugg_fmt.trim_end().to_string();
246                                err.span_suggestion_verbose(
247                                    unexpanded_fmt_span.shrink_to_lo(),
248                                    "you might be missing a string literal to format with",
249                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\", ", sugg_fmt))
    })format!("\"{sugg_fmt}\", "),
250                                    Applicability::MaybeIncorrect,
251                                );
252
253                                if let Some(Ok(snippet)) = snippet.as_ref() {
254                                    match snippet.as_str() {
255                                        "{}" | "{:?}" | "{:#?}" => {
256                                            err.span_suggestion_verbose(
257                                                unexpanded_fmt_span,
258                                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("you might want to enclose `{0}` with `\"\"`",
                snippet))
    })format!("you might want to enclose `{snippet}` with `\"\"`"),
259                                                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}\"", snippet))
    })format!("\"{snippet}\""),
260                                                Applicability::MaybeIncorrect,
261                                            );
262                                        }
263                                        _ => {}
264                                    };
265                                }
266                            }
267                        }
268                        err.emit_err()
269                    }
270                    Err(guar) => guar,
271                };
272                return ExpandResult::Ready(Err(guar));
273            }
274        }
275    };
276
277    let str_style = match fmt_style {
278        rustc_ast::StrStyle::Cooked => None,
279        rustc_ast::StrStyle::Raw(raw) => Some(raw as usize),
280    };
281
282    let fmt_str = fmt_str.as_str(); // for the suggestions below
283    let fmt_snippet = ecx.source_map().span_to_snippet(unexpanded_fmt_span).ok();
284    let mut parser = parse::Parser::new(
285        fmt_str,
286        str_style,
287        fmt_snippet,
288        append_newline,
289        parse::ParseMode::Format,
290    );
291
292    let mut pieces = Vec::new();
293    while let Some(piece) = parser.next() {
294        if !parser.errors.is_empty() {
295            break;
296        } else {
297            pieces.push(piece);
298        }
299    }
300
301    let is_source_literal = parser.is_source_literal;
302
303    if !parser.errors.is_empty() {
304        let err = parser.errors.remove(0);
305        let sp = if is_source_literal {
306            fmt_span.from_inner(InnerSpan::new(err.span.start, err.span.end))
307        } else {
308            // The format string could be another macro invocation, e.g.:
309            //     format!(concat!("abc", "{}"), 4);
310            // However, `err.span` is an inner span relative to the *result* of
311            // the macro invocation, which is why we would get a nonsensical
312            // result calling `fmt_span.from_inner(err.span)` as above, and
313            // might even end up inside a multibyte character (issue #86085).
314            // Therefore, we conservatively report the error for the entire
315            // argument span here.
316            fmt_span
317        };
318        let mut e = diagnostics::InvalidFormatString {
319            span: sp,
320            note_: None,
321            label_: None,
322            sugg_: None,
323            desc: err.description,
324            label1: err.label,
325        };
326        if let Some(note) = err.note {
327            e.note_ = Some(diagnostics::InvalidFormatStringNote { note });
328        }
329        if let Some((label, span)) = err.secondary_label
330            && is_source_literal
331        {
332            e.label_ = Some(diagnostics::InvalidFormatStringLabel {
333                span: fmt_span.from_inner(InnerSpan::new(span.start, span.end)),
334                label,
335            });
336        }
337        match err.suggestion {
338            parse::Suggestion::None => {}
339            parse::Suggestion::UsePositional => {
340                let captured_arg_span =
341                    fmt_span.from_inner(InnerSpan::new(err.span.start, err.span.end));
342                if is_source_literal
343                    && let Ok(arg) = ecx.source_map().span_to_snippet(captured_arg_span)
344                {
345                    let span = match args.unnamed_args().last() {
346                        Some(arg) => arg.expr.span,
347                        None => fmt_span,
348                    };
349                    e.sugg_ = Some(diagnostics::InvalidFormatStringSuggestion::UsePositional {
350                        captured: captured_arg_span,
351                        len: args.unnamed_args().len().to_string(),
352                        span: span.shrink_to_hi(),
353                        arg,
354                    });
355                }
356            }
357            parse::Suggestion::RemoveRawIdent(span) => {
358                if is_source_literal {
359                    let span = fmt_span.from_inner(InnerSpan::new(span.start, span.end));
360                    e.sugg_ =
361                        Some(diagnostics::InvalidFormatStringSuggestion::RemoveRawIdent { span })
362                }
363            }
364            parse::Suggestion::ReorderFormatParameter(span, replacement) => {
365                if is_source_literal {
366                    let span = fmt_span.from_inner(InnerSpan::new(span.start, span.end));
367                    e.sugg_ =
368                        Some(diagnostics::InvalidFormatStringSuggestion::ReorderFormatParameter {
369                            span,
370                            replacement,
371                        });
372                }
373            }
374            parse::Suggestion::AddMissingColon(span) => {
375                if is_source_literal {
376                    let span = fmt_span.from_inner(InnerSpan::new(span.start, span.end));
377                    e.sugg_ =
378                        Some(diagnostics::InvalidFormatStringSuggestion::AddMissingColon { span });
379                }
380            }
381            parse::Suggestion::UseRustDebugPrintingMacro => {
382                // This targets `println!("{=}", x);` and `println!("{0=}", x);`
383                if let [arg] = args.all_args() {
384                    let expr_span = arg.expr.span;
385                    if let Ok(expr_snippet) = ecx.source_map().span_to_snippet(expr_span) {
386                        let replacement = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}!({1})", "dbg", expr_snippet))
    })format!("{}!({})", "dbg", expr_snippet);
387
388                        let call_span = macro_span.source_callsite();
389                        e.sugg_ = Some(
390                            diagnostics::InvalidFormatStringSuggestion::UseRustDebugPrintingMacro {
391                                macro_span: call_span,
392                                replacement,
393                            },
394                        );
395                    }
396                }
397            }
398        }
399        let guar = ecx.dcx().emit_err(e);
400        return ExpandResult::Ready(Err(guar));
401    }
402
403    let to_span = |inner_span: Range<usize>| {
404        is_source_literal.then(|| {
405            fmt_span.from_inner(InnerSpan { start: inner_span.start, end: inner_span.end })
406        })
407    };
408
409    let mut used = ::alloc::vec::from_elem(false, args.explicit_args().len())vec![false; args.explicit_args().len()];
410    let mut invalid_refs = Vec::new();
411    let mut numeric_references_to_named_arg = Vec::new();
412
413    enum ArgRef<'a> {
414        Index(usize),
415        Name(&'a str, Option<Span>),
416    }
417    use ArgRef::*;
418
419    let mut unnamed_arg_after_named_arg = false;
420
421    let mut lookup_arg = |arg: ArgRef<'_>,
422                          span: Option<Span>,
423                          used_as: PositionUsedAs,
424                          kind: FormatArgPositionKind|
425     -> FormatArgPosition {
426        let index = match arg {
427            Index(index) => {
428                if let Some(arg) = args.by_index(index) {
429                    used[index] = true;
430                    if arg.kind.ident().is_some() {
431                        // This was a named argument, but it was used as a positional argument.
432                        numeric_references_to_named_arg.push((index, span, used_as));
433                    }
434                    Ok(index)
435                } else {
436                    // Doesn't exist as an explicit argument.
437                    invalid_refs.push((index, span, used_as, kind));
438                    Err(index)
439                }
440            }
441            Name(name, span) => {
442                let name = Symbol::intern(name);
443                if let Some((index, _)) = args.by_name(name) {
444                    // Name found in `args`, so we resolve it to its index.
445                    if index < args.explicit_args().len() {
446                        // Mark it as used, if it was an explicit argument.
447                        used[index] = true;
448                    }
449                    Ok(index)
450                } else {
451                    // Name not found in `args`, so we add it as an implicitly captured argument.
452                    let span = span.unwrap_or(fmt_span);
453                    let ident = Ident::new(name, span);
454                    let expr = if is_direct_literal {
455                        ecx.expr_ident(span, ident)
456                    } else {
457                        // For the moment capturing variables from format strings expanded from macros is
458                        // disabled (see RFC #2795)
459                        let guar = ecx.dcx().emit_err(diagnostics::FormatNoArgNamed { span, name });
460                        unnamed_arg_after_named_arg = true;
461                        DummyResult::raw_expr(span, Some(guar))
462                    };
463                    Ok(args.add(FormatArgument {
464                        original_span: span,
465                        kind: FormatArgumentKind::Captured(ident),
466                        expr,
467                    }))
468                }
469            }
470        };
471        FormatArgPosition { index, kind, span }
472    };
473
474    let mut template = Vec::new();
475    let mut unfinished_literal = String::new();
476    let mut placeholder_index = 0;
477
478    for piece in &pieces {
479        match piece.clone() {
480            parse::Piece::Lit(s) => {
481                unfinished_literal.push_str(s);
482            }
483            parse::Piece::NextArgument(parse::Argument { position, position_span, format }) => {
484                if !unfinished_literal.is_empty() {
485                    template.push(FormatArgsPiece::Literal(Symbol::intern(&unfinished_literal)));
486                    unfinished_literal.clear();
487                }
488
489                let span =
490                    parser.arg_places.get(placeholder_index).and_then(|s| to_span(s.clone()));
491                placeholder_index += 1;
492
493                let position_span = to_span(position_span);
494                let argument = match position {
495                    parse::ArgumentImplicitlyIs(i) => lookup_arg(
496                        Index(i),
497                        position_span,
498                        Placeholder(span),
499                        FormatArgPositionKind::Implicit,
500                    ),
501                    parse::ArgumentIs(i) => lookup_arg(
502                        Index(i),
503                        position_span,
504                        Placeholder(span),
505                        FormatArgPositionKind::Number,
506                    ),
507                    parse::ArgumentNamed(name) => lookup_arg(
508                        Name(name, position_span),
509                        position_span,
510                        Placeholder(span),
511                        FormatArgPositionKind::Named,
512                    ),
513                };
514
515                let alignment = match format.align {
516                    parse::AlignUnknown => None,
517                    parse::AlignLeft => Some(FormatAlignment::Left),
518                    parse::AlignRight => Some(FormatAlignment::Right),
519                    parse::AlignCenter => Some(FormatAlignment::Center),
520                };
521
522                let format_trait = match format.ty {
523                    "" => FormatTrait::Display,
524                    "?" => FormatTrait::Debug,
525                    "e" => FormatTrait::LowerExp,
526                    "E" => FormatTrait::UpperExp,
527                    "o" => FormatTrait::Octal,
528                    "p" => FormatTrait::Pointer,
529                    "b" => FormatTrait::Binary,
530                    "x" => FormatTrait::LowerHex,
531                    "X" => FormatTrait::UpperHex,
532                    _ => {
533                        invalid_placeholder_type_error(ecx, format.ty, format.ty_span, fmt_span);
534                        FormatTrait::Display
535                    }
536                };
537
538                let precision_span = format.precision_span.and_then(to_span);
539                let precision = match format.precision {
540                    parse::CountIs(n) => Some(FormatCount::Literal(n)),
541                    parse::CountIsName(name, name_span) => Some(FormatCount::Argument(lookup_arg(
542                        Name(name, to_span(name_span)),
543                        precision_span,
544                        Precision,
545                        FormatArgPositionKind::Named,
546                    ))),
547                    parse::CountIsParam(i) => Some(FormatCount::Argument(lookup_arg(
548                        Index(i),
549                        precision_span,
550                        Precision,
551                        FormatArgPositionKind::Number,
552                    ))),
553                    parse::CountIsStar(i) => Some(FormatCount::Argument(lookup_arg(
554                        Index(i),
555                        precision_span,
556                        Precision,
557                        FormatArgPositionKind::Implicit,
558                    ))),
559                    parse::CountImplied => None,
560                };
561
562                let width_span = format.width_span.and_then(to_span);
563                let width = match format.width {
564                    parse::CountIs(n) => Some(FormatCount::Literal(n)),
565                    parse::CountIsName(name, name_span) => Some(FormatCount::Argument(lookup_arg(
566                        Name(name, to_span(name_span)),
567                        width_span,
568                        Width,
569                        FormatArgPositionKind::Named,
570                    ))),
571                    parse::CountIsParam(i) => Some(FormatCount::Argument(lookup_arg(
572                        Index(i),
573                        width_span,
574                        Width,
575                        FormatArgPositionKind::Number,
576                    ))),
577                    parse::CountIsStar(_) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
578                    parse::CountImplied => None,
579                };
580
581                template.push(FormatArgsPiece::Placeholder(FormatPlaceholder {
582                    argument,
583                    span,
584                    format_trait,
585                    format_options: FormatOptions {
586                        fill: format.fill,
587                        alignment,
588                        sign: format.sign.map(|s| match s {
589                            parse::Sign::Plus => FormatSign::Plus,
590                            parse::Sign::Minus => FormatSign::Minus,
591                        }),
592                        alternate: format.alternate,
593                        zero_pad: format.zero_pad,
594                        debug_hex: format.debug_hex.map(|s| match s {
595                            parse::DebugHex::Lower => FormatDebugHex::Lower,
596                            parse::DebugHex::Upper => FormatDebugHex::Upper,
597                        }),
598                        precision,
599                        width,
600                    },
601                }));
602            }
603        }
604    }
605
606    if !unfinished_literal.is_empty() {
607        template.push(FormatArgsPiece::Literal(Symbol::intern(&unfinished_literal)));
608    }
609
610    if !invalid_refs.is_empty() {
611        report_invalid_references(ecx, &invalid_refs, &template, fmt_span, &args, parser);
612    }
613
614    let unused = used
615        .iter()
616        .enumerate()
617        .filter(|&(_, used)| !used)
618        .map(|(i, _)| {
619            let named = #[allow(non_exhaustive_omitted_patterns)] match args.explicit_args()[i].kind {
    FormatArgumentKind::Named(_) => true,
    _ => false,
}matches!(args.explicit_args()[i].kind, FormatArgumentKind::Named(_));
620            (args.explicit_args()[i].expr.span, named)
621        })
622        .collect::<Vec<_>>();
623
624    let has_unused = !unused.is_empty();
625    if has_unused {
626        let foreign_fmt_str =
627            if append_newline { fmt_str.strip_suffix('\n').unwrap_or(fmt_str) } else { fmt_str };
628        report_missing_placeholders(
629            ecx,
630            unused,
631            &used,
632            &args,
633            &pieces,
634            &invalid_refs,
635            str_style,
636            foreign_fmt_str,
637            uncooked_fmt_str.1.as_str(),
638            fmt_span,
639        );
640    }
641
642    // Only check for unused named argument names if there are no other errors to avoid causing
643    // too much noise in output errors, such as when a named argument is entirely unused.
644    if invalid_refs.is_empty() && !has_unused && !unnamed_arg_after_named_arg {
645        for &(index, span, used_as) in &numeric_references_to_named_arg {
646            let (position_sp_to_replace, position_sp_for_msg) = match used_as {
647                Placeholder(pspan) => (span, pspan),
648                Precision => {
649                    // Strip the leading `.` for precision.
650                    let span = span.map(|span| span.with_lo(span.lo() + BytePos(1)));
651                    (span, span)
652                }
653                Width => (span, span),
654            };
655            let arg_name = args.explicit_args()[index].kind.ident().unwrap();
656            ecx.buffered_early_lint.push(BufferedEarlyLint {
657                span: Some(arg_name.span.into()),
658                node_id: rustc_ast::CRATE_NODE_ID,
659                lint_id: LintId::of(NAMED_ARGUMENTS_USED_POSITIONALLY),
660                diagnostic: DecorateDiagCompat(Box::new(move |dcx, level, sess| {
661                    let (suggestion, name) =
662                        if let Some(positional_arg_to_replace) = position_sp_to_replace {
663                            let mut name = arg_name.name.to_string();
664                            let is_formatting_arg = #[allow(non_exhaustive_omitted_patterns)] match used_as {
    Width | Precision => true,
    _ => false,
}matches!(used_as, Width | Precision);
665                            if is_formatting_arg {
666                                name.push('$')
667                            };
668                            let span_to_replace = if let Ok(positional_arg_content) = sess
669                                .downcast_ref::<rustc_session::Session>()
670                                .expect("expected a `Session`")
671                                .source_map()
672                                .span_to_snippet(positional_arg_to_replace)
673                                && positional_arg_content.starts_with(':')
674                            {
675                                positional_arg_to_replace.shrink_to_lo()
676                            } else {
677                                positional_arg_to_replace
678                            };
679                            (Some(span_to_replace), name)
680                        } else {
681                            (None, String::new())
682                        };
683
684                    diagnostics::NamedArgumentUsedPositionally {
685                        named_arg_sp: arg_name.span,
686                        position_label_sp: position_sp_for_msg,
687                        suggestion,
688                        name,
689                        named_arg_name: arg_name.name.to_string(),
690                    }
691                    .into_diag(dcx, level)
692                })),
693            });
694        }
695    }
696
697    ExpandResult::Ready(Ok(FormatArgs {
698        span: fmt_span,
699        template,
700        arguments: args,
701        uncooked_fmt_str,
702        is_source_literal,
703    }))
704}
705
706fn invalid_placeholder_type_error(
707    ecx: &ExtCtxt<'_>,
708    ty: &str,
709    ty_span: Option<Range<usize>>,
710    fmt_span: Span,
711) {
712    let sp = ty_span.map(|sp| fmt_span.from_inner(InnerSpan::new(sp.start, sp.end)));
713    let suggs = if let Some(sp) = sp {
714        [
715            ("", "Display"),
716            ("?", "Debug"),
717            ("e", "LowerExp"),
718            ("E", "UpperExp"),
719            ("o", "Octal"),
720            ("p", "Pointer"),
721            ("b", "Binary"),
722            ("x", "LowerHex"),
723            ("X", "UpperHex"),
724        ]
725        .into_iter()
726        .map(|(fmt, trait_name)| diagnostics::FormatUnknownTraitSugg { span: sp, fmt, trait_name })
727        .collect()
728    } else {
729        ::alloc::vec::Vec::new()vec![]
730    };
731    ecx.dcx().emit_err(diagnostics::FormatUnknownTrait { span: sp.unwrap_or(fmt_span), ty, suggs });
732}
733
734fn report_missing_placeholders(
735    ecx: &ExtCtxt<'_>,
736    unused: Vec<(Span, bool)>,
737    used: &[bool],
738    args: &FormatArguments,
739    pieces: &[parse::Piece<'_>],
740    invalid_refs: &[(usize, Option<Span>, PositionUsedAs, FormatArgPositionKind)],
741    str_style: Option<usize>,
742    fmt_str: &str,
743    uncooked_fmt_str: &str,
744    fmt_span: Span,
745) {
746    let mut diag = if let &[(span, named)] = &unused[..] {
747        ecx.dcx().create_err(diagnostics::FormatUnusedArg { span, named })
748    } else {
749        let unused_labels = unused
750            .iter()
751            .map(|&(span, named)| diagnostics::FormatUnusedArg { span, named })
752            .collect();
753        let unused_spans = unused.iter().map(|&(span, _)| span).collect();
754        ecx.dcx().create_err(diagnostics::FormatUnusedArgs {
755            fmt: fmt_span,
756            unused: unused_spans,
757            unused_labels,
758        })
759    };
760
761    let placeholders = pieces
762        .iter()
763        .filter_map(|piece| {
764            if let parse::Piece::NextArgument(argument) = piece
765                && let ArgumentNamed(binding) = argument.position
766            {
767                let span = fmt_span.from_inner(InnerSpan::new(
768                    argument.position_span.start,
769                    argument.position_span.end,
770                ));
771                Some((span, binding))
772            } else {
773                None
774            }
775        })
776        .collect::<Vec<_>>();
777
778    if !placeholders.is_empty() {
779        if let Some(new_diag) = report_redundant_format_arguments(ecx, args, used, placeholders) {
780            diag.cancel();
781            new_diag.emit();
782            return;
783        }
784    }
785
786    // Used to ensure we only report translations for *one* kind of foreign format.
787    let mut found_foreign = false;
788
789    // If there's a lot of unused arguments,
790    // let's check if this format arguments looks like another syntax (printf / shell).
791    if unused.len() > args.explicit_args().len() / 2 {
792        use super::format_foreign as foreign;
793
794        // The set of foreign substitutions we've explained. This prevents spamming the user
795        // with `%d should be written as {}` over and over again.
796        let mut explained = FxHashSet::default();
797
798        macro_rules! check_foreign {
799            ($kind:ident) => {{
800                let mut show_doc_note = false;
801
802                let mut suggestions = vec![];
803                // account for `"` and account for raw strings `r#`
804                let padding = str_style.map(|i| i + 2).unwrap_or(1);
805                for sub in foreign::$kind::iter_subs(fmt_str, padding) {
806                    let (trn, success) = match sub.translate() {
807                        Ok(trn) => (trn, true),
808                        Err(Some(msg)) => (msg, false),
809
810                        // If it has no translation, don't call it out specifically.
811                        _ => continue,
812                    };
813
814                    let pos = sub.position();
815                    if !explained.insert(sub.to_string()) {
816                        continue;
817                    }
818
819                    if !found_foreign {
820                        found_foreign = true;
821                        show_doc_note = true;
822                    }
823
824                    let sp = fmt_span.from_inner(pos);
825
826                    if success {
827                        suggestions.push((sp, trn));
828                    } else {
829                        diag.span_note(
830                            sp,
831                            format!("format specifiers use curly braces, and {}", trn),
832                        );
833                    }
834                }
835
836                if show_doc_note {
837                    diag.note(concat!(
838                        stringify!($kind),
839                        " formatting is not supported; see the documentation for `std::fmt`",
840                    ));
841                }
842                if suggestions.len() > 0 {
843                    diag.multipart_suggestion(
844                        "format specifiers use curly braces",
845                        suggestions,
846                        Applicability::MachineApplicable,
847                    );
848                }
849            }};
850        }
851
852        {
    let mut show_doc_note = false;
    let mut suggestions = ::alloc::vec::Vec::new();
    let padding = str_style.map(|i| i + 2).unwrap_or(1);
    for sub in foreign::printf::iter_subs(fmt_str, padding) {
        let (trn, success) =
            match sub.translate() {
                Ok(trn) => (trn, true),
                Err(Some(msg)) => (msg, false),
                _ => continue,
            };
        let pos = sub.position();
        if !explained.insert(sub.to_string()) { continue; }
        if !found_foreign { found_foreign = true; show_doc_note = true; }
        let sp = fmt_span.from_inner(pos);
        if success {
            suggestions.push((sp, trn));
        } else {
            diag.span_note(sp,
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("format specifiers use curly braces, and {0}",
                                trn))
                    }));
        }
    }
    if show_doc_note {
        diag.note("printf formatting is not supported; see the documentation for `std::fmt`");
    }
    if suggestions.len() > 0 {
        diag.multipart_suggestion("format specifiers use curly braces",
            suggestions, Applicability::MachineApplicable);
    }
};check_foreign!(printf);
853        if !found_foreign {
854            {
    let mut show_doc_note = false;
    let mut suggestions = ::alloc::vec::Vec::new();
    let padding = str_style.map(|i| i + 2).unwrap_or(1);
    for sub in foreign::shell::iter_subs(fmt_str, padding) {
        let (trn, success) =
            match sub.translate() {
                Ok(trn) => (trn, true),
                Err(Some(msg)) => (msg, false),
                _ => continue,
            };
        let pos = sub.position();
        if !explained.insert(sub.to_string()) { continue; }
        if !found_foreign { found_foreign = true; show_doc_note = true; }
        let sp = fmt_span.from_inner(pos);
        if success {
            suggestions.push((sp, trn));
        } else {
            diag.span_note(sp,
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("format specifiers use curly braces, and {0}",
                                trn))
                    }));
        }
    }
    if show_doc_note {
        diag.note("shell formatting is not supported; see the documentation for `std::fmt`");
    }
    if suggestions.len() > 0 {
        diag.multipart_suggestion("format specifiers use curly braces",
            suggestions, Applicability::MachineApplicable);
    }
};check_foreign!(shell);
855        }
856    }
857    if !found_foreign && unused.len() == 1 {
858        diag.span_label(fmt_span, "formatting specifier missing");
859    }
860
861    if !found_foreign && invalid_refs.is_empty() {
862        // Show example if user didn't use any format specifiers
863        let show_example = !used.contains(&true);
864
865        if !show_example {
866            if unused.len() > 1 {
867                diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider adding {0} format specifiers",
                unused.len()))
    })format!("consider adding {} format specifiers", unused.len()));
868            }
869        } else {
870            let msg = if unused.len() == 1 {
871                "a format specifier".to_string()
872            } else {
873                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} format specifiers",
                unused.len()))
    })format!("{} format specifiers", unused.len())
874            };
875
876            let sugg = match str_style {
877                None => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("\"{0}{1}\"", uncooked_fmt_str,
                "{}".repeat(unused.len())))
    })format!("\"{}{}\"", uncooked_fmt_str, "{}".repeat(unused.len())),
878                Some(n_hashes) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("r{0}\"{2}{1}\"{0}",
                "#".repeat(n_hashes), "{}".repeat(unused.len()),
                uncooked_fmt_str))
    })format!(
879                    "r{hashes}\"{uncooked_fmt_str}{fmt_specifiers}\"{hashes}",
880                    hashes = "#".repeat(n_hashes),
881                    fmt_specifiers = "{}".repeat(unused.len())
882                ),
883            };
884            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("format specifiers use curly braces, consider adding {0}",
                msg))
    })format!("format specifiers use curly braces, consider adding {msg}");
885
886            diag.span_suggestion_verbose(fmt_span, msg, sugg, Applicability::MaybeIncorrect);
887        }
888    }
889
890    diag.emit();
891}
892
893/// This function detects and reports unused format!() arguments that are
894/// redundant due to implicit captures (e.g. `format!("{x}", x)`).
895fn report_redundant_format_arguments<'a>(
896    ecx: &ExtCtxt<'a>,
897    args: &FormatArguments,
898    used: &[bool],
899    placeholders: Vec<(Span, &str)>,
900) -> Option<Diag<'a>> {
901    let mut fmt_arg_indices = ::alloc::vec::Vec::new()vec![];
902    let mut args_spans = ::alloc::vec::Vec::new()vec![];
903    let mut fmt_spans = ::alloc::vec::Vec::new()vec![];
904
905    for (i, unnamed_arg) in args.unnamed_args().iter().enumerate().rev() {
906        let Some(ty) = unnamed_arg.expr.to_ty() else { continue };
907        let Some(argument_binding) = ty.kind.is_simple_path() else { continue };
908        let argument_binding = argument_binding.as_str();
909
910        if used[i] {
911            continue;
912        }
913
914        let matching_placeholders = placeholders
915            .iter()
916            .filter(|(_, inline_binding)| argument_binding == *inline_binding)
917            .map(|(span, _)| span)
918            .collect::<Vec<_>>();
919
920        if !matching_placeholders.is_empty() {
921            fmt_arg_indices.push(i);
922            args_spans.push(unnamed_arg.expr.span);
923            for span in &matching_placeholders {
924                if fmt_spans.contains(*span) {
925                    continue;
926                }
927                fmt_spans.push(**span);
928            }
929        }
930    }
931
932    if !args_spans.is_empty() {
933        let multispan = MultiSpan::from(fmt_spans);
934        let mut suggestion_spans = ::alloc::vec::Vec::new()vec![];
935
936        for (arg_span, fmt_arg_idx) in args_spans.iter().zip(fmt_arg_indices.iter()) {
937            let span = if fmt_arg_idx + 1 == args.explicit_args().len() {
938                *arg_span
939            } else {
940                arg_span.until(args.explicit_args()[*fmt_arg_idx + 1].expr.span)
941            };
942
943            suggestion_spans.push(span);
944        }
945
946        let sugg = if args.named_args().is_empty() {
947            Some(diagnostics::FormatRedundantArgsSugg { spans: suggestion_spans })
948        } else {
949            None
950        };
951
952        return Some(ecx.dcx().create_err(diagnostics::FormatRedundantArgs {
953            n: args_spans.len(),
954            span: MultiSpan::from(args_spans),
955            note: multispan,
956            sugg,
957        }));
958    }
959
960    None
961}
962
963/// Handle invalid references to positional arguments. Output different
964/// errors for the case where all arguments are positional and for when
965/// there are named arguments or numbered positional arguments in the
966/// format string.
967fn report_invalid_references(
968    ecx: &ExtCtxt<'_>,
969    invalid_refs: &[(usize, Option<Span>, PositionUsedAs, FormatArgPositionKind)],
970    template: &[FormatArgsPiece],
971    fmt_span: Span,
972    args: &FormatArguments,
973    parser: parse::Parser<'_>,
974) {
975    let num_args_desc = match args.explicit_args().len() {
976        0 => "no arguments were given".to_string(),
977        1 => "there is 1 argument".to_string(),
978        n => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("there are {0} arguments", n))
    })format!("there are {n} arguments"),
979    };
980
981    let mut e;
982
983    if template.iter().all(|piece| match piece {
984        FormatArgsPiece::Placeholder(FormatPlaceholder {
985            argument: FormatArgPosition { kind: FormatArgPositionKind::Number, .. },
986            ..
987        }) => false,
988        FormatArgsPiece::Placeholder(FormatPlaceholder {
989            format_options:
990                FormatOptions {
991                    precision:
992                        Some(FormatCount::Argument(FormatArgPosition {
993                            kind: FormatArgPositionKind::Number,
994                            ..
995                        })),
996                    ..
997                }
998                | FormatOptions {
999                    width:
1000                        Some(FormatCount::Argument(FormatArgPosition {
1001                            kind: FormatArgPositionKind::Number,
1002                            ..
1003                        })),
1004                    ..
1005                },
1006            ..
1007        }) => false,
1008        _ => true,
1009    }) {
1010        // There are no numeric positions.
1011        // Collect all the implicit positions:
1012        let mut spans = Vec::new();
1013        let mut num_placeholders = 0;
1014        let mut has_white_space_only_missing_arg = false;
1015        for piece in template {
1016            let mut placeholder = None;
1017            // `{arg:.*}`
1018            if let FormatArgsPiece::Placeholder(FormatPlaceholder {
1019                format_options:
1020                    FormatOptions {
1021                        precision:
1022                            Some(FormatCount::Argument(FormatArgPosition {
1023                                span,
1024                                kind: FormatArgPositionKind::Implicit,
1025                                ..
1026                            })),
1027                        ..
1028                    },
1029                ..
1030            }) = piece
1031            {
1032                placeholder = *span;
1033                num_placeholders += 1;
1034            }
1035            // `{}`
1036            if let FormatArgsPiece::Placeholder(FormatPlaceholder {
1037                argument: FormatArgPosition { kind: FormatArgPositionKind::Implicit, index, .. },
1038                span,
1039                ..
1040            }) = piece
1041            {
1042                placeholder = *span;
1043                num_placeholders += 1;
1044                //  Check whether there's any non-space whitespace in the placeholder. If so, we should emit a note suggesting an escaping `{`.
1045                if index.is_err()
1046                    && let Some(span) = span
1047                    && let Ok(snippet) = ecx.source_map().span_to_snippet(*span)
1048                    && snippet.chars().any(|c| c.is_whitespace() && c != ' ')
1049                {
1050                    has_white_space_only_missing_arg = true;
1051                }
1052            }
1053            // For `{:.*}`, we only push one span.
1054            spans.extend(placeholder);
1055        }
1056        let span = if spans.is_empty() {
1057            MultiSpan::from_span(fmt_span)
1058        } else {
1059            MultiSpan::from_spans(spans)
1060        };
1061        e = ecx.dcx().create_err(diagnostics::FormatPositionalMismatch {
1062            span,
1063            n: num_placeholders,
1064            desc: num_args_desc,
1065            highlight: SingleLabelManySpans {
1066                spans: args.explicit_args().iter().map(|arg| arg.expr.span).collect(),
1067                label: "",
1068            },
1069        });
1070        // Point out `{:.*}` placeholders: those take an extra argument.
1071        let mut has_precision_star = false;
1072        for piece in template {
1073            if let FormatArgsPiece::Placeholder(FormatPlaceholder {
1074                format_options:
1075                    FormatOptions {
1076                        precision:
1077                            Some(FormatCount::Argument(FormatArgPosition {
1078                                index,
1079                                span: Some(span),
1080                                kind: FormatArgPositionKind::Implicit,
1081                                ..
1082                            })),
1083                        ..
1084                    },
1085                ..
1086            }) = piece
1087            {
1088                let (Ok(index) | Err(index)) = index;
1089                has_precision_star = true;
1090                e.span_label(
1091                    *span,
1092                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this precision flag adds an extra required argument at position {0}, which is why there {1} expected",
                index,
                if num_placeholders == 1 {
                    "is 1 argument".to_string()
                } else {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("are {0} arguments",
                                    num_placeholders))
                        })
                }))
    })format!(
1093                        "this precision flag adds an extra required argument at position {}, which is why there {} expected",
1094                        index,
1095                        if num_placeholders == 1 {
1096                            "is 1 argument".to_string()
1097                        } else {
1098                            format!("are {num_placeholders} arguments")
1099                        },
1100                    ),
1101                );
1102            }
1103        }
1104        if has_precision_star {
1105            e.note("positional arguments are zero-based");
1106        }
1107        if has_white_space_only_missing_arg {
1108            e.note("if you intended to print `{`, you can escape it with `{{`");
1109        }
1110    } else {
1111        let mut indexes: Vec<_> = invalid_refs.iter().map(|&(index, _, _, _)| index).collect();
1112        // Avoid `invalid reference to positional arguments 7 and 7 (there is 1 argument)`
1113        // for `println!("{7:7$}", 1);`
1114        indexes.sort();
1115        indexes.dedup();
1116        let span = if !parser.is_source_literal || parser.arg_places.is_empty() {
1117            MultiSpan::from_span(fmt_span)
1118        } else {
1119            MultiSpan::from_spans(invalid_refs.iter().filter_map(|&(_, span, _, _)| span).collect())
1120        };
1121        let arg_list = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("argument{0} {1}",
                if indexes.len() == 1 { "" } else { "s" },
                listify(&indexes,
                        |i: &usize| i.to_string()).unwrap_or_default()))
    })format!(
1122            "argument{} {}",
1123            pluralize!(indexes.len()),
1124            listify(&indexes, |i: &usize| i.to_string()).unwrap_or_default()
1125        );
1126        e = ecx.dcx().struct_span_err(
1127            span,
1128            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("invalid reference to positional {0} ({1})",
                arg_list, num_args_desc))
    })format!("invalid reference to positional {arg_list} ({num_args_desc})"),
1129        );
1130        e.note("positional arguments are zero-based");
1131    }
1132
1133    if template.iter().any(|piece| match piece {
1134        FormatArgsPiece::Placeholder(FormatPlaceholder { format_options: f, .. }) => {
1135            *f != FormatOptions::default()
1136        }
1137        _ => false,
1138    }) {
1139        e.note("for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html");
1140    }
1141
1142    e.emit();
1143}
1144
1145fn expand_format_args_impl<'cx>(
1146    ecx: &'cx mut ExtCtxt<'_>,
1147    mut sp: Span,
1148    tts: TokenStream,
1149    nl: bool,
1150) -> MacroExpanderResult<'cx> {
1151    sp = ecx.with_def_site_ctxt(sp);
1152    ExpandResult::Ready(match parse_args(ecx, sp, tts) {
1153        Ok(input) => {
1154            let ExpandResult::Ready(mac) = make_format_args(ecx, input, nl, sp) else {
1155                return ExpandResult::Retry(());
1156            };
1157            match mac {
1158                Ok(format_args) => {
1159                    MacEager::expr(ecx.expr(sp, ExprKind::FormatArgs(Box::new(format_args))))
1160                }
1161                Err(guar) => MacEager::expr(DummyResult::raw_expr(sp, Some(guar))),
1162            }
1163        }
1164        Err(err) => {
1165            let guar = err.emit_err();
1166            DummyResult::any(sp, guar)
1167        }
1168    })
1169}
1170
1171pub(crate) fn expand_format_args<'cx>(
1172    ecx: &'cx mut ExtCtxt<'_>,
1173    sp: Span,
1174    tts: TokenStream,
1175) -> MacroExpanderResult<'cx> {
1176    expand_format_args_impl(ecx, sp, tts, false)
1177}
1178
1179pub(crate) fn expand_format_args_nl<'cx>(
1180    ecx: &'cx mut ExtCtxt<'_>,
1181    sp: Span,
1182    tts: TokenStream,
1183) -> MacroExpanderResult<'cx> {
1184    expand_format_args_impl(ecx, sp, tts, true)
1185}