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#[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 is_direct_literal: bool,
60}
61
62fn 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 p.parse_literal_maybe_minus()?
89 } else {
90 p.parse_expr()?
92 };
93
94 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 err.emit();
112 p.bump();
113 } else {
114 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 } 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 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(); 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 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 numeric_references_to_named_arg.push((index, span, used_as));
370 }
371 Ok(index)
372 } else {
373 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 if index < args.explicit_args().len() {
383 used[index] = true;
385 }
386 Ok(index)
387 } else {
388 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 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 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 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 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 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 detect_foreign_fmt: bool,
648 str_style: Option<usize>,
649 fmt_str: &str,
650 fmt_span: Span,
651) {
652 let mut diag = if let &[(span, named)] = &unused[..] {
653 ecx.dcx().create_err(errors::FormatUnusedArg { span, named })
654 } else {
655 let unused_labels =
656 unused.iter().map(|&(span, named)| errors::FormatUnusedArg { span, named }).collect();
657 let unused_spans = unused.iter().map(|&(span, _)| span).collect();
658 ecx.dcx().create_err(errors::FormatUnusedArgs {
659 fmt: fmt_span,
660 unused: unused_spans,
661 unused_labels,
662 })
663 };
664
665 let placeholders = pieces
666 .iter()
667 .filter_map(|piece| {
668 if let parse::Piece::NextArgument(argument) = piece
669 && let ArgumentNamed(binding) = argument.position
670 {
671 let span = fmt_span.from_inner(InnerSpan::new(
672 argument.position_span.start,
673 argument.position_span.end,
674 ));
675 Some((span, binding))
676 } else {
677 None
678 }
679 })
680 .collect::<Vec<_>>();
681
682 if !placeholders.is_empty() {
683 if let Some(new_diag) = report_redundant_format_arguments(ecx, args, used, placeholders) {
684 diag.cancel();
685 new_diag.emit();
686 return;
687 }
688 }
689
690 let mut found_foreign = false;
692
693 if detect_foreign_fmt {
695 use super::format_foreign as foreign;
696
697 let mut explained = FxHashSet::default();
700
701 macro_rules! check_foreign {
702 ($kind:ident) => {{
703 let mut show_doc_note = false;
704
705 let mut suggestions = vec![];
706 let padding = str_style.map(|i| i + 2).unwrap_or(1);
708 for sub in foreign::$kind::iter_subs(fmt_str, padding) {
709 let (trn, success) = match sub.translate() {
710 Ok(trn) => (trn, true),
711 Err(Some(msg)) => (msg, false),
712
713 _ => continue,
715 };
716
717 let pos = sub.position();
718 if !explained.insert(sub.to_string()) {
719 continue;
720 }
721
722 if !found_foreign {
723 found_foreign = true;
724 show_doc_note = true;
725 }
726
727 let sp = fmt_span.from_inner(pos);
728
729 if success {
730 suggestions.push((sp, trn));
731 } else {
732 diag.span_note(
733 sp,
734 format!("format specifiers use curly braces, and {}", trn),
735 );
736 }
737 }
738
739 if show_doc_note {
740 diag.note(concat!(
741 stringify!($kind),
742 " formatting is not supported; see the documentation for `std::fmt`",
743 ));
744 }
745 if suggestions.len() > 0 {
746 diag.multipart_suggestion(
747 "format specifiers use curly braces",
748 suggestions,
749 Applicability::MachineApplicable,
750 );
751 }
752 }};
753 }
754
755 check_foreign!(printf);
756 if !found_foreign {
757 check_foreign!(shell);
758 }
759 }
760 if !found_foreign && unused.len() == 1 {
761 diag.span_label(fmt_span, "formatting specifier missing");
762 }
763
764 diag.emit();
765}
766
767fn report_redundant_format_arguments<'a>(
770 ecx: &ExtCtxt<'a>,
771 args: &FormatArguments,
772 used: &[bool],
773 placeholders: Vec<(Span, &str)>,
774) -> Option<Diag<'a>> {
775 let mut fmt_arg_indices = vec![];
776 let mut args_spans = vec![];
777 let mut fmt_spans = vec![];
778
779 for (i, unnamed_arg) in args.unnamed_args().iter().enumerate().rev() {
780 let Some(ty) = unnamed_arg.expr.to_ty() else { continue };
781 let Some(argument_binding) = ty.kind.is_simple_path() else { continue };
782 let argument_binding = argument_binding.as_str();
783
784 if used[i] {
785 continue;
786 }
787
788 let matching_placeholders = placeholders
789 .iter()
790 .filter(|(_, inline_binding)| argument_binding == *inline_binding)
791 .map(|(span, _)| span)
792 .collect::<Vec<_>>();
793
794 if !matching_placeholders.is_empty() {
795 fmt_arg_indices.push(i);
796 args_spans.push(unnamed_arg.expr.span);
797 for span in &matching_placeholders {
798 if fmt_spans.contains(*span) {
799 continue;
800 }
801 fmt_spans.push(**span);
802 }
803 }
804 }
805
806 if !args_spans.is_empty() {
807 let multispan = MultiSpan::from(fmt_spans);
808 let mut suggestion_spans = vec![];
809
810 for (arg_span, fmt_arg_idx) in args_spans.iter().zip(fmt_arg_indices.iter()) {
811 let span = if fmt_arg_idx + 1 == args.explicit_args().len() {
812 *arg_span
813 } else {
814 arg_span.until(args.explicit_args()[*fmt_arg_idx + 1].expr.span)
815 };
816
817 suggestion_spans.push(span);
818 }
819
820 let sugg = if args.named_args().len() == 0 {
821 Some(errors::FormatRedundantArgsSugg { spans: suggestion_spans })
822 } else {
823 None
824 };
825
826 return Some(ecx.dcx().create_err(errors::FormatRedundantArgs {
827 n: args_spans.len(),
828 span: MultiSpan::from(args_spans),
829 note: multispan,
830 sugg,
831 }));
832 }
833
834 None
835}
836
837fn report_invalid_references(
842 ecx: &ExtCtxt<'_>,
843 invalid_refs: &[(usize, Option<Span>, PositionUsedAs, FormatArgPositionKind)],
844 template: &[FormatArgsPiece],
845 fmt_span: Span,
846 args: &FormatArguments,
847 parser: parse::Parser<'_>,
848) {
849 let num_args_desc = match args.explicit_args().len() {
850 0 => "no arguments were given".to_string(),
851 1 => "there is 1 argument".to_string(),
852 n => format!("there are {n} arguments"),
853 };
854
855 let mut e;
856
857 if template.iter().all(|piece| match piece {
858 FormatArgsPiece::Placeholder(FormatPlaceholder {
859 argument: FormatArgPosition { kind: FormatArgPositionKind::Number, .. },
860 ..
861 }) => false,
862 FormatArgsPiece::Placeholder(FormatPlaceholder {
863 format_options:
864 FormatOptions {
865 precision:
866 Some(FormatCount::Argument(FormatArgPosition {
867 kind: FormatArgPositionKind::Number,
868 ..
869 })),
870 ..
871 }
872 | FormatOptions {
873 width:
874 Some(FormatCount::Argument(FormatArgPosition {
875 kind: FormatArgPositionKind::Number,
876 ..
877 })),
878 ..
879 },
880 ..
881 }) => false,
882 _ => true,
883 }) {
884 let mut spans = Vec::new();
887 let mut num_placeholders = 0;
888 for piece in template {
889 let mut placeholder = None;
890 if let FormatArgsPiece::Placeholder(FormatPlaceholder {
892 format_options:
893 FormatOptions {
894 precision:
895 Some(FormatCount::Argument(FormatArgPosition {
896 span,
897 kind: FormatArgPositionKind::Implicit,
898 ..
899 })),
900 ..
901 },
902 ..
903 }) = piece
904 {
905 placeholder = *span;
906 num_placeholders += 1;
907 }
908 if let FormatArgsPiece::Placeholder(FormatPlaceholder {
910 argument: FormatArgPosition { kind: FormatArgPositionKind::Implicit, .. },
911 span,
912 ..
913 }) = piece
914 {
915 placeholder = *span;
916 num_placeholders += 1;
917 }
918 spans.extend(placeholder);
920 }
921 let span = if spans.is_empty() {
922 MultiSpan::from_span(fmt_span)
923 } else {
924 MultiSpan::from_spans(spans)
925 };
926 e = ecx.dcx().create_err(errors::FormatPositionalMismatch {
927 span,
928 n: num_placeholders,
929 desc: num_args_desc,
930 highlight: SingleLabelManySpans {
931 spans: args.explicit_args().iter().map(|arg| arg.expr.span).collect(),
932 label: "",
933 },
934 });
935 let mut has_precision_star = false;
937 for piece in template {
938 if let FormatArgsPiece::Placeholder(FormatPlaceholder {
939 format_options:
940 FormatOptions {
941 precision:
942 Some(FormatCount::Argument(FormatArgPosition {
943 index,
944 span: Some(span),
945 kind: FormatArgPositionKind::Implicit,
946 ..
947 })),
948 ..
949 },
950 ..
951 }) = piece
952 {
953 let (Ok(index) | Err(index)) = index;
954 has_precision_star = true;
955 e.span_label(
956 *span,
957 format!(
958 "this precision flag adds an extra required argument at position {}, which is why there {} expected",
959 index,
960 if num_placeholders == 1 {
961 "is 1 argument".to_string()
962 } else {
963 format!("are {num_placeholders} arguments")
964 },
965 ),
966 );
967 }
968 }
969 if has_precision_star {
970 e.note("positional arguments are zero-based");
971 }
972 } else {
973 let mut indexes: Vec<_> = invalid_refs.iter().map(|&(index, _, _, _)| index).collect();
974 indexes.sort();
977 indexes.dedup();
978 let span: MultiSpan = if !parser.is_source_literal || parser.arg_places.is_empty() {
979 MultiSpan::from_span(fmt_span)
980 } else {
981 MultiSpan::from_spans(invalid_refs.iter().filter_map(|&(_, span, _, _)| span).collect())
982 };
983 let arg_list = format!(
984 "argument{} {}",
985 pluralize!(indexes.len()),
986 listify(&indexes, |i: &usize| i.to_string()).unwrap_or_default()
987 );
988 e = ecx.dcx().struct_span_err(
989 span,
990 format!("invalid reference to positional {arg_list} ({num_args_desc})"),
991 );
992 e.note("positional arguments are zero-based");
993 }
994
995 if template.iter().any(|piece| match piece {
996 FormatArgsPiece::Placeholder(FormatPlaceholder { format_options: f, .. }) => {
997 *f != FormatOptions::default()
998 }
999 _ => false,
1000 }) {
1001 e.note("for information about formatting flags, visit https://doc.rust-lang.org/std/fmt/index.html");
1002 }
1003
1004 e.emit();
1005}
1006
1007fn expand_format_args_impl<'cx>(
1008 ecx: &'cx mut ExtCtxt<'_>,
1009 mut sp: Span,
1010 tts: TokenStream,
1011 nl: bool,
1012) -> MacroExpanderResult<'cx> {
1013 sp = ecx.with_def_site_ctxt(sp);
1014 ExpandResult::Ready(match parse_args(ecx, sp, tts) {
1015 Ok(input) => {
1016 let ExpandResult::Ready(mac) = make_format_args(ecx, input, nl) else {
1017 return ExpandResult::Retry(());
1018 };
1019 match mac {
1020 Ok(format_args) => {
1021 MacEager::expr(ecx.expr(sp, ExprKind::FormatArgs(P(format_args))))
1022 }
1023 Err(guar) => MacEager::expr(DummyResult::raw_expr(sp, Some(guar))),
1024 }
1025 }
1026 Err(err) => {
1027 let guar = err.emit();
1028 DummyResult::any(sp, guar)
1029 }
1030 })
1031}
1032
1033pub(crate) fn expand_format_args<'cx>(
1034 ecx: &'cx mut ExtCtxt<'_>,
1035 sp: Span,
1036 tts: TokenStream,
1037) -> MacroExpanderResult<'cx> {
1038 expand_format_args_impl(ecx, sp, tts, false)
1039}
1040
1041pub(crate) fn expand_format_args_nl<'cx>(
1042 ecx: &'cx mut ExtCtxt<'_>,
1043 sp: Span,
1044 tts: TokenStream,
1045) -> MacroExpanderResult<'cx> {
1046 expand_format_args_impl(ecx, sp, tts, true)
1047}