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<'a>) {
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 if has_precision || has_width {
437 // push before named params are resolved to aid diagnostics
438 self.arg_with_formatting.push(arg.format);
441 // argument second, if it's an implicit positional parameter
442 // it's written second, so it should come after width/precision.
443 let pos = match arg.position {
444 parse::ArgumentIs(i) => {
445 self.unused_names_lint.maybe_add_positional_named_arg(
447 PositionalNamedArgType::Arg,
449 Some(arg.position_span),
450 has_precision || has_width,
455 parse::ArgumentImplicitlyIs(i) => {
456 self.unused_names_lint.maybe_add_positional_named_arg(
458 PositionalNamedArgType::Arg,
461 has_precision || has_width,
465 parse::ArgumentNamed(s) => {
466 let symbol = Symbol::intern(s);
467 let span = arg.position_span;
468 Named(symbol, InnerSpan::new(span.start, span.end))
472 let ty = Placeholder(match arg.format.ty {
483 let fmtsp = self.fmtsp;
487 .map(|sp| fmtsp.from_inner(InnerSpan::new(sp.start, sp.end)));
488 let mut err = self.ecx.struct_span_err(
490 &format!("unknown format trait `{}`", arg.format.ty),
493 "the only appropriate formatting traits are:\n\
494 - ``, which uses the `Display` trait\n\
495 - `?`, which uses the `Debug` trait\n\
496 - `e`, which uses the `LowerExp` trait\n\
497 - `E`, which uses the `UpperExp` trait\n\
498 - `o`, which uses the `Octal` trait\n\
499 - `p`, which uses the `Pointer` trait\n\
500 - `b`, which uses the `Binary` trait\n\
501 - `x`, which uses the `LowerHex` trait\n\
502 - `X`, which uses the `UpperHex` trait",
504 if let Some(sp) = sp {
505 for (fmt, name) in &[
516 // FIXME: rustfix (`run-rustfix`) fails to apply suggestions.
517 // > "Cannot replace slice of data that was already replaced"
518 err.tool_only_span_suggestion(
520 &format!("use the `{}` trait", name),
522 Applicability::MaybeIncorrect,
530 self.verify_arg_type(pos, ty);
539 inner_span: &Option<rustc_parse_format::InnerSpan>,
540 named_arg_type: PositionalNamedArgType,
543 parse::CountImplied | parse::CountIs(..) => {}
544 parse::CountIsParam(i) | parse::CountIsStar(i) => {
545 self.unused_names_lint.maybe_add_positional_named_arg(
552 self.verify_arg_type(Exact(i), Count);
554 parse::CountIsName(s, span) => {
555 self.verify_arg_type(
556 Named(Symbol::intern(s), InnerSpan::new(span.start, span.end)),
563 fn describe_num_args(&self) -> Cow<'_, str> {
564 match self.num_args() {
565 0 => "no arguments were given".into(),
566 1 => "there is 1 argument".into(),
567 x => format!("there are {} arguments", x).into(),
571 /// Handle invalid references to positional arguments. Output different
572 /// errors for the case where all arguments are positional and for when
573 /// there are named arguments or numbered positional arguments in the
575 fn report_invalid_references(&self, numbered_position_args: bool) {
577 let sp = if !self.arg_spans.is_empty() {
578 // Point at the formatting arguments.
579 MultiSpan::from_spans(self.arg_spans.clone())
581 MultiSpan::from_span(self.fmtsp)
584 self.invalid_refs.iter().map(|(r, pos)| (r.to_string(), self.arg_spans.get(*pos)));
586 let mut zero_based_note = false;
588 let count = self.pieces.len()
592 .filter(|fmt| matches!(fmt.precision, parse::CountIsStar(_)))
594 if self.names.is_empty() && !numbered_position_args && count != self.num_args() {
595 e = self.ecx.struct_span_err(
598 "{} positional argument{} in format string, but {}",
601 self.describe_num_args(),
604 for arg in &self.args {
605 // Point at the arguments that will be formatted.
606 e.span_label(arg.expr.span, "");
609 let (mut refs, spans): (Vec<_>, Vec<_>) = refs.unzip();
610 // Avoid `invalid reference to positional arguments 7 and 7 (there is 1 argument)`
611 // for `println!("{7:7$}", 1);`
614 let spans: Vec<_> = spans.into_iter().filter_map(|sp| sp.copied()).collect();
615 let sp = if self.arg_spans.is_empty() || spans.is_empty() {
616 MultiSpan::from_span(self.fmtsp)
618 MultiSpan::from_spans(spans)
620 let arg_list = if refs.len() == 1 {
621 format!("argument {}", refs[0])
623 let reg = refs.pop().unwrap();
624 format!("arguments {head} and {tail}", head = refs.join(", "), tail = reg)
627 e = self.ecx.struct_span_err(
630 "invalid reference to positional {} ({})",
632 self.describe_num_args()
635 zero_based_note = true;
638 for fmt in &self.arg_with_formatting {
639 if let Some(span) = fmt.precision_span {
640 let span = self.fmtsp.from_inner(InnerSpan::new(span.start, span.end));
641 match fmt.precision {
642 parse::CountIsParam(pos) if pos >= self.num_args() => {
646 "this precision flag expects an `usize` argument at position {}, \
649 self.describe_num_args(),
652 zero_based_note = true;
654 parse::CountIsStar(pos) => {
655 let count = self.pieces.len()
659 .filter(|fmt| matches!(fmt.precision, parse::CountIsStar(_)))
664 "this precision flag adds an extra required argument at position {}, \
665 which is why there {} expected",
668 "is 1 argument".to_string()
670 format!("are {} arguments", count)
674 if let Some(arg) = self.args.get(pos) {
677 "this parameter corresponds to the precision flag",
680 zero_based_note = true;
685 if let Some(span) = fmt.width_span {
686 let span = self.fmtsp.from_inner(InnerSpan::new(span.start, span.end));
688 parse::CountIsParam(pos) if pos >= self.num_args() => {
692 "this width flag expects an `usize` argument at position {}, \
695 self.describe_num_args(),
698 zero_based_note = true;
705 e.note("positional arguments are zero-based");
707 if !self.arg_with_formatting.is_empty() {
709 "for information about formatting flags, visit \
710 https://doc.rust-lang.org/std/fmt/index.html",
717 /// Actually verifies and tracks a given format placeholder
718 /// (a.k.a. argument).
719 fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
720 if let Exact(arg) = arg {
721 if arg >= self.num_args() {
722 self.invalid_refs.push((arg, self.curpiece));
728 Exact(arg) | Capture(arg) => {
731 // record every (position, type) combination only once
732 let seen_ty = &mut self.arg_unique_types[arg];
733 let i = seen_ty.iter().position(|x| *x == ty).unwrap_or_else(|| {
734 let i = seen_ty.len();
738 self.arg_types[arg].push(i);
741 if let Entry::Vacant(e) = self.count_positions.entry(arg) {
742 let i = self.count_positions_count;
744 self.count_args.push(arg);
745 self.count_positions_count += 1;
751 Named(name, span) => {
752 match self.names.get(&name) {
754 // Treat as positional arg.
755 self.verify_arg_type(Capture(idx), ty)
758 // For the moment capturing variables from format strings expanded from macros is
759 // disabled (see RFC #2795)
761 // Treat this name as a variable to capture from the surrounding scope
762 let idx = self.args.len();
763 self.arg_types.push(Vec::new());
764 self.arg_unique_types.push(Vec::new());
765 let span = if self.is_literal {
766 self.fmtsp.from_inner(span)
770 self.num_captured_args += 1;
771 self.args.push(FormatArg {
772 expr: self.ecx.expr_ident(span, Ident::new(name, span)),
773 name: Some(Ident::new(name, span)),
775 self.names.insert(name, idx);
776 self.verify_arg_type(Capture(idx), ty)
778 let msg = format!("there is no argument named `{}`", name);
779 let sp = if self.is_literal {
780 self.fmtsp.from_inner(span)
784 let mut err = self.ecx.struct_span_err(sp, &msg);
787 "did you intend to capture a variable `{}` from \
788 the surrounding scope?",
792 "to avoid ambiguity, `format_args!` cannot capture variables \
793 when the format string is expanded from a macro",
804 /// Builds the mapping between format placeholders and argument objects.
805 fn build_index_map(&mut self) {
806 // NOTE: Keep the ordering the same as `into_expr`'s expansion would do!
807 let args_len = self.args.len();
808 self.arg_index_map.reserve(args_len);
810 let mut sofar = 0usize;
813 for i in 0..args_len {
814 let arg_types = &self.arg_types[i];
815 let arg_offsets = arg_types.iter().map(|offset| sofar + *offset).collect::<Vec<_>>();
816 self.arg_index_map.push(arg_offsets);
817 sofar += self.arg_unique_types[i].len();
820 // Record starting index for counts, which appear just after arguments
821 self.count_args_index_offset = sofar;
824 fn rtpath(ecx: &ExtCtxt<'_>, s: Symbol) -> Vec<Ident> {
825 ecx.std_path(&[sym::fmt, sym::rt, sym::v1, s])
828 fn build_count(&self, c: parse::Count<'_>) -> P<ast::Expr> {
830 let count = |c, arg| {
831 let mut path = Context::rtpath(self.ecx, sym::Count);
832 path.push(Ident::new(c, sp));
834 Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]),
835 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
839 parse::CountIs(i) => count(sym::Is, Some(self.ecx.expr_usize(sp, i))),
840 parse::CountIsParam(i) | parse::CountIsStar(i) => {
841 // This needs mapping too, as `i` is referring to a macro
842 // argument. If `i` is not found in `count_positions` then
843 // the error had already been emitted elsewhere.
844 let i = self.count_positions.get(&i).cloned().unwrap_or(0)
845 + self.count_args_index_offset;
846 count(sym::Param, Some(self.ecx.expr_usize(sp, i)))
848 parse::CountImplied => count(sym::Implied, None),
849 // should never be the case, names are already resolved
850 parse::CountIsName(..) => panic!("should never happen"),
854 /// Build a literal expression from the accumulated string literals
855 fn build_literal_string(&mut self) -> P<ast::Expr> {
857 let s = Symbol::intern(&self.literal);
858 self.literal.clear();
859 self.ecx.expr_str(sp, s)
862 /// Builds a static `rt::Argument` from a `parse::Piece` or append
863 /// to the `literal` string.
866 piece: &parse::Piece<'a>,
867 arg_index_consumed: &mut Vec<usize>,
868 ) -> Option<P<ast::Expr>> {
871 parse::String(s) => {
872 self.literal.push_str(s);
875 parse::NextArgument(ref arg) => {
876 // Build the position
879 parse::ArgumentIs(i, ..) | parse::ArgumentImplicitlyIs(i) => {
880 // Map to index in final generated argument array
881 // in case of multiple types specified
882 let arg_idx = match arg_index_consumed.get_mut(i) {
883 None => 0, // error already emitted elsewhere
885 let idx_map = &self.arg_index_map[i];
886 // unwrap_or branch: error already emitted elsewhere
887 let arg_idx = *idx_map.get(*offset).unwrap_or(&0);
892 self.ecx.expr_usize(sp, arg_idx)
895 // should never be the case, because names are already
897 parse::ArgumentNamed(..) => panic!("should never happen"),
901 let simple_arg = parse::Argument {
903 // We don't have ArgumentNext any more, so we have to
904 // track the current argument ourselves.
909 position_span: arg.position_span,
910 format: parse::FormatSpec {
912 align: parse::AlignUnknown,
914 precision: parse::CountImplied,
915 precision_span: arg.format.precision_span,
916 width: parse::CountImplied,
917 width_span: arg.format.width_span,
919 ty_span: arg.format.ty_span,
923 let fill = arg.format.fill.unwrap_or(' ');
924 let pos_simple = arg.position.index() == simple_arg.position.index();
926 if !pos_simple || arg.format != simple_arg.format {
927 self.all_pieces_simple = false;
931 let fill = self.ecx.expr_char(sp, fill);
933 let mut p = Context::rtpath(self.ecx, sym::Alignment);
934 p.push(Ident::new(name, sp));
935 self.ecx.path_global(sp, p)
937 let align = match arg.format.align {
938 parse::AlignLeft => align(sym::Left),
939 parse::AlignRight => align(sym::Right),
940 parse::AlignCenter => align(sym::Center),
941 parse::AlignUnknown => align(sym::Unknown),
943 let align = self.ecx.expr_path(align);
944 let flags = self.ecx.expr_u32(sp, arg.format.flags);
945 let prec = self.build_count(arg.format.precision);
946 let width = self.build_count(arg.format.width);
947 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, sym::FormatSpec));
948 let fmt = self.ecx.expr_struct(
952 self.ecx.field_imm(sp, Ident::new(sym::fill, sp), fill),
953 self.ecx.field_imm(sp, Ident::new(sym::align, sp), align),
954 self.ecx.field_imm(sp, Ident::new(sym::flags, sp), flags),
955 self.ecx.field_imm(sp, Ident::new(sym::precision, sp), prec),
956 self.ecx.field_imm(sp, Ident::new(sym::width, sp), width),
960 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, sym::Argument));
961 Some(self.ecx.expr_struct(
965 self.ecx.field_imm(sp, Ident::new(sym::position, sp), pos),
966 self.ecx.field_imm(sp, Ident::new(sym::format, sp), fmt),
973 /// Actually builds the expression which the format_args! block will be
975 fn into_expr(self) -> P<ast::Expr> {
976 let mut original_args = self.args;
977 let mut fmt_args = Vec::with_capacity(
978 self.arg_unique_types.iter().map(|v| v.len()).sum::<usize>() + self.count_args.len(),
981 // First, build up the static array which will become our precompiled
983 let pieces = self.ecx.expr_array_ref(self.fmtsp, self.str_pieces);
985 // We need to construct a &[ArgumentV1] to pass into the fmt::Arguments
986 // constructor. In general the expressions in this slice might be
987 // permuted from their order in original_args (such as in the case of
988 // "{1} {0}"), or may have multiple entries referring to the same
989 // element of original_args ("{0} {0}").
991 // The following vector has one item per element of our output slice,
992 // identifying the index of which element of original_args it's passing,
993 // and that argument's type.
994 let mut fmt_arg_index_and_ty = SmallVec::<[(usize, &ArgumentType); 8]>::new();
995 for (i, unique_types) in self.arg_unique_types.iter().enumerate() {
996 fmt_arg_index_and_ty.extend(unique_types.iter().map(|ty| (i, ty)));
998 fmt_arg_index_and_ty.extend(self.count_args.iter().map(|&i| (i, &Count)));
1000 // Figure out whether there are permuted or repeated elements. If not,
1001 // we can generate simpler code.
1003 // The sequence has no indices out of order or repeated if: for every
1004 // adjacent pair of elements, the first one's index is less than the
1005 // second one's index.
1006 let nicely_ordered =
1007 fmt_arg_index_and_ty.array_windows().all(|[(i, _i_ty), (j, _j_ty)]| i < j);
1011 // [ArgumentV1::new(&$arg0, …), ArgumentV1::new(&$arg1, …), …]
1013 // However, it's only legal to do so if $arg0, $arg1, … were written in
1014 // exactly that order by the programmer. When arguments are permuted, we
1015 // want them evaluated in the order written by the programmer, not in
1016 // the order provided to fmt::Arguments. When arguments are repeated, we
1017 // want the expression evaluated only once.
1019 // Further, if any arg _after the first one_ contains a yield point such
1020 // as `await` or `yield`, the above short form is inconvenient for the
1021 // caller because it would keep a temporary of type ArgumentV1 alive
1022 // across the yield point. ArgumentV1 can't implement Send since it
1023 // holds a type-erased arbitrary type.
1025 // Thus in the not nicely ordered case, and in the yielding case, we
1026 // emit the following instead:
1028 // match (&$arg0, &$arg1, …) {
1029 // args => [ArgumentV1::new(args.$i, …), ArgumentV1::new(args.$j, …), …]
1032 // for the sequence of indices $i, $j, … governed by fmt_arg_index_and_ty.
1033 // This more verbose representation ensures that all arguments are
1034 // evaluated a single time each, in the order written by the programmer,
1035 // and that the surrounding future/generator (if any) is Send whenever
1037 let no_need_for_match = nicely_ordered
1038 && !original_args.iter().skip(1).any(|arg| may_contain_yield_point(&arg.expr));
1040 for (arg_index, arg_ty) in fmt_arg_index_and_ty {
1041 let e = &mut original_args[arg_index].expr;
1043 let arg = if no_need_for_match {
1044 let expansion_span = e.span.with_ctxt(self.macsp.ctxt());
1045 // The indices are strictly ordered so e has not been taken yet.
1046 self.ecx.expr_addr_of(expansion_span, P(e.take()))
1048 let def_site = self.ecx.with_def_site_ctxt(span);
1049 let args_tuple = self.ecx.expr_ident(def_site, Ident::new(sym::args, def_site));
1050 let member = Ident::new(sym::integer(arg_index), def_site);
1051 self.ecx.expr(def_site, ast::ExprKind::Field(args_tuple, member))
1053 fmt_args.push(Context::format_arg(self.ecx, self.macsp, span, arg_ty, arg));
1056 let args_array = self.ecx.expr_array(self.macsp, fmt_args);
1057 let args_slice = self.ecx.expr_addr_of(
1059 if no_need_for_match {
1062 // In the !no_need_for_match case, none of the exprs were moved
1063 // away in the previous loop.
1065 // This uses the arg span for `&arg` so that borrowck errors
1066 // point to the specific expression passed to the macro (the
1067 // span is otherwise unavailable in the MIR used by borrowck).
1068 let heads = original_args
1071 self.ecx.expr_addr_of(arg.expr.span.with_ctxt(self.macsp.ctxt()), arg.expr)
1075 let pat = self.ecx.pat_ident(self.macsp, Ident::new(sym::args, self.macsp));
1076 let arm = self.ecx.arm(self.macsp, pat, args_array);
1077 let head = self.ecx.expr(self.macsp, ast::ExprKind::Tup(heads));
1078 self.ecx.expr_match(self.macsp, head, vec![arm])
1082 // Now create the fmt::Arguments struct with all our locals we created.
1083 let (fn_name, fn_args) = if self.all_pieces_simple {
1084 ("new_v1", vec![pieces, args_slice])
1086 // Build up the static array which will store our precompiled
1087 // nonstandard placeholders, if there are any.
1088 let fmt = self.ecx.expr_array_ref(self.macsp, self.pieces);
1090 let path = self.ecx.std_path(&[sym::fmt, sym::UnsafeArg, sym::new]);
1091 let unsafe_arg = self.ecx.expr_call_global(self.macsp, path, Vec::new());
1092 let unsafe_expr = self.ecx.expr_block(P(ast::Block {
1093 stmts: vec![self.ecx.stmt_expr(unsafe_arg)],
1094 id: ast::DUMMY_NODE_ID,
1095 rules: BlockCheckMode::Unsafe(UnsafeSource::CompilerGenerated),
1098 could_be_bare_literal: false,
1101 ("new_v1_formatted", vec![pieces, args_slice, fmt, unsafe_expr])
1104 let path = self.ecx.std_path(&[sym::fmt, sym::Arguments, Symbol::intern(fn_name)]);
1105 self.ecx.expr_call_global(self.macsp, path, fn_args)
1115 sp = ecx.with_def_site_ctxt(sp);
1116 let trait_ = match *ty {
1117 Placeholder(trait_) if trait_ == "<invalid>" => return DummyResult::raw_expr(sp, true),
1118 Placeholder(trait_) => trait_,
1120 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, sym::from_usize]);
1121 return ecx.expr_call_global(macsp, path, vec![arg]);
1124 let new_fn_name = match trait_ {
1125 "Display" => "new_display",
1126 "Debug" => "new_debug",
1127 "LowerExp" => "new_lower_exp",
1128 "UpperExp" => "new_upper_exp",
1129 "Octal" => "new_octal",
1130 "Pointer" => "new_pointer",
1131 "Binary" => "new_binary",
1132 "LowerHex" => "new_lower_hex",
1133 "UpperHex" => "new_upper_hex",
1134 _ => unreachable!(),
1137 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, Symbol::intern(new_fn_name)]);
1138 ecx.expr_call_global(sp, path, vec![arg])
1142 fn expand_format_args_impl<'cx>(
1143 ecx: &'cx mut ExtCtxt<'_>,
1147 ) -> Box<dyn base::MacResult + 'cx> {
1148 sp = ecx.with_def_site_ctxt(sp);
1149 match parse_args(ecx, sp, tts) {
1150 Ok((efmt, args, names)) => {
1151 MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt, args, names, nl))
1155 DummyResult::any(sp)
1160 pub fn expand_format_args<'cx>(
1161 ecx: &'cx mut ExtCtxt<'_>,
1164 ) -> Box<dyn base::MacResult + 'cx> {
1165 expand_format_args_impl(ecx, sp, tts, false)
1168 pub fn expand_format_args_nl<'cx>(
1169 ecx: &'cx mut ExtCtxt<'_>,
1172 ) -> Box<dyn base::MacResult + 'cx> {
1173 expand_format_args_impl(ecx, sp, tts, true)
1176 fn create_lints_for_named_arguments_used_positionally(cx: &mut Context<'_, '_>) {
1177 for named_arg in &cx.unused_names_lint.positional_named_args {
1178 let (position_sp_to_replace, position_sp_for_msg) = named_arg.get_positional_arg_spans(cx);
1180 let msg = format!("named argument `{}` is not used by name", named_arg.replacement);
1182 cx.ecx.buffered_early_lint.push(BufferedEarlyLint {
1183 span: MultiSpan::from_span(named_arg.positional_named_arg_span),
1185 node_id: ast::CRATE_NODE_ID,
1186 lint_id: LintId::of(&NAMED_ARGUMENTS_USED_POSITIONALLY),
1187 diagnostic: BuiltinLintDiagnostics::NamedArgumentUsedPositionally {
1188 position_sp_to_replace,
1189 position_sp_for_msg,
1190 named_arg_sp: named_arg.positional_named_arg_span,
1191 named_arg_name: named_arg.replacement.to_string(),
1192 is_formatting_arg: named_arg.ty != PositionalNamedArgType::Arg,
1198 /// Take the various parts of `format_args!(efmt, args..., name=names...)`
1199 /// and construct the appropriate formatting expression.
1200 pub fn expand_preparsed_format_args(
1201 ecx: &mut ExtCtxt<'_>,
1204 args: Vec<FormatArg>,
1205 names: FxHashMap<Symbol, usize>,
1206 append_newline: bool,
1208 // NOTE: this verbose way of initializing `Vec<Vec<ArgumentType>>` is because
1209 // `ArgumentType` does not derive `Clone`.
1210 let arg_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
1211 let arg_unique_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
1213 let mut macsp = ecx.call_site();
1214 macsp = ecx.with_def_site_ctxt(macsp);
1216 let msg = "format argument must be a string literal";
1217 let fmt_sp = efmt.span;
1218 let efmt_kind_is_lit: bool = matches!(efmt.kind, ast::ExprKind::Lit(_));
1219 let (fmt_str, fmt_style, fmt_span) = match expr_to_spanned_string(ecx, efmt, msg) {
1220 Ok(mut fmt) if append_newline => {
1221 fmt.0 = Symbol::intern(&format!("{}\n", fmt.0));
1226 if let Some((mut err, suggested)) = err {
1227 let sugg_fmt = match args.len() {
1228 0 => "{}".to_string(),
1229 _ => format!("{}{{}}", "{} ".repeat(args.len())),
1232 err.span_suggestion(
1233 fmt_sp.shrink_to_lo(),
1234 "you might be missing a string literal to format with",
1235 format!("\"{}\", ", sugg_fmt),
1236 Applicability::MaybeIncorrect,
1241 return DummyResult::raw_expr(sp, true);
1245 let str_style = match fmt_style {
1246 ast::StrStyle::Cooked => None,
1247 ast::StrStyle::Raw(raw) => Some(raw as usize),
1250 let fmt_str = fmt_str.as_str(); // for the suggestions below
1251 let fmt_snippet = ecx.source_map().span_to_snippet(fmt_sp).ok();
1252 let mut parser = parse::Parser::new(
1257 parse::ParseMode::Format,
1260 let mut unverified_pieces = Vec::new();
1261 while let Some(piece) = parser.next() {
1262 if !parser.errors.is_empty() {
1265 unverified_pieces.push(piece);
1269 if !parser.errors.is_empty() {
1270 let err = parser.errors.remove(0);
1271 let sp = if efmt_kind_is_lit {
1272 fmt_span.from_inner(InnerSpan::new(err.span.start, err.span.end))
1274 // The format string could be another macro invocation, e.g.:
1275 // format!(concat!("abc", "{}"), 4);
1276 // However, `err.span` is an inner span relative to the *result* of
1277 // the macro invocation, which is why we would get a nonsensical
1278 // result calling `fmt_span.from_inner(err.span)` as above, and
1279 // might even end up inside a multibyte character (issue #86085).
1280 // Therefore, we conservatively report the error for the entire
1281 // argument span here.
1284 let mut e = ecx.struct_span_err(sp, &format!("invalid format string: {}", err.description));
1285 e.span_label(sp, err.label + " in format string");
1286 if let Some(note) = err.note {
1289 if let Some((label, span)) = err.secondary_label {
1290 if efmt_kind_is_lit {
1291 e.span_label(fmt_span.from_inner(InnerSpan::new(span.start, span.end)), label);
1294 if err.should_be_replaced_with_positional_argument {
1295 let captured_arg_span =
1296 fmt_span.from_inner(InnerSpan::new(err.span.start, err.span.end));
1297 let n_positional_args =
1298 args.iter().rposition(|arg| arg.name.is_none()).map_or(0, |i| i + 1);
1299 if let Ok(arg) = ecx.source_map().span_to_snippet(captured_arg_span) {
1300 let span = match args[..n_positional_args].last() {
1301 Some(arg) => arg.expr.span,
1304 e.multipart_suggestion_verbose(
1305 "consider using a positional formatting argument instead",
1307 (captured_arg_span, n_positional_args.to_string()),
1308 (span.shrink_to_hi(), format!(", {}", arg)),
1310 Applicability::MachineApplicable,
1315 return DummyResult::raw_expr(sp, true);
1318 let arg_spans = parser
1321 .map(|span| fmt_span.from_inner(InnerSpan::new(span.start, span.end)))
1324 let mut cx = Context {
1327 num_captured_args: 0,
1333 arg_index_map: Vec::new(),
1334 count_args: Vec::new(),
1335 count_positions: FxHashMap::default(),
1336 count_positions_count: 0,
1337 count_args_index_offset: 0,
1338 literal: String::new(),
1339 pieces: Vec::with_capacity(unverified_pieces.len()),
1340 str_pieces: Vec::with_capacity(unverified_pieces.len()),
1341 all_pieces_simple: true,
1344 invalid_refs: Vec::new(),
1346 arg_with_formatting: Vec::new(),
1347 is_literal: parser.is_literal,
1348 unused_names_lint: PositionalNamedArgsLint { positional_named_args: vec![] },
1351 // This needs to happen *after* the Parser has consumed all pieces to create all the spans
1352 let pieces = unverified_pieces
1355 cx.verify_piece(&piece);
1356 cx.resolve_name_inplace(&mut piece);
1359 .collect::<Vec<_>>();
1361 let numbered_position_args = pieces.iter().any(|arg: &parse::Piece<'_>| match *arg {
1362 parse::String(_) => false,
1363 parse::NextArgument(arg) => matches!(arg.position, parse::Position::ArgumentIs(..)),
1366 cx.build_index_map();
1368 let mut arg_index_consumed = vec![0usize; cx.arg_index_map.len()];
1370 for piece in pieces {
1371 if let Some(piece) = cx.build_piece(&piece, &mut arg_index_consumed) {
1372 let s = cx.build_literal_string();
1373 cx.str_pieces.push(s);
1374 cx.pieces.push(piece);
1378 if !cx.literal.is_empty() {
1379 let s = cx.build_literal_string();
1380 cx.str_pieces.push(s);
1383 if !cx.invalid_refs.is_empty() {
1384 cx.report_invalid_references(numbered_position_args);
1387 // Make sure that all arguments were used and all arguments have types.
1392 .filter(|(i, ty)| ty.is_empty() && !cx.count_positions.contains_key(&i))
1394 let msg = if cx.args[i].name.is_some() {
1395 "named argument never used"
1397 "argument never used"
1399 (cx.args[i].expr.span, msg)
1401 .collect::<Vec<_>>();
1403 let errs_len = errs.len();
1404 if !errs.is_empty() {
1405 let args_used = cx.arg_types.len() - errs_len;
1406 let args_unused = errs_len;
1409 if let [(sp, msg)] = &errs[..] {
1410 let mut diag = cx.ecx.struct_span_err(*sp, *msg);
1411 diag.span_label(*sp, *msg);
1414 let mut diag = cx.ecx.struct_span_err(
1415 errs.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
1416 "multiple unused formatting arguments",
1418 diag.span_label(cx.fmtsp, "multiple missing formatting specifiers");
1419 for (sp, msg) in errs {
1420 diag.span_label(sp, msg);
1426 // Used to ensure we only report translations for *one* kind of foreign format.
1427 let mut found_foreign = false;
1428 // Decide if we want to look for foreign formatting directives.
1429 if args_used < args_unused {
1430 use super::format_foreign as foreign;
1432 // The set of foreign substitutions we've explained. This prevents spamming the user
1433 // with `%d should be written as {}` over and over again.
1434 let mut explained = FxHashSet::default();
1436 macro_rules! check_foreign {
1438 let mut show_doc_note = false;
1440 let mut suggestions = vec![];
1441 // account for `"` and account for raw strings `r#`
1442 let padding = str_style.map(|i| i + 2).unwrap_or(1);
1443 for sub in foreign::$kind::iter_subs(fmt_str, padding) {
1444 let (trn, success) = match sub.translate() {
1445 Ok(trn) => (trn, true),
1446 Err(Some(msg)) => (msg, false),
1448 // If it has no translation, don't call it out specifically.
1452 let pos = sub.position();
1453 let sub = String::from(sub.as_str());
1454 if explained.contains(&sub) {
1457 explained.insert(sub.clone());
1460 found_foreign = true;
1461 show_doc_note = true;
1464 if let Some(inner_sp) = pos {
1465 let sp = fmt_sp.from_inner(inner_sp);
1468 suggestions.push((sp, trn));
1472 &format!("format specifiers use curly braces, and {}", trn),
1477 diag.help(&format!("`{}` should be written as `{}`", sub, trn));
1480 "`{}` should use curly braces, and {}",
1490 " formatting not supported; see the documentation for `std::fmt`",
1493 if suggestions.len() > 0 {
1494 diag.multipart_suggestion(
1495 "format specifiers use curly braces",
1497 Applicability::MachineApplicable,
1503 check_foreign!(printf);
1505 check_foreign!(shell);
1508 if !found_foreign && errs_len == 1 {
1509 diag.span_label(cx.fmtsp, "formatting specifier missing");
1513 } else if cx.invalid_refs.is_empty() && cx.ecx.sess.err_count() == 0 {
1514 // Only check for unused named argument names if there are no other errors to avoid causing
1515 // too much noise in output errors, such as when a named argument is entirely unused.
1516 create_lints_for_named_arguments_used_positionally(&mut cx);
1522 fn may_contain_yield_point(e: &ast::Expr) -> bool {
1523 struct MayContainYieldPoint(bool);
1525 impl Visitor<'_> for MayContainYieldPoint {
1526 fn visit_expr(&mut self, e: &ast::Expr) {
1527 if let ast::ExprKind::Await(_) | ast::ExprKind::Yield(_) = e.kind {
1530 visit::walk_expr(self, e);
1534 fn visit_mac_call(&mut self, _: &ast::MacCall) {
1538 fn visit_attribute(&mut self, _: &ast::Attribute) {
1539 // Conservatively assume this may be a proc macro attribute in
1540 // expression position.
1544 fn visit_item(&mut self, _: &ast::Item) {
1545 // Do not recurse into nested items.
1549 let mut visitor = MayContainYieldPoint(false);
1550 visitor.visit_expr(e);