6 use rustc_ast::tokenstream::TokenStream;
7 use rustc_ast::visit::{self, Visitor};
8 use rustc_ast::{token, BlockCheckMode, UnsafeSource};
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use rustc_errors::{pluralize, Applicability, MultiSpan, PResult};
11 use rustc_expand::base::{self, *};
12 use rustc_parse_format as parse;
13 use rustc_span::symbol::{sym, Ident, Symbol};
14 use rustc_span::{BytePos, InnerSpan, Span};
15 use smallvec::SmallVec;
17 use rustc_lint_defs::builtin::NAMED_ARGUMENTS_USED_POSITIONALLY;
18 use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics, LintId};
19 use rustc_parse_format::Count;
21 use std::collections::hash_map::Entry;
25 Placeholder(&'static str),
32 Named(Symbol, InnerSpan),
35 /// Indicates how positional named argument (i.e. an named argument which is used by position
36 /// instead of by name) is used in format string
37 /// * `Arg` is the actual argument to print
38 /// * `Width` is width format argument
39 /// * `Precision` is precion format argument
40 /// Example: `{Arg:Width$.Precision$}
41 #[derive(Debug, Eq, PartialEq)]
42 enum PositionalNamedArgType {
48 /// Contains information necessary to create a lint for a positional named argument
50 struct PositionalNamedArg {
51 ty: PositionalNamedArgType,
52 /// The piece of the using this argument (multiple pieces can use the same argument)
54 /// The InnerSpan for in the string to be replaced with the named argument
55 /// This will be None when the position is implicit
56 inner_span_to_replace: Option<rustc_parse_format::InnerSpan>,
57 /// The name to use instead of the position
59 /// The span for the positional named argument (so the lint can point a message to it)
60 positional_named_arg_span: Span,
64 impl PositionalNamedArg {
66 /// 1) span to be replaced with the name of the named argument and
67 /// 2) span to be underlined for error messages
68 fn get_positional_arg_spans(&self, cx: &Context<'_, '_>) -> (Option<Span>, Option<Span>) {
69 if let Some(inner_span) = &self.inner_span_to_replace {
71 cx.fmtsp.from_inner(InnerSpan { start: inner_span.start, end: inner_span.end });
72 (Some(span), Some(span))
73 } else if self.ty == PositionalNamedArgType::Arg {
74 // In the case of a named argument whose position is implicit, if the argument *has*
75 // formatting, there will not be a span to replace. Instead, we insert the name after
76 // the `{`, which will be the first character of arg_span. If the argument does *not*
77 // have formatting, there may or may not be a span to replace. This is because
78 // whitespace is allowed in arguments without formatting (such as `format!("{ }", 1);`)
79 // but is not allowed in arguments with formatting (an error will be generated in cases
80 // like `format!("{ :1.1}", 1.0f32);`.
81 // For the message span, if there is formatting, we want to use the opening `{` and the
82 // next character, which will the `:` indicating the start of formatting. If there is
83 // not any formatting, we want to underline the entire span.
84 cx.arg_spans.get(self.cur_piece).map_or((None, None), |arg_span| {
85 if self.has_formatting {
87 Some(arg_span.with_lo(arg_span.lo() + BytePos(1)).shrink_to_lo()),
88 Some(arg_span.with_hi(arg_span.lo() + BytePos(2))),
91 let replace_start = arg_span.lo() + BytePos(1);
92 let replace_end = arg_span.hi() - BytePos(1);
93 let to_replace = arg_span.with_lo(replace_start).with_hi(replace_end);
94 (Some(to_replace), Some(*arg_span))
103 /// Encapsulates all the named arguments that have been used positionally
105 struct PositionalNamedArgsLint {
106 positional_named_args: Vec<PositionalNamedArg>,
109 impl PositionalNamedArgsLint {
110 /// For a given positional argument, check if the index is for a named argument.
112 /// Since positional arguments are required to come before named arguments, if the positional
113 /// index is greater than or equal to the start of named arguments, we know it's a named
114 /// argument used positionally.
117 /// println!("{} {} {2}", 0, a=1, b=2);
119 /// In this case, the first piece (`{}`) would be ArgumentImplicitlyIs with an index of 0. The
120 /// total number of arguments is 3 and the number of named arguments is 2, so the start of named
121 /// arguments is index 1. Therefore, the index of 0 is okay.
123 /// The second piece (`{}`) would be ArgumentImplicitlyIs with an index of 1, which is the start
124 /// of named arguments, and so we should add a lint to use the named argument `a`.
126 /// The third piece (`{2}`) would be ArgumentIs with an index of 2, which is greater than the
127 /// start of named arguments, and so we should add a lint to use the named argument `b`.
129 /// This same check also works for width and precision formatting when either or both are
130 /// CountIsParam, which contains an index into the arguments.
131 fn maybe_add_positional_named_arg(
133 arg: Option<&FormatArg>,
134 ty: PositionalNamedArgType,
136 inner_span_to_replace: Option<rustc_parse_format::InnerSpan>,
137 has_formatting: bool,
139 if let Some(arg) = arg {
140 if let Some(name) = arg.name {
141 self.push(name, ty, cur_piece, inner_span_to_replace, has_formatting)
146 /// Construct a PositionalNamedArg struct and push it into the vec of positional
151 ty: PositionalNamedArgType,
153 inner_span_to_replace: Option<rustc_parse_format::InnerSpan>,
154 has_formatting: bool,
156 // In FormatSpec, `precision_span` starts at the leading `.`, which we want to keep in
157 // the lint suggestion, so increment `start` by 1 when `PositionalArgumentType` is
159 let inner_span_to_replace = if ty == PositionalNamedArgType::Precision {
160 inner_span_to_replace
161 .map(|is| rustc_parse_format::InnerSpan { start: is.start + 1, end: is.end })
163 inner_span_to_replace
165 self.positional_named_args.push(PositionalNamedArg {
168 inner_span_to_replace,
169 replacement: arg_name.name,
170 positional_named_arg_span: arg_name.span,
176 struct Context<'a, 'b> {
177 ecx: &'a mut ExtCtxt<'b>,
178 /// The macro's call site. References to unstable formatting internals must
179 /// use this span to pass the stability checker.
181 /// The span of the format string literal.
184 /// List of parsed argument expressions.
185 /// Named expressions are resolved early, and are appended to the end of
186 /// argument expressions.
188 /// Example showing the various data structures in motion:
190 /// * Original: `"{foo:o} {:o} {foo:x} {0:x} {1:o} {:x} {1:x} {0:o}"`
191 /// * Implicit argument resolution: `"{foo:o} {0:o} {foo:x} {0:x} {1:o} {1:x} {1:x} {0:o}"`
192 /// * Name resolution: `"{2:o} {0:o} {2:x} {0:x} {1:o} {1:x} {1:x} {0:o}"`
193 /// * `arg_types` (in JSON): `[[0, 1, 0], [0, 1, 1], [0, 1]]`
194 /// * `arg_unique_types` (in simplified JSON): `[["o", "x"], ["o", "x"], ["o", "x"]]`
195 /// * `names` (in JSON): `{"foo": 2}`
196 args: Vec<FormatArg>,
197 /// The number of arguments that were added by implicit capturing.
198 num_captured_args: usize,
199 /// Placeholder slot numbers indexed by argument.
200 arg_types: Vec<Vec<usize>>,
201 /// Unique format specs seen for each argument.
202 arg_unique_types: Vec<Vec<ArgumentType>>,
203 /// Map from named arguments to their resolved indices.
204 names: FxHashMap<Symbol, usize>,
206 /// The latest consecutive literal strings, or empty if there weren't any.
209 /// Collection of the compiled `rt::Argument` structures
210 pieces: Vec<P<ast::Expr>>,
211 /// Collection of string literals
212 str_pieces: Vec<P<ast::Expr>>,
213 /// Stays `true` if all formatting parameters are default (as in "{}{}").
214 all_pieces_simple: bool,
216 /// Mapping between positional argument references and indices into the
217 /// final generated static argument array. We record the starting indices
218 /// corresponding to each positional argument, and number of references
219 /// consumed so far for each argument, to facilitate correct `Position`
220 /// mapping in `build_piece`. In effect this can be seen as a "flattened"
221 /// version of `arg_unique_types`.
223 /// Again with the example described above in docstring for `args`:
225 /// * `arg_index_map` (in JSON): `[[0, 1, 0], [2, 3, 3], [4, 5]]`
226 arg_index_map: Vec<Vec<usize>>,
228 /// Starting offset of count argument slots.
229 count_args_index_offset: usize,
231 /// Count argument slots and tracking data structures.
232 /// Count arguments are separately tracked for de-duplication in case
233 /// multiple references are made to one argument. For example, in this
236 /// * Original: `"{:.*} {:.foo$} {1:.*} {:.0$}"`
237 /// * Implicit argument resolution: `"{1:.0$} {2:.foo$} {1:.3$} {4:.0$}"`
238 /// * Name resolution: `"{1:.0$} {2:.5$} {1:.3$} {4:.0$}"`
239 /// * `count_positions` (in JSON): `{0: 0, 5: 1, 3: 2}`
240 /// * `count_args`: `vec![0, 5, 3]`
241 count_args: Vec<usize>,
242 /// Relative slot numbers for count arguments.
243 count_positions: FxHashMap<usize, usize>,
244 /// Number of count slots assigned.
245 count_positions_count: usize,
247 /// Current position of the implicit positional arg pointer, as if it
248 /// still existed in this phase of processing.
249 /// Used only for `all_pieces_simple` tracking in `build_piece`.
251 /// Current piece being evaluated, used for error reporting.
253 /// Keep track of invalid references to positional arguments.
254 invalid_refs: Vec<(usize, usize)>,
255 /// Spans of all the formatting arguments, in order.
256 arg_spans: Vec<Span>,
257 /// All the formatting arguments that have formatting flags set, in order for diagnostics.
258 arg_with_formatting: Vec<parse::FormatSpec<'a>>,
260 /// Whether this format string came from a string literal, as opposed to a macro.
262 unused_names_lint: PositionalNamedArgsLint,
265 pub struct FormatArg {
270 /// Parses the arguments from the given list of tokens, returning the diagnostic
271 /// if there's a parse error so we can continue parsing other format!
274 /// If parsing succeeds, the return value is:
277 /// Some((fmtstr, parsed arguments, index map for named arguments))
280 ecx: &mut ExtCtxt<'a>,
283 ) -> PResult<'a, (P<ast::Expr>, Vec<FormatArg>, FxHashMap<Symbol, usize>)> {
284 let mut args = Vec::<FormatArg>::new();
285 let mut names = FxHashMap::<Symbol, usize>::default();
287 let mut p = ecx.new_parser_from_tts(tts);
289 if p.token == token::Eof {
290 return Err(ecx.struct_span_err(sp, "requires at least a format string argument"));
293 let first_token = &p.token;
294 let fmtstr = match first_token.kind {
295 token::TokenKind::Literal(token::Lit {
296 kind: token::LitKind::Str | token::LitKind::StrRaw(_),
299 // If the first token is a string literal, then a format expression
300 // is constructed from it.
302 // This allows us to properly handle cases when the first comma
303 // after the format string is mistakenly replaced with any operator,
304 // which cause the expression parser to eat too much tokens.
305 p.parse_literal_maybe_minus()?
308 // Otherwise, we fall back to the expression parser.
313 let mut first = true;
314 let mut named = false;
316 while p.token != token::Eof {
317 if !p.eat(&token::Comma) {
319 p.clear_expected_tokens();
322 match p.expect(&token::Comma) {
324 match token::TokenKind::Comma.similar_tokens() {
325 Some(tks) if tks.contains(&p.token.kind) => {
326 // If a similar token is found, then it may be a typo. We
327 // consider it as a comma, and continue parsing.
331 // Otherwise stop the parsing and return the error.
332 _ => return Err(err),
341 if p.token == token::Eof {
343 } // accept trailing commas
344 match p.token.ident() {
345 Some((ident, _)) if p.look_ahead(1, |t| *t == token::Eq) => {
348 p.expect(&token::Eq)?;
349 let e = p.parse_expr()?;
350 if let Some(&prev) = names.get(&ident.name) {
351 ecx.struct_span_err(e.span, &format!("duplicate argument named `{}`", ident))
352 .span_label(args[prev].expr.span, "previously here")
353 .span_label(e.span, "duplicate argument")
358 // Resolve names into slots early.
359 // Since all the positional args are already seen at this point
360 // if the input is valid, we can simply append to the positional
361 // args. And remember the names.
362 let slot = args.len();
363 names.insert(ident.name, slot);
364 args.push(FormatArg { expr: e, name: Some(ident) });
367 let e = p.parse_expr()?;
369 let mut err = ecx.struct_span_err(
371 "positional arguments cannot follow named arguments",
373 err.span_label(e.span, "positional arguments must be before named arguments");
374 for &pos in names.values() {
375 err.span_label(args[pos].expr.span, "named argument");
379 args.push(FormatArg { expr: e, name: None });
383 Ok((fmtstr, args, names))
386 impl<'a, 'b> Context<'a, 'b> {
387 /// The number of arguments that were explicitly given.
388 fn num_args(&self) -> usize {
389 self.args.len() - self.num_captured_args
392 fn resolve_name_inplace(&mut self, p: &mut parse::Piece<'_>) {
393 // NOTE: the `unwrap_or` branch is needed in case of invalid format
394 // arguments, e.g., `format_args!("{foo}")`.
395 let lookup = |s: &str| self.names.get(&Symbol::intern(s)).copied().unwrap_or(0);
398 parse::String(_) => {}
399 parse::NextArgument(ref mut arg) => {
400 if let parse::ArgumentNamed(s) = arg.position {
401 arg.position = parse::ArgumentIs(lookup(s));
403 if let parse::CountIsName(s, _) = arg.format.width {
404 arg.format.width = parse::CountIsParam(lookup(s));
406 if let parse::CountIsName(s, _) = arg.format.precision {
407 arg.format.precision = parse::CountIsParam(lookup(s));
413 /// Verifies one piece of a parse string, and remembers it if valid.
414 /// All errors are not emitted as fatal so we can continue giving errors
415 /// about this and possibly other format strings.
416 fn verify_piece(&mut self, p: &parse::Piece<'_>) {
418 parse::String(..) => {}
419 parse::NextArgument(ref arg) => {
420 // width/precision first, if they have implicit positional
421 // parameters it makes more sense to consume them first.
424 &arg.format.width_span,
425 PositionalNamedArgType::Width,
428 arg.format.precision,
429 &arg.format.precision_span,
430 PositionalNamedArgType::Precision,
433 let has_precision = arg.format.precision != Count::CountImplied;
434 let has_width = arg.format.width != Count::CountImplied;
436 // argument second, if it's an implicit positional parameter
437 // it's written second, so it should come after width/precision.
438 let pos = match arg.position {
439 parse::ArgumentIs(i) => {
440 self.unused_names_lint.maybe_add_positional_named_arg(
442 PositionalNamedArgType::Arg,
444 Some(arg.position_span),
445 has_precision || has_width,
450 parse::ArgumentImplicitlyIs(i) => {
451 self.unused_names_lint.maybe_add_positional_named_arg(
453 PositionalNamedArgType::Arg,
456 has_precision || has_width,
460 parse::ArgumentNamed(s) => {
461 let symbol = Symbol::intern(s);
462 let span = arg.position_span;
463 Named(symbol, InnerSpan::new(span.start, span.end))
467 let ty = Placeholder(match arg.format.ty {
478 let fmtsp = self.fmtsp;
482 .map(|sp| fmtsp.from_inner(InnerSpan::new(sp.start, sp.end)));
483 let mut err = self.ecx.struct_span_err(
485 &format!("unknown format trait `{}`", arg.format.ty),
488 "the only appropriate formatting traits are:\n\
489 - ``, which uses the `Display` trait\n\
490 - `?`, which uses the `Debug` trait\n\
491 - `e`, which uses the `LowerExp` trait\n\
492 - `E`, which uses the `UpperExp` trait\n\
493 - `o`, which uses the `Octal` trait\n\
494 - `p`, which uses the `Pointer` trait\n\
495 - `b`, which uses the `Binary` trait\n\
496 - `x`, which uses the `LowerHex` trait\n\
497 - `X`, which uses the `UpperHex` trait",
499 if let Some(sp) = sp {
500 for (fmt, name) in &[
511 // FIXME: rustfix (`run-rustfix`) fails to apply suggestions.
512 // > "Cannot replace slice of data that was already replaced"
513 err.tool_only_span_suggestion(
515 &format!("use the `{}` trait", name),
517 Applicability::MaybeIncorrect,
525 self.verify_arg_type(pos, ty);
534 inner_span: &Option<rustc_parse_format::InnerSpan>,
535 named_arg_type: PositionalNamedArgType,
538 parse::CountImplied | parse::CountIs(..) => {}
539 parse::CountIsParam(i) => {
540 self.unused_names_lint.maybe_add_positional_named_arg(
547 self.verify_arg_type(Exact(i), Count);
549 parse::CountIsName(s, span) => {
550 self.verify_arg_type(
551 Named(Symbol::intern(s), InnerSpan::new(span.start, span.end)),
558 fn describe_num_args(&self) -> Cow<'_, str> {
559 match self.num_args() {
560 0 => "no arguments were given".into(),
561 1 => "there is 1 argument".into(),
562 x => format!("there are {} arguments", x).into(),
566 /// Handle invalid references to positional arguments. Output different
567 /// errors for the case where all arguments are positional and for when
568 /// there are named arguments or numbered positional arguments in the
570 fn report_invalid_references(&self, numbered_position_args: bool) {
572 let sp = if !self.arg_spans.is_empty() {
573 // Point at the formatting arguments.
574 MultiSpan::from_spans(self.arg_spans.clone())
576 MultiSpan::from_span(self.fmtsp)
579 self.invalid_refs.iter().map(|(r, pos)| (r.to_string(), self.arg_spans.get(*pos)));
581 let mut zero_based_note = false;
583 let count = self.pieces.len()
584 + self.arg_with_formatting.iter().filter(|fmt| fmt.precision_span.is_some()).count();
585 if self.names.is_empty() && !numbered_position_args && count != self.num_args() {
586 e = self.ecx.struct_span_err(
589 "{} positional argument{} in format string, but {}",
592 self.describe_num_args(),
595 for arg in &self.args {
596 // Point at the arguments that will be formatted.
597 e.span_label(arg.expr.span, "");
600 let (mut refs, spans): (Vec<_>, Vec<_>) = refs.unzip();
601 // Avoid `invalid reference to positional arguments 7 and 7 (there is 1 argument)`
602 // for `println!("{7:7$}", 1);`
605 let spans: Vec<_> = spans.into_iter().filter_map(|sp| sp.copied()).collect();
606 let sp = if self.arg_spans.is_empty() || spans.is_empty() {
607 MultiSpan::from_span(self.fmtsp)
609 MultiSpan::from_spans(spans)
611 let arg_list = if refs.len() == 1 {
612 format!("argument {}", refs[0])
614 let reg = refs.pop().unwrap();
615 format!("arguments {head} and {tail}", head = refs.join(", "), tail = reg)
618 e = self.ecx.struct_span_err(
621 "invalid reference to positional {} ({})",
623 self.describe_num_args()
626 zero_based_note = true;
629 for fmt in &self.arg_with_formatting {
630 if let Some(span) = fmt.precision_span {
631 let span = self.fmtsp.from_inner(InnerSpan::new(span.start, span.end));
632 match fmt.precision {
633 parse::CountIsParam(pos) if pos > self.num_args() => {
637 "this precision flag expects an `usize` argument at position {}, \
640 self.describe_num_args(),
643 zero_based_note = true;
645 parse::CountIsParam(pos) => {
646 let count = self.pieces.len()
650 .filter(|fmt| fmt.precision_span.is_some())
655 "this precision flag adds an extra required argument at position {}, \
656 which is why there {} expected",
659 "is 1 argument".to_string()
661 format!("are {} arguments", count)
665 if let Some(arg) = self.args.get(pos) {
668 "this parameter corresponds to the precision flag",
671 zero_based_note = true;
676 if let Some(span) = fmt.width_span {
677 let span = self.fmtsp.from_inner(InnerSpan::new(span.start, span.end));
679 parse::CountIsParam(pos) if pos >= self.num_args() => {
683 "this width flag expects an `usize` argument at position {}, \
686 self.describe_num_args(),
689 zero_based_note = true;
696 e.note("positional arguments are zero-based");
698 if !self.arg_with_formatting.is_empty() {
700 "for information about formatting flags, visit \
701 https://doc.rust-lang.org/std/fmt/index.html",
708 /// Actually verifies and tracks a given format placeholder
709 /// (a.k.a. argument).
710 fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
711 if let Exact(arg) = arg {
712 if arg >= self.num_args() {
713 self.invalid_refs.push((arg, self.curpiece));
719 Exact(arg) | Capture(arg) => {
722 // record every (position, type) combination only once
723 let seen_ty = &mut self.arg_unique_types[arg];
724 let i = seen_ty.iter().position(|x| *x == ty).unwrap_or_else(|| {
725 let i = seen_ty.len();
729 self.arg_types[arg].push(i);
732 if let Entry::Vacant(e) = self.count_positions.entry(arg) {
733 let i = self.count_positions_count;
735 self.count_args.push(arg);
736 self.count_positions_count += 1;
742 Named(name, span) => {
743 match self.names.get(&name) {
745 // Treat as positional arg.
746 self.verify_arg_type(Capture(idx), ty)
749 // For the moment capturing variables from format strings expanded from macros is
750 // disabled (see RFC #2795)
752 // Treat this name as a variable to capture from the surrounding scope
753 let idx = self.args.len();
754 self.arg_types.push(Vec::new());
755 self.arg_unique_types.push(Vec::new());
756 let span = if self.is_literal {
757 self.fmtsp.from_inner(span)
761 self.num_captured_args += 1;
762 self.args.push(FormatArg {
763 expr: self.ecx.expr_ident(span, Ident::new(name, span)),
764 name: Some(Ident::new(name, span)),
766 self.names.insert(name, idx);
767 self.verify_arg_type(Capture(idx), ty)
769 let msg = format!("there is no argument named `{}`", name);
770 let sp = if self.is_literal {
771 self.fmtsp.from_inner(span)
775 let mut err = self.ecx.struct_span_err(sp, &msg);
778 "did you intend to capture a variable `{}` from \
779 the surrounding scope?",
783 "to avoid ambiguity, `format_args!` cannot capture variables \
784 when the format string is expanded from a macro",
795 /// Builds the mapping between format placeholders and argument objects.
796 fn build_index_map(&mut self) {
797 // NOTE: Keep the ordering the same as `into_expr`'s expansion would do!
798 let args_len = self.args.len();
799 self.arg_index_map.reserve(args_len);
801 let mut sofar = 0usize;
804 for i in 0..args_len {
805 let arg_types = &self.arg_types[i];
806 let arg_offsets = arg_types.iter().map(|offset| sofar + *offset).collect::<Vec<_>>();
807 self.arg_index_map.push(arg_offsets);
808 sofar += self.arg_unique_types[i].len();
811 // Record starting index for counts, which appear just after arguments
812 self.count_args_index_offset = sofar;
815 fn rtpath(ecx: &ExtCtxt<'_>, s: Symbol) -> Vec<Ident> {
816 ecx.std_path(&[sym::fmt, sym::rt, sym::v1, s])
819 fn build_count(&self, c: parse::Count<'_>) -> P<ast::Expr> {
821 let count = |c, arg| {
822 let mut path = Context::rtpath(self.ecx, sym::Count);
823 path.push(Ident::new(c, sp));
825 Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]),
826 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
830 parse::CountIs(i) => count(sym::Is, Some(self.ecx.expr_usize(sp, i))),
831 parse::CountIsParam(i) => {
832 // This needs mapping too, as `i` is referring to a macro
833 // argument. If `i` is not found in `count_positions` then
834 // the error had already been emitted elsewhere.
835 let i = self.count_positions.get(&i).cloned().unwrap_or(0)
836 + self.count_args_index_offset;
837 count(sym::Param, Some(self.ecx.expr_usize(sp, i)))
839 parse::CountImplied => count(sym::Implied, None),
840 // should never be the case, names are already resolved
841 parse::CountIsName(..) => panic!("should never happen"),
845 /// Build a literal expression from the accumulated string literals
846 fn build_literal_string(&mut self) -> P<ast::Expr> {
848 let s = Symbol::intern(&self.literal);
849 self.literal.clear();
850 self.ecx.expr_str(sp, s)
853 /// Builds a static `rt::Argument` from a `parse::Piece` or append
854 /// to the `literal` string.
857 piece: &parse::Piece<'a>,
858 arg_index_consumed: &mut Vec<usize>,
859 ) -> Option<P<ast::Expr>> {
862 parse::String(s) => {
863 self.literal.push_str(s);
866 parse::NextArgument(ref arg) => {
867 // Build the position
870 parse::ArgumentIs(i, ..) | parse::ArgumentImplicitlyIs(i) => {
871 // Map to index in final generated argument array
872 // in case of multiple types specified
873 let arg_idx = match arg_index_consumed.get_mut(i) {
874 None => 0, // error already emitted elsewhere
876 let idx_map = &self.arg_index_map[i];
877 // unwrap_or branch: error already emitted elsewhere
878 let arg_idx = *idx_map.get(*offset).unwrap_or(&0);
883 self.ecx.expr_usize(sp, arg_idx)
886 // should never be the case, because names are already
888 parse::ArgumentNamed(..) => panic!("should never happen"),
892 let simple_arg = parse::Argument {
894 // We don't have ArgumentNext any more, so we have to
895 // track the current argument ourselves.
900 position_span: arg.position_span,
901 format: parse::FormatSpec {
902 fill: arg.format.fill,
903 align: parse::AlignUnknown,
905 precision: parse::CountImplied,
906 precision_span: None,
907 width: parse::CountImplied,
910 ty_span: arg.format.ty_span,
914 let fill = arg.format.fill.unwrap_or(' ');
916 let pos_simple = arg.position.index() == simple_arg.position.index();
918 if arg.format.precision_span.is_some() || arg.format.width_span.is_some() {
919 self.arg_with_formatting.push(arg.format);
921 if !pos_simple || arg.format != simple_arg.format || fill != ' ' {
922 self.all_pieces_simple = false;
926 let fill = self.ecx.expr_char(sp, fill);
928 let mut p = Context::rtpath(self.ecx, sym::Alignment);
929 p.push(Ident::new(name, sp));
930 self.ecx.path_global(sp, p)
932 let align = match arg.format.align {
933 parse::AlignLeft => align(sym::Left),
934 parse::AlignRight => align(sym::Right),
935 parse::AlignCenter => align(sym::Center),
936 parse::AlignUnknown => align(sym::Unknown),
938 let align = self.ecx.expr_path(align);
939 let flags = self.ecx.expr_u32(sp, arg.format.flags);
940 let prec = self.build_count(arg.format.precision);
941 let width = self.build_count(arg.format.width);
942 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, sym::FormatSpec));
943 let fmt = self.ecx.expr_struct(
947 self.ecx.field_imm(sp, Ident::new(sym::fill, sp), fill),
948 self.ecx.field_imm(sp, Ident::new(sym::align, sp), align),
949 self.ecx.field_imm(sp, Ident::new(sym::flags, sp), flags),
950 self.ecx.field_imm(sp, Ident::new(sym::precision, sp), prec),
951 self.ecx.field_imm(sp, Ident::new(sym::width, sp), width),
955 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, sym::Argument));
956 Some(self.ecx.expr_struct(
960 self.ecx.field_imm(sp, Ident::new(sym::position, sp), pos),
961 self.ecx.field_imm(sp, Ident::new(sym::format, sp), fmt),
968 /// Actually builds the expression which the format_args! block will be
970 fn into_expr(self) -> P<ast::Expr> {
971 let mut original_args = self.args;
972 let mut fmt_args = Vec::with_capacity(
973 self.arg_unique_types.iter().map(|v| v.len()).sum::<usize>() + self.count_args.len(),
976 // First, build up the static array which will become our precompiled
978 let pieces = self.ecx.expr_array_ref(self.fmtsp, self.str_pieces);
980 // We need to construct a &[ArgumentV1] to pass into the fmt::Arguments
981 // constructor. In general the expressions in this slice might be
982 // permuted from their order in original_args (such as in the case of
983 // "{1} {0}"), or may have multiple entries referring to the same
984 // element of original_args ("{0} {0}").
986 // The following vector has one item per element of our output slice,
987 // identifying the index of which element of original_args it's passing,
988 // and that argument's type.
989 let mut fmt_arg_index_and_ty = SmallVec::<[(usize, &ArgumentType); 8]>::new();
990 for (i, unique_types) in self.arg_unique_types.iter().enumerate() {
991 fmt_arg_index_and_ty.extend(unique_types.iter().map(|ty| (i, ty)));
993 fmt_arg_index_and_ty.extend(self.count_args.iter().map(|&i| (i, &Count)));
995 // Figure out whether there are permuted or repeated elements. If not,
996 // we can generate simpler code.
998 // The sequence has no indices out of order or repeated if: for every
999 // adjacent pair of elements, the first one's index is less than the
1000 // second one's index.
1001 let nicely_ordered =
1002 fmt_arg_index_and_ty.array_windows().all(|[(i, _i_ty), (j, _j_ty)]| i < j);
1006 // [ArgumentV1::new(&$arg0, …), ArgumentV1::new(&$arg1, …), …]
1008 // However, it's only legal to do so if $arg0, $arg1, … were written in
1009 // exactly that order by the programmer. When arguments are permuted, we
1010 // want them evaluated in the order written by the programmer, not in
1011 // the order provided to fmt::Arguments. When arguments are repeated, we
1012 // want the expression evaluated only once.
1014 // Further, if any arg _after the first one_ contains a yield point such
1015 // as `await` or `yield`, the above short form is inconvenient for the
1016 // caller because it would keep a temporary of type ArgumentV1 alive
1017 // across the yield point. ArgumentV1 can't implement Send since it
1018 // holds a type-erased arbitrary type.
1020 // Thus in the not nicely ordered case, and in the yielding case, we
1021 // emit the following instead:
1023 // match (&$arg0, &$arg1, …) {
1024 // args => [ArgumentV1::new(args.$i, …), ArgumentV1::new(args.$j, …), …]
1027 // for the sequence of indices $i, $j, … governed by fmt_arg_index_and_ty.
1028 // This more verbose representation ensures that all arguments are
1029 // evaluated a single time each, in the order written by the programmer,
1030 // and that the surrounding future/generator (if any) is Send whenever
1032 let no_need_for_match = nicely_ordered
1033 && !original_args.iter().skip(1).any(|arg| may_contain_yield_point(&arg.expr));
1035 for (arg_index, arg_ty) in fmt_arg_index_and_ty {
1036 let e = &mut original_args[arg_index].expr;
1038 let arg = if no_need_for_match {
1039 let expansion_span = e.span.with_ctxt(self.macsp.ctxt());
1040 // The indices are strictly ordered so e has not been taken yet.
1041 self.ecx.expr_addr_of(expansion_span, P(e.take()))
1043 let def_site = self.ecx.with_def_site_ctxt(span);
1044 let args_tuple = self.ecx.expr_ident(def_site, Ident::new(sym::args, def_site));
1045 let member = Ident::new(sym::integer(arg_index), def_site);
1046 self.ecx.expr(def_site, ast::ExprKind::Field(args_tuple, member))
1048 fmt_args.push(Context::format_arg(self.ecx, self.macsp, span, arg_ty, arg));
1051 let args_array = self.ecx.expr_array(self.macsp, fmt_args);
1052 let args_slice = self.ecx.expr_addr_of(
1054 if no_need_for_match {
1057 // In the !no_need_for_match case, none of the exprs were moved
1058 // away in the previous loop.
1060 // This uses the arg span for `&arg` so that borrowck errors
1061 // point to the specific expression passed to the macro (the
1062 // span is otherwise unavailable in the MIR used by borrowck).
1063 let heads = original_args
1066 self.ecx.expr_addr_of(arg.expr.span.with_ctxt(self.macsp.ctxt()), arg.expr)
1070 let pat = self.ecx.pat_ident(self.macsp, Ident::new(sym::args, self.macsp));
1071 let arm = self.ecx.arm(self.macsp, pat, args_array);
1072 let head = self.ecx.expr(self.macsp, ast::ExprKind::Tup(heads));
1073 self.ecx.expr_match(self.macsp, head, vec![arm])
1077 // Now create the fmt::Arguments struct with all our locals we created.
1078 let (fn_name, fn_args) = if self.all_pieces_simple {
1079 ("new_v1", vec![pieces, args_slice])
1081 // Build up the static array which will store our precompiled
1082 // nonstandard placeholders, if there are any.
1083 let fmt = self.ecx.expr_array_ref(self.macsp, self.pieces);
1085 let path = self.ecx.std_path(&[sym::fmt, sym::UnsafeArg, sym::new]);
1086 let unsafe_arg = self.ecx.expr_call_global(self.macsp, path, Vec::new());
1087 let unsafe_expr = self.ecx.expr_block(P(ast::Block {
1088 stmts: vec![self.ecx.stmt_expr(unsafe_arg)],
1089 id: ast::DUMMY_NODE_ID,
1090 rules: BlockCheckMode::Unsafe(UnsafeSource::CompilerGenerated),
1093 could_be_bare_literal: false,
1096 ("new_v1_formatted", vec![pieces, args_slice, fmt, unsafe_expr])
1099 let path = self.ecx.std_path(&[sym::fmt, sym::Arguments, Symbol::intern(fn_name)]);
1100 self.ecx.expr_call_global(self.macsp, path, fn_args)
1110 sp = ecx.with_def_site_ctxt(sp);
1111 let trait_ = match *ty {
1112 Placeholder(trait_) if trait_ == "<invalid>" => return DummyResult::raw_expr(sp, true),
1113 Placeholder(trait_) => trait_,
1115 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, sym::from_usize]);
1116 return ecx.expr_call_global(macsp, path, vec![arg]);
1119 let new_fn_name = match trait_ {
1120 "Display" => "new_display",
1121 "Debug" => "new_debug",
1122 "LowerExp" => "new_lower_exp",
1123 "UpperExp" => "new_upper_exp",
1124 "Octal" => "new_octal",
1125 "Pointer" => "new_pointer",
1126 "Binary" => "new_binary",
1127 "LowerHex" => "new_lower_hex",
1128 "UpperHex" => "new_upper_hex",
1129 _ => unreachable!(),
1132 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, Symbol::intern(new_fn_name)]);
1133 ecx.expr_call_global(sp, path, vec![arg])
1137 fn expand_format_args_impl<'cx>(
1138 ecx: &'cx mut ExtCtxt<'_>,
1142 ) -> Box<dyn base::MacResult + 'cx> {
1143 sp = ecx.with_def_site_ctxt(sp);
1144 match parse_args(ecx, sp, tts) {
1145 Ok((efmt, args, names)) => {
1146 MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt, args, names, nl))
1150 DummyResult::any(sp)
1155 pub fn expand_format_args<'cx>(
1156 ecx: &'cx mut ExtCtxt<'_>,
1159 ) -> Box<dyn base::MacResult + 'cx> {
1160 expand_format_args_impl(ecx, sp, tts, false)
1163 pub fn expand_format_args_nl<'cx>(
1164 ecx: &'cx mut ExtCtxt<'_>,
1167 ) -> Box<dyn base::MacResult + 'cx> {
1168 expand_format_args_impl(ecx, sp, tts, true)
1171 fn create_lints_for_named_arguments_used_positionally(cx: &mut Context<'_, '_>) {
1172 for named_arg in &cx.unused_names_lint.positional_named_args {
1173 let (position_sp_to_replace, position_sp_for_msg) = named_arg.get_positional_arg_spans(cx);
1175 let msg = format!("named argument `{}` is not used by name", named_arg.replacement);
1177 cx.ecx.buffered_early_lint.push(BufferedEarlyLint {
1178 span: MultiSpan::from_span(named_arg.positional_named_arg_span),
1179 msg: msg.clone().into(),
1180 node_id: ast::CRATE_NODE_ID,
1181 lint_id: LintId::of(&NAMED_ARGUMENTS_USED_POSITIONALLY),
1182 diagnostic: BuiltinLintDiagnostics::NamedArgumentUsedPositionally {
1183 position_sp_to_replace,
1184 position_sp_for_msg,
1185 named_arg_sp: named_arg.positional_named_arg_span,
1186 named_arg_name: named_arg.replacement.to_string(),
1187 is_formatting_arg: named_arg.ty != PositionalNamedArgType::Arg,
1193 /// Take the various parts of `format_args!(efmt, args..., name=names...)`
1194 /// and construct the appropriate formatting expression.
1195 pub fn expand_preparsed_format_args(
1196 ecx: &mut ExtCtxt<'_>,
1199 args: Vec<FormatArg>,
1200 names: FxHashMap<Symbol, usize>,
1201 append_newline: bool,
1203 // NOTE: this verbose way of initializing `Vec<Vec<ArgumentType>>` is because
1204 // `ArgumentType` does not derive `Clone`.
1205 let arg_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
1206 let arg_unique_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
1208 let mut macsp = ecx.call_site();
1209 macsp = ecx.with_def_site_ctxt(macsp);
1211 let msg = "format argument must be a string literal";
1212 let fmt_sp = efmt.span;
1213 let efmt_kind_is_lit: bool = matches!(efmt.kind, ast::ExprKind::Lit(_));
1214 let (fmt_str, fmt_style, fmt_span) = match expr_to_spanned_string(ecx, efmt, msg) {
1215 Ok(mut fmt) if append_newline => {
1216 fmt.0 = Symbol::intern(&format!("{}\n", fmt.0));
1221 if let Some((mut err, suggested)) = err {
1222 let sugg_fmt = match args.len() {
1223 0 => "{}".to_string(),
1224 _ => format!("{}{{}}", "{} ".repeat(args.len())),
1227 err.span_suggestion(
1228 fmt_sp.shrink_to_lo(),
1229 "you might be missing a string literal to format with",
1230 format!("\"{}\", ", sugg_fmt),
1231 Applicability::MaybeIncorrect,
1236 return DummyResult::raw_expr(sp, true);
1240 let str_style = match fmt_style {
1241 ast::StrStyle::Cooked => None,
1242 ast::StrStyle::Raw(raw) => Some(raw as usize),
1245 let fmt_str = fmt_str.as_str(); // for the suggestions below
1246 let fmt_snippet = ecx.source_map().span_to_snippet(fmt_sp).ok();
1247 let mut parser = parse::Parser::new(
1252 parse::ParseMode::Format,
1255 let mut unverified_pieces = Vec::new();
1256 while let Some(piece) = parser.next() {
1257 if !parser.errors.is_empty() {
1260 unverified_pieces.push(piece);
1264 if !parser.errors.is_empty() {
1265 let err = parser.errors.remove(0);
1266 let sp = if efmt_kind_is_lit {
1267 fmt_span.from_inner(InnerSpan::new(err.span.start, err.span.end))
1269 // The format string could be another macro invocation, e.g.:
1270 // format!(concat!("abc", "{}"), 4);
1271 // However, `err.span` is an inner span relative to the *result* of
1272 // the macro invocation, which is why we would get a nonsensical
1273 // result calling `fmt_span.from_inner(err.span)` as above, and
1274 // might even end up inside a multibyte character (issue #86085).
1275 // Therefore, we conservatively report the error for the entire
1276 // argument span here.
1279 let mut e = ecx.struct_span_err(sp, &format!("invalid format string: {}", err.description));
1280 e.span_label(sp, err.label + " in format string");
1281 if let Some(note) = err.note {
1284 if let Some((label, span)) = err.secondary_label {
1285 if efmt_kind_is_lit {
1286 e.span_label(fmt_span.from_inner(InnerSpan::new(span.start, span.end)), label);
1289 if err.should_be_replaced_with_positional_argument {
1290 let captured_arg_span =
1291 fmt_span.from_inner(InnerSpan::new(err.span.start, err.span.end));
1292 let n_positional_args =
1293 args.iter().rposition(|arg| arg.name.is_none()).map_or(0, |i| i + 1);
1294 if let Ok(arg) = ecx.source_map().span_to_snippet(captured_arg_span) {
1295 let span = match args[..n_positional_args].last() {
1296 Some(arg) => arg.expr.span,
1299 e.multipart_suggestion_verbose(
1300 "consider using a positional formatting argument instead",
1302 (captured_arg_span, n_positional_args.to_string()),
1303 (span.shrink_to_hi(), format!(", {}", arg)),
1305 Applicability::MachineApplicable,
1310 return DummyResult::raw_expr(sp, true);
1313 let arg_spans = parser
1316 .map(|span| fmt_span.from_inner(InnerSpan::new(span.start, span.end)))
1319 let mut cx = Context {
1322 num_captured_args: 0,
1328 arg_index_map: Vec::new(),
1329 count_args: Vec::new(),
1330 count_positions: FxHashMap::default(),
1331 count_positions_count: 0,
1332 count_args_index_offset: 0,
1333 literal: String::new(),
1334 pieces: Vec::with_capacity(unverified_pieces.len()),
1335 str_pieces: Vec::with_capacity(unverified_pieces.len()),
1336 all_pieces_simple: true,
1339 invalid_refs: Vec::new(),
1341 arg_with_formatting: Vec::new(),
1342 is_literal: parser.is_literal,
1343 unused_names_lint: PositionalNamedArgsLint { positional_named_args: vec![] },
1346 // This needs to happen *after* the Parser has consumed all pieces to create all the spans
1347 let pieces = unverified_pieces
1350 cx.verify_piece(&piece);
1351 cx.resolve_name_inplace(&mut piece);
1354 .collect::<Vec<_>>();
1356 let numbered_position_args = pieces.iter().any(|arg: &parse::Piece<'_>| match *arg {
1357 parse::String(_) => false,
1358 parse::NextArgument(arg) => matches!(arg.position, parse::Position::ArgumentIs(..)),
1361 cx.build_index_map();
1363 let mut arg_index_consumed = vec![0usize; cx.arg_index_map.len()];
1365 for piece in pieces {
1366 if let Some(piece) = cx.build_piece(&piece, &mut arg_index_consumed) {
1367 let s = cx.build_literal_string();
1368 cx.str_pieces.push(s);
1369 cx.pieces.push(piece);
1373 if !cx.literal.is_empty() {
1374 let s = cx.build_literal_string();
1375 cx.str_pieces.push(s);
1378 if !cx.invalid_refs.is_empty() {
1379 cx.report_invalid_references(numbered_position_args);
1382 // Make sure that all arguments were used and all arguments have types.
1387 .filter(|(i, ty)| ty.is_empty() && !cx.count_positions.contains_key(&i))
1389 let msg = if cx.args[i].name.is_some() {
1390 "named argument never used"
1392 "argument never used"
1394 (cx.args[i].expr.span, msg)
1396 .collect::<Vec<_>>();
1398 let errs_len = errs.len();
1399 if !errs.is_empty() {
1400 let args_used = cx.arg_types.len() - errs_len;
1401 let args_unused = errs_len;
1404 if let [(sp, msg)] = &errs[..] {
1405 let mut diag = cx.ecx.struct_span_err(*sp, *msg);
1406 diag.span_label(*sp, *msg);
1409 let mut diag = cx.ecx.struct_span_err(
1410 errs.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
1411 "multiple unused formatting arguments",
1413 diag.span_label(cx.fmtsp, "multiple missing formatting specifiers");
1414 for (sp, msg) in errs {
1415 diag.span_label(sp, msg);
1421 // Used to ensure we only report translations for *one* kind of foreign format.
1422 let mut found_foreign = false;
1423 // Decide if we want to look for foreign formatting directives.
1424 if args_used < args_unused {
1425 use super::format_foreign as foreign;
1427 // The set of foreign substitutions we've explained. This prevents spamming the user
1428 // with `%d should be written as {}` over and over again.
1429 let mut explained = FxHashSet::default();
1431 macro_rules! check_foreign {
1433 let mut show_doc_note = false;
1435 let mut suggestions = vec![];
1436 // account for `"` and account for raw strings `r#`
1437 let padding = str_style.map(|i| i + 2).unwrap_or(1);
1438 for sub in foreign::$kind::iter_subs(fmt_str, padding) {
1439 let (trn, success) = match sub.translate() {
1440 Ok(trn) => (trn, true),
1441 Err(Some(msg)) => (msg, false),
1443 // If it has no translation, don't call it out specifically.
1447 let pos = sub.position();
1448 let sub = String::from(sub.as_str());
1449 if explained.contains(&sub) {
1452 explained.insert(sub.clone());
1455 found_foreign = true;
1456 show_doc_note = true;
1459 if let Some(inner_sp) = pos {
1460 let sp = fmt_sp.from_inner(inner_sp);
1463 suggestions.push((sp, trn));
1467 &format!("format specifiers use curly braces, and {}", trn),
1472 diag.help(&format!("`{}` should be written as `{}`", sub, trn));
1475 "`{}` should use curly braces, and {}",
1485 " formatting not supported; see the documentation for `std::fmt`",
1488 if suggestions.len() > 0 {
1489 diag.multipart_suggestion(
1490 "format specifiers use curly braces",
1492 Applicability::MachineApplicable,
1498 check_foreign!(printf);
1500 check_foreign!(shell);
1503 if !found_foreign && errs_len == 1 {
1504 diag.span_label(cx.fmtsp, "formatting specifier missing");
1508 } else if cx.invalid_refs.is_empty() && cx.ecx.sess.err_count() == 0 {
1509 // Only check for unused named argument names if there are no other errors to avoid causing
1510 // too much noise in output errors, such as when a named argument is entirely unused.
1511 create_lints_for_named_arguments_used_positionally(&mut cx);
1517 fn may_contain_yield_point(e: &ast::Expr) -> bool {
1518 struct MayContainYieldPoint(bool);
1520 impl Visitor<'_> for MayContainYieldPoint {
1521 fn visit_expr(&mut self, e: &ast::Expr) {
1522 if let ast::ExprKind::Await(_) | ast::ExprKind::Yield(_) = e.kind {
1525 visit::walk_expr(self, e);
1529 fn visit_mac_call(&mut self, _: &ast::MacCall) {
1533 fn visit_attribute(&mut self, _: &ast::Attribute) {
1534 // Conservatively assume this may be a proc macro attribute in
1535 // expression position.
1539 fn visit_item(&mut self, _: &ast::Item) {
1540 // Do not recurse into nested items.
1544 let mut visitor = MayContainYieldPoint(false);
1545 visitor.visit_expr(e);