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