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 current_positional_arg: usize,
134 total_args_length: usize,
135 format_argument_index: usize,
136 ty: PositionalNamedArgType,
138 inner_span_to_replace: Option<rustc_parse_format::InnerSpan>,
139 names: &FxHashMap<Symbol, (usize, Span)>,
140 has_formatting: bool,
142 let start_of_named_args = total_args_length - names.len();
143 if current_positional_arg >= start_of_named_args {
145 format_argument_index,
148 inner_span_to_replace,
155 /// Try constructing a PositionalNamedArg struct and pushing it into the vec of positional
156 /// named arguments. If a named arg associated with `format_argument_index` cannot be found,
157 /// a new item will not be added as the lint cannot be emitted in this case.
160 format_argument_index: usize,
161 ty: PositionalNamedArgType,
163 inner_span_to_replace: Option<rustc_parse_format::InnerSpan>,
164 names: &FxHashMap<Symbol, (usize, Span)>,
165 has_formatting: bool,
167 let named_arg = names
169 .find(|&(_, &(index, _))| index == format_argument_index)
170 .map(|found| found.clone());
172 if let Some((&replacement, &(_, positional_named_arg_span))) = named_arg {
173 // In FormatSpec, `precision_span` starts at the leading `.`, which we want to keep in
174 // the lint suggestion, so increment `start` by 1 when `PositionalArgumentType` is
176 let inner_span_to_replace = if ty == PositionalNamedArgType::Precision {
177 inner_span_to_replace
178 .map(|is| rustc_parse_format::InnerSpan { start: is.start + 1, end: is.end })
180 inner_span_to_replace
182 self.positional_named_args.push(PositionalNamedArg {
185 inner_span_to_replace,
187 positional_named_arg_span,
194 struct Context<'a, 'b> {
195 ecx: &'a mut ExtCtxt<'b>,
196 /// The macro's call site. References to unstable formatting internals must
197 /// use this span to pass the stability checker.
199 /// The span of the format string literal.
202 /// List of parsed argument expressions.
203 /// Named expressions are resolved early, and are appended to the end of
204 /// argument expressions.
206 /// Example showing the various data structures in motion:
208 /// * Original: `"{foo:o} {:o} {foo:x} {0:x} {1:o} {:x} {1:x} {0:o}"`
209 /// * Implicit argument resolution: `"{foo:o} {0:o} {foo:x} {0:x} {1:o} {1:x} {1:x} {0:o}"`
210 /// * Name resolution: `"{2:o} {0:o} {2:x} {0:x} {1:o} {1:x} {1:x} {0:o}"`
211 /// * `arg_types` (in JSON): `[[0, 1, 0], [0, 1, 1], [0, 1]]`
212 /// * `arg_unique_types` (in simplified JSON): `[["o", "x"], ["o", "x"], ["o", "x"]]`
213 /// * `names` (in JSON): `{"foo": 2}`
214 args: Vec<P<ast::Expr>>,
215 /// The number of arguments that were added by implicit capturing.
216 num_captured_args: usize,
217 /// Placeholder slot numbers indexed by argument.
218 arg_types: Vec<Vec<usize>>,
219 /// Unique format specs seen for each argument.
220 arg_unique_types: Vec<Vec<ArgumentType>>,
221 /// Map from named arguments to their resolved indices.
222 names: FxHashMap<Symbol, (usize, Span)>,
224 /// The latest consecutive literal strings, or empty if there weren't any.
227 /// Collection of the compiled `rt::Argument` structures
228 pieces: Vec<P<ast::Expr>>,
229 /// Collection of string literals
230 str_pieces: Vec<P<ast::Expr>>,
231 /// Stays `true` if all formatting parameters are default (as in "{}{}").
232 all_pieces_simple: bool,
234 /// Mapping between positional argument references and indices into the
235 /// final generated static argument array. We record the starting indices
236 /// corresponding to each positional argument, and number of references
237 /// consumed so far for each argument, to facilitate correct `Position`
238 /// mapping in `build_piece`. In effect this can be seen as a "flattened"
239 /// version of `arg_unique_types`.
241 /// Again with the example described above in docstring for `args`:
243 /// * `arg_index_map` (in JSON): `[[0, 1, 0], [2, 3, 3], [4, 5]]`
244 arg_index_map: Vec<Vec<usize>>,
246 /// Starting offset of count argument slots.
247 count_args_index_offset: usize,
249 /// Count argument slots and tracking data structures.
250 /// Count arguments are separately tracked for de-duplication in case
251 /// multiple references are made to one argument. For example, in this
254 /// * Original: `"{:.*} {:.foo$} {1:.*} {:.0$}"`
255 /// * Implicit argument resolution: `"{1:.0$} {2:.foo$} {1:.3$} {4:.0$}"`
256 /// * Name resolution: `"{1:.0$} {2:.5$} {1:.3$} {4:.0$}"`
257 /// * `count_positions` (in JSON): `{0: 0, 5: 1, 3: 2}`
258 /// * `count_args`: `vec![0, 5, 3]`
259 count_args: Vec<usize>,
260 /// Relative slot numbers for count arguments.
261 count_positions: FxHashMap<usize, usize>,
262 /// Number of count slots assigned.
263 count_positions_count: usize,
265 /// Current position of the implicit positional arg pointer, as if it
266 /// still existed in this phase of processing.
267 /// Used only for `all_pieces_simple` tracking in `build_piece`.
269 /// Current piece being evaluated, used for error reporting.
271 /// Keep track of invalid references to positional arguments.
272 invalid_refs: Vec<(usize, usize)>,
273 /// Spans of all the formatting arguments, in order.
274 arg_spans: Vec<Span>,
275 /// All the formatting arguments that have formatting flags set, in order for diagnostics.
276 arg_with_formatting: Vec<parse::FormatSpec<'a>>,
278 /// Whether this format string came from a string literal, as opposed to a macro.
280 unused_names_lint: PositionalNamedArgsLint,
283 pub struct FormatArg {
288 /// Parses the arguments from the given list of tokens, returning the diagnostic
289 /// if there's a parse error so we can continue parsing other format!
292 /// If parsing succeeds, the return value is:
295 /// Some((fmtstr, parsed arguments, index map for named arguments))
298 ecx: &mut ExtCtxt<'a>,
301 ) -> PResult<'a, (P<ast::Expr>, Vec<FormatArg>, FxHashMap<Symbol, (usize, Span)>)> {
302 let mut args = Vec::<FormatArg>::new();
303 let mut names = FxHashMap::<Symbol, (usize, Span)>::default();
305 let mut p = ecx.new_parser_from_tts(tts);
307 if p.token == token::Eof {
308 return Err(ecx.struct_span_err(sp, "requires at least a format string argument"));
311 let first_token = &p.token;
312 let fmtstr = match first_token.kind {
313 token::TokenKind::Literal(token::Lit {
314 kind: token::LitKind::Str | token::LitKind::StrRaw(_),
317 // If the first token is a string literal, then a format expression
318 // is constructed from it.
320 // This allows us to properly handle cases when the first comma
321 // after the format string is mistakenly replaced with any operator,
322 // which cause the expression parser to eat too much tokens.
323 p.parse_literal_maybe_minus()?
326 // Otherwise, we fall back to the expression parser.
331 let mut first = true;
332 let mut named = false;
334 while p.token != token::Eof {
335 if !p.eat(&token::Comma) {
337 p.clear_expected_tokens();
340 match p.expect(&token::Comma) {
342 match token::TokenKind::Comma.similar_tokens() {
343 Some(tks) if tks.contains(&p.token.kind) => {
344 // If a similar token is found, then it may be a typo. We
345 // consider it as a comma, and continue parsing.
349 // Otherwise stop the parsing and return the error.
350 _ => return Err(err),
359 if p.token == token::Eof {
361 } // accept trailing commas
362 match p.token.ident() {
363 Some((ident, _)) if p.look_ahead(1, |t| *t == token::Eq) => {
366 p.expect(&token::Eq)?;
367 let e = p.parse_expr()?;
368 if let Some((prev, _)) = names.get(&ident.name) {
369 ecx.struct_span_err(e.span, &format!("duplicate argument named `{}`", ident))
370 .span_label(args[*prev].expr.span, "previously here")
371 .span_label(e.span, "duplicate argument")
376 // Resolve names into slots early.
377 // Since all the positional args are already seen at this point
378 // if the input is valid, we can simply append to the positional
379 // args. And remember the names.
380 let slot = args.len();
381 names.insert(ident.name, (slot, ident.span));
382 args.push(FormatArg { expr: e, named: true });
385 let e = p.parse_expr()?;
387 let mut err = ecx.struct_span_err(
389 "positional arguments cannot follow named arguments",
391 err.span_label(e.span, "positional arguments must be before named arguments");
392 for pos in names.values() {
393 err.span_label(args[pos.0].expr.span, "named argument");
397 args.push(FormatArg { expr: e, named: false });
401 Ok((fmtstr, args, names))
404 impl<'a, 'b> Context<'a, 'b> {
405 /// The number of arguments that were explicitly given.
406 fn num_args(&self) -> usize {
407 self.args.len() - self.num_captured_args
410 fn resolve_name_inplace(&mut self, p: &mut parse::Piece<'_>) {
411 // NOTE: the `unwrap_or` branch is needed in case of invalid format
412 // arguments, e.g., `format_args!("{foo}")`.
414 |s: &str| self.names.get(&Symbol::intern(s)).unwrap_or(&(0, Span::default())).0;
417 parse::String(_) => {}
418 parse::NextArgument(ref mut arg) => {
419 if let parse::ArgumentNamed(s) = arg.position {
420 arg.position = parse::ArgumentIs(lookup(s));
422 if let parse::CountIsName(s, _) = arg.format.width {
423 arg.format.width = parse::CountIsParam(lookup(s));
425 if let parse::CountIsName(s, _) = arg.format.precision {
426 arg.format.precision = parse::CountIsParam(lookup(s));
432 /// Verifies one piece of a parse string, and remembers it if valid.
433 /// All errors are not emitted as fatal so we can continue giving errors
434 /// about this and possibly other format strings.
435 fn verify_piece(&mut self, p: &parse::Piece<'_>) {
437 parse::String(..) => {}
438 parse::NextArgument(ref arg) => {
439 // width/precision first, if they have implicit positional
440 // parameters it makes more sense to consume them first.
443 &arg.format.width_span,
444 PositionalNamedArgType::Width,
447 arg.format.precision,
448 &arg.format.precision_span,
449 PositionalNamedArgType::Precision,
452 let has_precision = arg.format.precision != Count::CountImplied;
453 let has_width = arg.format.width != Count::CountImplied;
455 // argument second, if it's an implicit positional parameter
456 // it's written second, so it should come after width/precision.
457 let pos = match arg.position {
458 parse::ArgumentIs(i) => {
459 self.unused_names_lint.maybe_add_positional_named_arg(
463 PositionalNamedArgType::Arg,
465 Some(arg.position_span),
467 has_precision || has_width,
472 parse::ArgumentImplicitlyIs(i) => {
473 self.unused_names_lint.maybe_add_positional_named_arg(
477 PositionalNamedArgType::Arg,
481 has_precision || has_width,
485 parse::ArgumentNamed(s) => {
486 let symbol = Symbol::intern(s);
487 let span = arg.position_span;
488 Named(symbol, InnerSpan::new(span.start, span.end))
492 let ty = Placeholder(match arg.format.ty {
503 let fmtsp = self.fmtsp;
507 .map(|sp| fmtsp.from_inner(InnerSpan::new(sp.start, sp.end)));
508 let mut err = self.ecx.struct_span_err(
510 &format!("unknown format trait `{}`", arg.format.ty),
513 "the only appropriate formatting traits are:\n\
514 - ``, which uses the `Display` trait\n\
515 - `?`, which uses the `Debug` trait\n\
516 - `e`, which uses the `LowerExp` trait\n\
517 - `E`, which uses the `UpperExp` trait\n\
518 - `o`, which uses the `Octal` trait\n\
519 - `p`, which uses the `Pointer` trait\n\
520 - `b`, which uses the `Binary` trait\n\
521 - `x`, which uses the `LowerHex` trait\n\
522 - `X`, which uses the `UpperHex` trait",
524 if let Some(sp) = sp {
525 for (fmt, name) in &[
536 // FIXME: rustfix (`run-rustfix`) fails to apply suggestions.
537 // > "Cannot replace slice of data that was already replaced"
538 err.tool_only_span_suggestion(
540 &format!("use the `{}` trait", name),
542 Applicability::MaybeIncorrect,
550 self.verify_arg_type(pos, ty);
559 inner_span: &Option<rustc_parse_format::InnerSpan>,
560 named_arg_type: PositionalNamedArgType,
563 parse::CountImplied | parse::CountIs(..) => {}
564 parse::CountIsParam(i) => {
565 self.unused_names_lint.maybe_add_positional_named_arg(
575 self.verify_arg_type(Exact(i), Count);
577 parse::CountIsName(s, span) => {
578 self.verify_arg_type(
579 Named(Symbol::intern(s), InnerSpan::new(span.start, span.end)),
586 fn describe_num_args(&self) -> Cow<'_, str> {
587 match self.num_args() {
588 0 => "no arguments were given".into(),
589 1 => "there is 1 argument".into(),
590 x => format!("there are {} arguments", x).into(),
594 /// Handle invalid references to positional arguments. Output different
595 /// errors for the case where all arguments are positional and for when
596 /// there are named arguments or numbered positional arguments in the
598 fn report_invalid_references(&self, numbered_position_args: bool) {
600 let sp = if !self.arg_spans.is_empty() {
601 // Point at the formatting arguments.
602 MultiSpan::from_spans(self.arg_spans.clone())
604 MultiSpan::from_span(self.fmtsp)
607 self.invalid_refs.iter().map(|(r, pos)| (r.to_string(), self.arg_spans.get(*pos)));
609 let mut zero_based_note = false;
611 let count = self.pieces.len()
612 + self.arg_with_formatting.iter().filter(|fmt| fmt.precision_span.is_some()).count();
613 if self.names.is_empty() && !numbered_position_args && count != self.num_args() {
614 e = self.ecx.struct_span_err(
617 "{} positional argument{} in format string, but {}",
620 self.describe_num_args(),
623 for arg in &self.args {
624 // Point at the arguments that will be formatted.
625 e.span_label(arg.span, "");
628 let (mut refs, spans): (Vec<_>, Vec<_>) = refs.unzip();
629 // Avoid `invalid reference to positional arguments 7 and 7 (there is 1 argument)`
630 // for `println!("{7:7$}", 1);`
633 let spans: Vec<_> = spans.into_iter().filter_map(|sp| sp.copied()).collect();
634 let sp = if self.arg_spans.is_empty() || spans.is_empty() {
635 MultiSpan::from_span(self.fmtsp)
637 MultiSpan::from_spans(spans)
639 let arg_list = if refs.len() == 1 {
640 format!("argument {}", refs[0])
642 let reg = refs.pop().unwrap();
643 format!("arguments {head} and {tail}", head = refs.join(", "), tail = reg)
646 e = self.ecx.struct_span_err(
649 "invalid reference to positional {} ({})",
651 self.describe_num_args()
654 zero_based_note = true;
657 for fmt in &self.arg_with_formatting {
658 if let Some(span) = fmt.precision_span {
659 let span = self.fmtsp.from_inner(InnerSpan::new(span.start, span.end));
660 match fmt.precision {
661 parse::CountIsParam(pos) if pos > self.num_args() => {
665 "this precision flag expects an `usize` argument at position {}, \
668 self.describe_num_args(),
671 zero_based_note = true;
673 parse::CountIsParam(pos) => {
674 let count = self.pieces.len()
678 .filter(|fmt| fmt.precision_span.is_some())
683 "this precision flag adds an extra required argument at position {}, \
684 which is why there {} expected",
687 "is 1 argument".to_string()
689 format!("are {} arguments", count)
693 if let Some(arg) = self.args.get(pos) {
696 "this parameter corresponds to the precision flag",
699 zero_based_note = true;
704 if let Some(span) = fmt.width_span {
705 let span = self.fmtsp.from_inner(InnerSpan::new(span.start, span.end));
707 parse::CountIsParam(pos) if pos >= self.num_args() => {
711 "this width flag expects an `usize` argument at position {}, \
714 self.describe_num_args(),
717 zero_based_note = true;
724 e.note("positional arguments are zero-based");
726 if !self.arg_with_formatting.is_empty() {
728 "for information about formatting flags, visit \
729 https://doc.rust-lang.org/std/fmt/index.html",
736 /// Actually verifies and tracks a given format placeholder
737 /// (a.k.a. argument).
738 fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
739 if let Exact(arg) = arg {
740 if arg >= self.num_args() {
741 self.invalid_refs.push((arg, self.curpiece));
747 Exact(arg) | Capture(arg) => {
750 // record every (position, type) combination only once
751 let seen_ty = &mut self.arg_unique_types[arg];
752 let i = seen_ty.iter().position(|x| *x == ty).unwrap_or_else(|| {
753 let i = seen_ty.len();
757 self.arg_types[arg].push(i);
760 if let Entry::Vacant(e) = self.count_positions.entry(arg) {
761 let i = self.count_positions_count;
763 self.count_args.push(arg);
764 self.count_positions_count += 1;
770 Named(name, span) => {
771 match self.names.get(&name) {
773 // Treat as positional arg.
774 self.verify_arg_type(Capture(idx.0), ty)
777 // For the moment capturing variables from format strings expanded from macros is
778 // disabled (see RFC #2795)
780 // Treat this name as a variable to capture from the surrounding scope
781 let idx = self.args.len();
782 self.arg_types.push(Vec::new());
783 self.arg_unique_types.push(Vec::new());
784 let span = if self.is_literal {
785 self.fmtsp.from_inner(span)
789 self.num_captured_args += 1;
790 self.args.push(self.ecx.expr_ident(span, Ident::new(name, span)));
791 self.names.insert(name, (idx, span));
792 self.verify_arg_type(Capture(idx), ty)
794 let msg = format!("there is no argument named `{}`", name);
795 let sp = if self.is_literal {
796 self.fmtsp.from_inner(span)
800 let mut err = self.ecx.struct_span_err(sp, &msg);
803 "did you intend to capture a variable `{}` from \
804 the surrounding scope?",
808 "to avoid ambiguity, `format_args!` cannot capture variables \
809 when the format string is expanded from a macro",
820 /// Builds the mapping between format placeholders and argument objects.
821 fn build_index_map(&mut self) {
822 // NOTE: Keep the ordering the same as `into_expr`'s expansion would do!
823 let args_len = self.args.len();
824 self.arg_index_map.reserve(args_len);
826 let mut sofar = 0usize;
829 for i in 0..args_len {
830 let arg_types = &self.arg_types[i];
831 let arg_offsets = arg_types.iter().map(|offset| sofar + *offset).collect::<Vec<_>>();
832 self.arg_index_map.push(arg_offsets);
833 sofar += self.arg_unique_types[i].len();
836 // Record starting index for counts, which appear just after arguments
837 self.count_args_index_offset = sofar;
840 fn rtpath(ecx: &ExtCtxt<'_>, s: Symbol) -> Vec<Ident> {
841 ecx.std_path(&[sym::fmt, sym::rt, sym::v1, s])
844 fn build_count(&self, c: parse::Count<'_>) -> P<ast::Expr> {
846 let count = |c, arg| {
847 let mut path = Context::rtpath(self.ecx, sym::Count);
848 path.push(Ident::new(c, sp));
850 Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]),
851 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
855 parse::CountIs(i) => count(sym::Is, Some(self.ecx.expr_usize(sp, i))),
856 parse::CountIsParam(i) => {
857 // This needs mapping too, as `i` is referring to a macro
858 // argument. If `i` is not found in `count_positions` then
859 // the error had already been emitted elsewhere.
860 let i = self.count_positions.get(&i).cloned().unwrap_or(0)
861 + self.count_args_index_offset;
862 count(sym::Param, Some(self.ecx.expr_usize(sp, i)))
864 parse::CountImplied => count(sym::Implied, None),
865 // should never be the case, names are already resolved
866 parse::CountIsName(..) => panic!("should never happen"),
870 /// Build a literal expression from the accumulated string literals
871 fn build_literal_string(&mut self) -> P<ast::Expr> {
873 let s = Symbol::intern(&self.literal);
874 self.literal.clear();
875 self.ecx.expr_str(sp, s)
878 /// Builds a static `rt::Argument` from a `parse::Piece` or append
879 /// to the `literal` string.
882 piece: &parse::Piece<'a>,
883 arg_index_consumed: &mut Vec<usize>,
884 ) -> Option<P<ast::Expr>> {
887 parse::String(s) => {
888 self.literal.push_str(s);
891 parse::NextArgument(ref arg) => {
892 // Build the position
895 parse::ArgumentIs(i, ..) | parse::ArgumentImplicitlyIs(i) => {
896 // Map to index in final generated argument array
897 // in case of multiple types specified
898 let arg_idx = match arg_index_consumed.get_mut(i) {
899 None => 0, // error already emitted elsewhere
901 let idx_map = &self.arg_index_map[i];
902 // unwrap_or branch: error already emitted elsewhere
903 let arg_idx = *idx_map.get(*offset).unwrap_or(&0);
908 self.ecx.expr_usize(sp, arg_idx)
911 // should never be the case, because names are already
913 parse::ArgumentNamed(..) => panic!("should never happen"),
917 let simple_arg = parse::Argument {
919 // We don't have ArgumentNext any more, so we have to
920 // track the current argument ourselves.
925 position_span: arg.position_span,
926 format: parse::FormatSpec {
927 fill: arg.format.fill,
928 align: parse::AlignUnknown,
930 precision: parse::CountImplied,
931 precision_span: None,
932 width: parse::CountImplied,
935 ty_span: arg.format.ty_span,
939 let fill = arg.format.fill.unwrap_or(' ');
941 let pos_simple = arg.position.index() == simple_arg.position.index();
943 if arg.format.precision_span.is_some() || arg.format.width_span.is_some() {
944 self.arg_with_formatting.push(arg.format);
946 if !pos_simple || arg.format != simple_arg.format || fill != ' ' {
947 self.all_pieces_simple = false;
951 let fill = self.ecx.expr_lit(sp, ast::LitKind::Char(fill));
953 let mut p = Context::rtpath(self.ecx, sym::Alignment);
954 p.push(Ident::new(name, sp));
955 self.ecx.path_global(sp, p)
957 let align = match arg.format.align {
958 parse::AlignLeft => align(sym::Left),
959 parse::AlignRight => align(sym::Right),
960 parse::AlignCenter => align(sym::Center),
961 parse::AlignUnknown => align(sym::Unknown),
963 let align = self.ecx.expr_path(align);
964 let flags = self.ecx.expr_u32(sp, arg.format.flags);
965 let prec = self.build_count(arg.format.precision);
966 let width = self.build_count(arg.format.width);
967 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, sym::FormatSpec));
968 let fmt = self.ecx.expr_struct(
972 self.ecx.field_imm(sp, Ident::new(sym::fill, sp), fill),
973 self.ecx.field_imm(sp, Ident::new(sym::align, sp), align),
974 self.ecx.field_imm(sp, Ident::new(sym::flags, sp), flags),
975 self.ecx.field_imm(sp, Ident::new(sym::precision, sp), prec),
976 self.ecx.field_imm(sp, Ident::new(sym::width, sp), width),
980 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, sym::Argument));
981 Some(self.ecx.expr_struct(
985 self.ecx.field_imm(sp, Ident::new(sym::position, sp), pos),
986 self.ecx.field_imm(sp, Ident::new(sym::format, sp), fmt),
993 /// Actually builds the expression which the format_args! block will be
995 fn into_expr(self) -> P<ast::Expr> {
996 let mut original_args = self.args;
997 let mut fmt_args = Vec::with_capacity(
998 self.arg_unique_types.iter().map(|v| v.len()).sum::<usize>() + self.count_args.len(),
1001 // First, build up the static array which will become our precompiled
1003 let pieces = self.ecx.expr_array_ref(self.fmtsp, self.str_pieces);
1005 // We need to construct a &[ArgumentV1] to pass into the fmt::Arguments
1006 // constructor. In general the expressions in this slice might be
1007 // permuted from their order in original_args (such as in the case of
1008 // "{1} {0}"), or may have multiple entries referring to the same
1009 // element of original_args ("{0} {0}").
1011 // The following vector has one item per element of our output slice,
1012 // identifying the index of which element of original_args it's passing,
1013 // and that argument's type.
1014 let mut fmt_arg_index_and_ty = SmallVec::<[(usize, &ArgumentType); 8]>::new();
1015 for (i, unique_types) in self.arg_unique_types.iter().enumerate() {
1016 fmt_arg_index_and_ty.extend(unique_types.iter().map(|ty| (i, ty)));
1018 fmt_arg_index_and_ty.extend(self.count_args.iter().map(|&i| (i, &Count)));
1020 // Figure out whether there are permuted or repeated elements. If not,
1021 // we can generate simpler code.
1023 // The sequence has no indices out of order or repeated if: for every
1024 // adjacent pair of elements, the first one's index is less than the
1025 // second one's index.
1026 let nicely_ordered =
1027 fmt_arg_index_and_ty.array_windows().all(|[(i, _i_ty), (j, _j_ty)]| i < j);
1031 // [ArgumentV1::new(&$arg0, …), ArgumentV1::new(&$arg1, …), …]
1033 // However, it's only legal to do so if $arg0, $arg1, … were written in
1034 // exactly that order by the programmer. When arguments are permuted, we
1035 // want them evaluated in the order written by the programmer, not in
1036 // the order provided to fmt::Arguments. When arguments are repeated, we
1037 // want the expression evaluated only once.
1039 // Further, if any arg _after the first one_ contains a yield point such
1040 // as `await` or `yield`, the above short form is inconvenient for the
1041 // caller because it would keep a temporary of type ArgumentV1 alive
1042 // across the yield point. ArgumentV1 can't implement Send since it
1043 // holds a type-erased arbitrary type.
1045 // Thus in the not nicely ordered case, and in the yielding case, we
1046 // emit the following instead:
1048 // match (&$arg0, &$arg1, …) {
1049 // args => [ArgumentV1::new(args.$i, …), ArgumentV1::new(args.$j, …), …]
1052 // for the sequence of indices $i, $j, … governed by fmt_arg_index_and_ty.
1053 // This more verbose representation ensures that all arguments are
1054 // evaluated a single time each, in the order written by the programmer,
1055 // and that the surrounding future/generator (if any) is Send whenever
1057 let no_need_for_match =
1058 nicely_ordered && !original_args.iter().skip(1).any(|e| may_contain_yield_point(e));
1060 for (arg_index, arg_ty) in fmt_arg_index_and_ty {
1061 let e = &mut original_args[arg_index];
1063 let arg = if no_need_for_match {
1064 let expansion_span = e.span.with_ctxt(self.macsp.ctxt());
1065 // The indices are strictly ordered so e has not been taken yet.
1066 self.ecx.expr_addr_of(expansion_span, P(e.take()))
1068 let def_site = self.ecx.with_def_site_ctxt(span);
1069 let args_tuple = self.ecx.expr_ident(def_site, Ident::new(sym::args, def_site));
1070 let member = Ident::new(sym::integer(arg_index), def_site);
1071 self.ecx.expr(def_site, ast::ExprKind::Field(args_tuple, member))
1073 fmt_args.push(Context::format_arg(self.ecx, self.macsp, span, arg_ty, arg));
1076 let args_array = self.ecx.expr_array(self.macsp, fmt_args);
1077 let args_slice = self.ecx.expr_addr_of(
1079 if no_need_for_match {
1082 // In the !no_need_for_match case, none of the exprs were moved
1083 // away in the previous loop.
1085 // This uses the arg span for `&arg` so that borrowck errors
1086 // point to the specific expression passed to the macro (the
1087 // span is otherwise unavailable in the MIR used by borrowck).
1088 let heads = original_args
1090 .map(|e| self.ecx.expr_addr_of(e.span.with_ctxt(self.macsp.ctxt()), e))
1093 let pat = self.ecx.pat_ident(self.macsp, Ident::new(sym::args, self.macsp));
1094 let arm = self.ecx.arm(self.macsp, pat, args_array);
1095 let head = self.ecx.expr(self.macsp, ast::ExprKind::Tup(heads));
1096 self.ecx.expr_match(self.macsp, head, vec![arm])
1100 // Now create the fmt::Arguments struct with all our locals we created.
1101 let (fn_name, fn_args) = if self.all_pieces_simple {
1102 ("new_v1", vec![pieces, args_slice])
1104 // Build up the static array which will store our precompiled
1105 // nonstandard placeholders, if there are any.
1106 let fmt = self.ecx.expr_array_ref(self.macsp, self.pieces);
1108 let path = self.ecx.std_path(&[sym::fmt, sym::UnsafeArg, sym::new]);
1109 let unsafe_arg = self.ecx.expr_call_global(self.macsp, path, Vec::new());
1110 let unsafe_expr = self.ecx.expr_block(P(ast::Block {
1111 stmts: vec![self.ecx.stmt_expr(unsafe_arg)],
1112 id: ast::DUMMY_NODE_ID,
1113 rules: BlockCheckMode::Unsafe(UnsafeSource::CompilerGenerated),
1116 could_be_bare_literal: false,
1119 ("new_v1_formatted", vec![pieces, args_slice, fmt, unsafe_expr])
1122 let path = self.ecx.std_path(&[sym::fmt, sym::Arguments, Symbol::intern(fn_name)]);
1123 self.ecx.expr_call_global(self.macsp, path, fn_args)
1133 sp = ecx.with_def_site_ctxt(sp);
1134 let trait_ = match *ty {
1135 Placeholder(trait_) if trait_ == "<invalid>" => return DummyResult::raw_expr(sp, true),
1136 Placeholder(trait_) => trait_,
1138 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, sym::from_usize]);
1139 return ecx.expr_call_global(macsp, path, vec![arg]);
1142 let new_fn_name = match trait_ {
1143 "Display" => "new_display",
1144 "Debug" => "new_debug",
1145 "LowerExp" => "new_lower_exp",
1146 "UpperExp" => "new_upper_exp",
1147 "Octal" => "new_octal",
1148 "Pointer" => "new_pointer",
1149 "Binary" => "new_binary",
1150 "LowerHex" => "new_lower_hex",
1151 "UpperHex" => "new_upper_hex",
1152 _ => unreachable!(),
1155 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, Symbol::intern(new_fn_name)]);
1156 ecx.expr_call_global(sp, path, vec![arg])
1160 fn expand_format_args_impl<'cx>(
1161 ecx: &'cx mut ExtCtxt<'_>,
1165 ) -> Box<dyn base::MacResult + 'cx> {
1166 sp = ecx.with_def_site_ctxt(sp);
1167 match parse_args(ecx, sp, tts) {
1168 Ok((efmt, args, names)) => {
1169 MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt, args, names, nl))
1173 DummyResult::any(sp)
1178 pub fn expand_format_args<'cx>(
1179 ecx: &'cx mut ExtCtxt<'_>,
1182 ) -> Box<dyn base::MacResult + 'cx> {
1183 expand_format_args_impl(ecx, sp, tts, false)
1186 pub fn expand_format_args_nl<'cx>(
1187 ecx: &'cx mut ExtCtxt<'_>,
1190 ) -> Box<dyn base::MacResult + 'cx> {
1191 expand_format_args_impl(ecx, sp, tts, true)
1194 fn create_lints_for_named_arguments_used_positionally(cx: &mut Context<'_, '_>) {
1195 for named_arg in &cx.unused_names_lint.positional_named_args {
1196 let (position_sp_to_replace, position_sp_for_msg) = named_arg.get_positional_arg_spans(cx);
1198 let msg = format!("named argument `{}` is not used by name", named_arg.replacement);
1200 cx.ecx.buffered_early_lint.push(BufferedEarlyLint {
1201 span: MultiSpan::from_span(named_arg.positional_named_arg_span),
1203 node_id: ast::CRATE_NODE_ID,
1204 lint_id: LintId::of(&NAMED_ARGUMENTS_USED_POSITIONALLY),
1205 diagnostic: BuiltinLintDiagnostics::NamedArgumentUsedPositionally {
1206 position_sp_to_replace,
1207 position_sp_for_msg,
1208 named_arg_sp: named_arg.positional_named_arg_span,
1209 named_arg_name: named_arg.replacement.to_string(),
1210 is_formatting_arg: named_arg.ty != PositionalNamedArgType::Arg,
1216 /// Take the various parts of `format_args!(efmt, args..., name=names...)`
1217 /// and construct the appropriate formatting expression.
1218 pub fn expand_preparsed_format_args(
1219 ecx: &mut ExtCtxt<'_>,
1222 args: Vec<FormatArg>,
1223 names: FxHashMap<Symbol, (usize, Span)>,
1224 append_newline: bool,
1226 // NOTE: this verbose way of initializing `Vec<Vec<ArgumentType>>` is because
1227 // `ArgumentType` does not derive `Clone`.
1228 let arg_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
1229 let arg_unique_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
1231 let mut macsp = ecx.call_site();
1232 macsp = ecx.with_def_site_ctxt(macsp);
1234 let msg = "format argument must be a string literal";
1235 let fmt_sp = efmt.span;
1236 let efmt_kind_is_lit: bool = matches!(efmt.kind, ast::ExprKind::Lit(_));
1237 let (fmt_str, fmt_style, fmt_span) = match expr_to_spanned_string(ecx, efmt, msg) {
1238 Ok(mut fmt) if append_newline => {
1239 fmt.0 = Symbol::intern(&format!("{}\n", fmt.0));
1244 if let Some((mut err, suggested)) = err {
1245 let sugg_fmt = match args.len() {
1246 0 => "{}".to_string(),
1247 _ => format!("{}{{}}", "{} ".repeat(args.len())),
1250 err.span_suggestion(
1251 fmt_sp.shrink_to_lo(),
1252 "you might be missing a string literal to format with",
1253 format!("\"{}\", ", sugg_fmt),
1254 Applicability::MaybeIncorrect,
1259 return DummyResult::raw_expr(sp, true);
1263 let str_style = match fmt_style {
1264 ast::StrStyle::Cooked => None,
1265 ast::StrStyle::Raw(raw) => Some(raw as usize),
1268 let fmt_str = fmt_str.as_str(); // for the suggestions below
1269 let fmt_snippet = ecx.source_map().span_to_snippet(fmt_sp).ok();
1270 let mut parser = parse::Parser::new(
1275 parse::ParseMode::Format,
1278 let mut unverified_pieces = Vec::new();
1279 while let Some(piece) = parser.next() {
1280 if !parser.errors.is_empty() {
1283 unverified_pieces.push(piece);
1287 if !parser.errors.is_empty() {
1288 let err = parser.errors.remove(0);
1289 let sp = if efmt_kind_is_lit {
1290 fmt_span.from_inner(InnerSpan::new(err.span.start, err.span.end))
1292 // The format string could be another macro invocation, e.g.:
1293 // format!(concat!("abc", "{}"), 4);
1294 // However, `err.span` is an inner span relative to the *result* of
1295 // the macro invocation, which is why we would get a nonsensical
1296 // result calling `fmt_span.from_inner(err.span)` as above, and
1297 // might even end up inside a multibyte character (issue #86085).
1298 // Therefore, we conservatively report the error for the entire
1299 // argument span here.
1302 let mut e = ecx.struct_span_err(sp, &format!("invalid format string: {}", err.description));
1303 e.span_label(sp, err.label + " in format string");
1304 if let Some(note) = err.note {
1307 if let Some((label, span)) = err.secondary_label {
1308 if efmt_kind_is_lit {
1309 e.span_label(fmt_span.from_inner(InnerSpan::new(span.start, span.end)), label);
1312 if err.should_be_replaced_with_positional_argument {
1313 let captured_arg_span =
1314 fmt_span.from_inner(InnerSpan::new(err.span.start, err.span.end));
1315 let positional_args = args.iter().filter(|arg| !arg.named).collect::<Vec<_>>();
1316 if let Ok(arg) = ecx.source_map().span_to_snippet(captured_arg_span) {
1317 let span = match positional_args.last() {
1318 Some(arg) => arg.expr.span,
1321 e.multipart_suggestion_verbose(
1322 "consider using a positional formatting argument instead",
1324 (captured_arg_span, positional_args.len().to_string()),
1325 (span.shrink_to_hi(), format!(", {}", arg)),
1327 Applicability::MachineApplicable,
1332 return DummyResult::raw_expr(sp, true);
1335 let arg_spans = parser
1338 .map(|span| fmt_span.from_inner(InnerSpan::new(span.start, span.end)))
1341 let named_pos: FxHashSet<usize> = names.values().cloned().map(|(i, _)| i).collect();
1343 let mut cx = Context {
1345 args: args.into_iter().map(|arg| arg.expr).collect(),
1346 num_captured_args: 0,
1352 arg_index_map: Vec::new(),
1353 count_args: Vec::new(),
1354 count_positions: FxHashMap::default(),
1355 count_positions_count: 0,
1356 count_args_index_offset: 0,
1357 literal: String::new(),
1358 pieces: Vec::with_capacity(unverified_pieces.len()),
1359 str_pieces: Vec::with_capacity(unverified_pieces.len()),
1360 all_pieces_simple: true,
1363 invalid_refs: Vec::new(),
1365 arg_with_formatting: Vec::new(),
1366 is_literal: parser.is_literal,
1367 unused_names_lint: PositionalNamedArgsLint { positional_named_args: vec![] },
1370 // This needs to happen *after* the Parser has consumed all pieces to create all the spans
1371 let pieces = unverified_pieces
1374 cx.verify_piece(&piece);
1375 cx.resolve_name_inplace(&mut piece);
1378 .collect::<Vec<_>>();
1380 let numbered_position_args = pieces.iter().any(|arg: &parse::Piece<'_>| match *arg {
1381 parse::String(_) => false,
1382 parse::NextArgument(arg) => matches!(arg.position, parse::Position::ArgumentIs(..)),
1385 cx.build_index_map();
1387 let mut arg_index_consumed = vec![0usize; cx.arg_index_map.len()];
1389 for piece in pieces {
1390 if let Some(piece) = cx.build_piece(&piece, &mut arg_index_consumed) {
1391 let s = cx.build_literal_string();
1392 cx.str_pieces.push(s);
1393 cx.pieces.push(piece);
1397 if !cx.literal.is_empty() {
1398 let s = cx.build_literal_string();
1399 cx.str_pieces.push(s);
1402 if !cx.invalid_refs.is_empty() {
1403 cx.report_invalid_references(numbered_position_args);
1406 // Make sure that all arguments were used and all arguments have types.
1411 .filter(|(i, ty)| ty.is_empty() && !cx.count_positions.contains_key(&i))
1413 let msg = if named_pos.contains(&i) {
1415 "named argument never used"
1417 // positional argument
1418 "argument never used"
1420 (cx.args[i].span, msg)
1422 .collect::<Vec<_>>();
1424 let errs_len = errs.len();
1425 if !errs.is_empty() {
1426 let args_used = cx.arg_types.len() - errs_len;
1427 let args_unused = errs_len;
1430 if let [(sp, msg)] = &errs[..] {
1431 let mut diag = cx.ecx.struct_span_err(*sp, *msg);
1432 diag.span_label(*sp, *msg);
1435 let mut diag = cx.ecx.struct_span_err(
1436 errs.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
1437 "multiple unused formatting arguments",
1439 diag.span_label(cx.fmtsp, "multiple missing formatting specifiers");
1440 for (sp, msg) in errs {
1441 diag.span_label(sp, msg);
1447 // Used to ensure we only report translations for *one* kind of foreign format.
1448 let mut found_foreign = false;
1449 // Decide if we want to look for foreign formatting directives.
1450 if args_used < args_unused {
1451 use super::format_foreign as foreign;
1453 // The set of foreign substitutions we've explained. This prevents spamming the user
1454 // with `%d should be written as {}` over and over again.
1455 let mut explained = FxHashSet::default();
1457 macro_rules! check_foreign {
1459 let mut show_doc_note = false;
1461 let mut suggestions = vec![];
1462 // account for `"` and account for raw strings `r#`
1463 let padding = str_style.map(|i| i + 2).unwrap_or(1);
1464 for sub in foreign::$kind::iter_subs(fmt_str, padding) {
1465 let (trn, success) = match sub.translate() {
1466 Ok(trn) => (trn, true),
1467 Err(Some(msg)) => (msg, false),
1469 // If it has no translation, don't call it out specifically.
1473 let pos = sub.position();
1474 let sub = String::from(sub.as_str());
1475 if explained.contains(&sub) {
1478 explained.insert(sub.clone());
1481 found_foreign = true;
1482 show_doc_note = true;
1485 if let Some(inner_sp) = pos {
1486 let sp = fmt_sp.from_inner(inner_sp);
1489 suggestions.push((sp, trn));
1493 &format!("format specifiers use curly braces, and {}", trn),
1498 diag.help(&format!("`{}` should be written as `{}`", sub, trn));
1501 "`{}` should use curly braces, and {}",
1511 " formatting not supported; see the documentation for `std::fmt`",
1514 if suggestions.len() > 0 {
1515 diag.multipart_suggestion(
1516 "format specifiers use curly braces",
1518 Applicability::MachineApplicable,
1524 check_foreign!(printf);
1526 check_foreign!(shell);
1529 if !found_foreign && errs_len == 1 {
1530 diag.span_label(cx.fmtsp, "formatting specifier missing");
1534 } else if cx.invalid_refs.is_empty() && cx.ecx.sess.err_count() == 0 {
1535 // Only check for unused named argument names if there are no other errors to avoid causing
1536 // too much noise in output errors, such as when a named argument is entirely unused.
1537 create_lints_for_named_arguments_used_positionally(&mut cx);
1543 fn may_contain_yield_point(e: &ast::Expr) -> bool {
1544 struct MayContainYieldPoint(bool);
1546 impl Visitor<'_> for MayContainYieldPoint {
1547 fn visit_expr(&mut self, e: &ast::Expr) {
1548 if let ast::ExprKind::Await(_) | ast::ExprKind::Yield(_) = e.kind {
1551 visit::walk_expr(self, e);
1555 fn visit_mac_call(&mut self, _: &ast::MacCall) {
1559 fn visit_attribute(&mut self, _: &ast::Attribute) {
1560 // Conservatively assume this may be a proc macro attribute in
1561 // expression position.
1565 fn visit_item(&mut self, _: &ast::Item) {
1566 // Do not recurse into nested items.
1570 let mut visitor = MayContainYieldPoint(false);
1571 visitor.visit_expr(e);