rustc_builtin_macros/
format.rs

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