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