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 /// Parses the arguments from the given list of tokens, returning the diagnostic
284 /// if there's a parse error so we can continue parsing other format!
287 /// If parsing succeeds, the return value is:
290 /// Some((fmtstr, parsed arguments, index map for named arguments))
293 ecx: &mut ExtCtxt<'a>,
296 ) -> PResult<'a, (P<ast::Expr>, Vec<P<ast::Expr>>, FxHashMap<Symbol, (usize, Span)>)> {
297 let mut args = Vec::<P<ast::Expr>>::new();
298 let mut names = FxHashMap::<Symbol, (usize, Span)>::default();
300 let mut p = ecx.new_parser_from_tts(tts);
302 if p.token == token::Eof {
303 return Err(ecx.struct_span_err(sp, "requires at least a format string argument"));
306 let first_token = &p.token;
307 let fmtstr = match first_token.kind {
308 token::TokenKind::Literal(token::Lit {
309 kind: token::LitKind::Str | token::LitKind::StrRaw(_),
312 // If the first token is a string literal, then a format expression
313 // is constructed from it.
315 // This allows us to properly handle cases when the first comma
316 // after the format string is mistakenly replaced with any operator,
317 // which cause the expression parser to eat too much tokens.
318 p.parse_literal_maybe_minus()?
321 // Otherwise, we fall back to the expression parser.
326 let mut first = true;
327 let mut named = false;
329 while p.token != token::Eof {
330 if !p.eat(&token::Comma) {
332 p.clear_expected_tokens();
335 match p.expect(&token::Comma) {
337 match token::TokenKind::Comma.similar_tokens() {
338 Some(tks) if tks.contains(&p.token.kind) => {
339 // If a similar token is found, then it may be a typo. We
340 // consider it as a comma, and continue parsing.
344 // Otherwise stop the parsing and return the error.
345 _ => return Err(err),
354 if p.token == token::Eof {
356 } // accept trailing commas
357 match p.token.ident() {
358 Some((ident, _)) if p.look_ahead(1, |t| *t == token::Eq) => {
361 p.expect(&token::Eq)?;
362 let e = p.parse_expr()?;
363 if let Some((prev, _)) = names.get(&ident.name) {
364 ecx.struct_span_err(e.span, &format!("duplicate argument named `{}`", ident))
365 .span_label(args[*prev].span, "previously here")
366 .span_label(e.span, "duplicate argument")
371 // Resolve names into slots early.
372 // Since all the positional args are already seen at this point
373 // if the input is valid, we can simply append to the positional
374 // args. And remember the names.
375 let slot = args.len();
376 names.insert(ident.name, (slot, ident.span));
380 let e = p.parse_expr()?;
382 let mut err = ecx.struct_span_err(
384 "positional arguments cannot follow named arguments",
386 err.span_label(e.span, "positional arguments must be before named arguments");
387 for pos in names.values() {
388 err.span_label(args[pos.0].span, "named argument");
396 Ok((fmtstr, args, names))
399 impl<'a, 'b> Context<'a, 'b> {
400 /// The number of arguments that were explicitly given.
401 fn num_args(&self) -> usize {
402 self.args.len() - self.num_captured_args
405 fn resolve_name_inplace(&mut self, p: &mut parse::Piece<'_>) {
406 // NOTE: the `unwrap_or` branch is needed in case of invalid format
407 // arguments, e.g., `format_args!("{foo}")`.
409 |s: &str| self.names.get(&Symbol::intern(s)).unwrap_or(&(0, Span::default())).0;
412 parse::String(_) => {}
413 parse::NextArgument(ref mut arg) => {
414 if let parse::ArgumentNamed(s) = arg.position {
415 arg.position = parse::ArgumentIs(lookup(s));
417 if let parse::CountIsName(s, _) = arg.format.width {
418 arg.format.width = parse::CountIsParam(lookup(s));
420 if let parse::CountIsName(s, _) = arg.format.precision {
421 arg.format.precision = parse::CountIsParam(lookup(s));
427 /// Verifies one piece of a parse string, and remembers it if valid.
428 /// All errors are not emitted as fatal so we can continue giving errors
429 /// about this and possibly other format strings.
430 fn verify_piece(&mut self, p: &parse::Piece<'_>) {
432 parse::String(..) => {}
433 parse::NextArgument(ref arg) => {
434 // width/precision first, if they have implicit positional
435 // parameters it makes more sense to consume them first.
438 &arg.format.width_span,
439 PositionalNamedArgType::Width,
442 arg.format.precision,
443 &arg.format.precision_span,
444 PositionalNamedArgType::Precision,
447 let has_precision = arg.format.precision != Count::CountImplied;
448 let has_width = arg.format.width != Count::CountImplied;
450 // argument second, if it's an implicit positional parameter
451 // it's written second, so it should come after width/precision.
452 let pos = match arg.position {
453 parse::ArgumentIs(i) => {
454 self.unused_names_lint.maybe_add_positional_named_arg(
458 PositionalNamedArgType::Arg,
460 Some(arg.position_span),
462 has_precision || has_width,
467 parse::ArgumentImplicitlyIs(i) => {
468 self.unused_names_lint.maybe_add_positional_named_arg(
472 PositionalNamedArgType::Arg,
476 has_precision || has_width,
480 parse::ArgumentNamed(s) => {
481 let symbol = Symbol::intern(s);
482 let span = arg.position_span;
483 Named(symbol, InnerSpan::new(span.start, span.end))
487 let ty = Placeholder(match arg.format.ty {
498 let fmtsp = self.fmtsp;
502 .map(|sp| fmtsp.from_inner(InnerSpan::new(sp.start, sp.end)));
503 let mut err = self.ecx.struct_span_err(
505 &format!("unknown format trait `{}`", arg.format.ty),
508 "the only appropriate formatting traits are:\n\
509 - ``, which uses the `Display` trait\n\
510 - `?`, which uses the `Debug` trait\n\
511 - `e`, which uses the `LowerExp` trait\n\
512 - `E`, which uses the `UpperExp` trait\n\
513 - `o`, which uses the `Octal` trait\n\
514 - `p`, which uses the `Pointer` trait\n\
515 - `b`, which uses the `Binary` trait\n\
516 - `x`, which uses the `LowerHex` trait\n\
517 - `X`, which uses the `UpperHex` trait",
519 if let Some(sp) = sp {
520 for (fmt, name) in &[
531 // FIXME: rustfix (`run-rustfix`) fails to apply suggestions.
532 // > "Cannot replace slice of data that was already replaced"
533 err.tool_only_span_suggestion(
535 &format!("use the `{}` trait", name),
537 Applicability::MaybeIncorrect,
545 self.verify_arg_type(pos, ty);
554 inner_span: &Option<rustc_parse_format::InnerSpan>,
555 named_arg_type: PositionalNamedArgType,
558 parse::CountImplied | parse::CountIs(..) => {}
559 parse::CountIsParam(i) => {
560 self.unused_names_lint.maybe_add_positional_named_arg(
570 self.verify_arg_type(Exact(i), Count);
572 parse::CountIsName(s, span) => {
573 self.verify_arg_type(
574 Named(Symbol::intern(s), InnerSpan::new(span.start, span.end)),
581 fn describe_num_args(&self) -> Cow<'_, str> {
582 match self.num_args() {
583 0 => "no arguments were given".into(),
584 1 => "there is 1 argument".into(),
585 x => format!("there are {} arguments", x).into(),
589 /// Handle invalid references to positional arguments. Output different
590 /// errors for the case where all arguments are positional and for when
591 /// there are named arguments or numbered positional arguments in the
593 fn report_invalid_references(&self, numbered_position_args: bool) {
595 let sp = if !self.arg_spans.is_empty() {
596 // Point at the formatting arguments.
597 MultiSpan::from_spans(self.arg_spans.clone())
599 MultiSpan::from_span(self.fmtsp)
602 self.invalid_refs.iter().map(|(r, pos)| (r.to_string(), self.arg_spans.get(*pos)));
604 let mut zero_based_note = false;
606 let count = self.pieces.len()
607 + self.arg_with_formatting.iter().filter(|fmt| fmt.precision_span.is_some()).count();
608 if self.names.is_empty() && !numbered_position_args && count != self.num_args() {
609 e = self.ecx.struct_span_err(
612 "{} positional argument{} in format string, but {}",
615 self.describe_num_args(),
618 for arg in &self.args {
619 // Point at the arguments that will be formatted.
620 e.span_label(arg.span, "");
623 let (mut refs, spans): (Vec<_>, Vec<_>) = refs.unzip();
624 // Avoid `invalid reference to positional arguments 7 and 7 (there is 1 argument)`
625 // for `println!("{7:7$}", 1);`
628 let spans: Vec<_> = spans.into_iter().filter_map(|sp| sp.copied()).collect();
629 let sp = if self.arg_spans.is_empty() || spans.is_empty() {
630 MultiSpan::from_span(self.fmtsp)
632 MultiSpan::from_spans(spans)
634 let arg_list = if refs.len() == 1 {
635 format!("argument {}", refs[0])
637 let reg = refs.pop().unwrap();
638 format!("arguments {head} and {tail}", head = refs.join(", "), tail = reg)
641 e = self.ecx.struct_span_err(
644 "invalid reference to positional {} ({})",
646 self.describe_num_args()
649 zero_based_note = true;
652 for fmt in &self.arg_with_formatting {
653 if let Some(span) = fmt.precision_span {
654 let span = self.fmtsp.from_inner(InnerSpan::new(span.start, span.end));
655 match fmt.precision {
656 parse::CountIsParam(pos) if pos > self.num_args() => {
660 "this precision flag expects an `usize` argument at position {}, \
663 self.describe_num_args(),
666 zero_based_note = true;
668 parse::CountIsParam(pos) => {
669 let count = self.pieces.len()
673 .filter(|fmt| fmt.precision_span.is_some())
678 "this precision flag adds an extra required argument at position {}, \
679 which is why there {} expected",
682 "is 1 argument".to_string()
684 format!("are {} arguments", count)
688 if let Some(arg) = self.args.get(pos) {
691 "this parameter corresponds to the precision flag",
694 zero_based_note = true;
699 if let Some(span) = fmt.width_span {
700 let span = self.fmtsp.from_inner(InnerSpan::new(span.start, span.end));
702 parse::CountIsParam(pos) if pos >= self.num_args() => {
706 "this width flag expects an `usize` argument at position {}, \
709 self.describe_num_args(),
712 zero_based_note = true;
719 e.note("positional arguments are zero-based");
721 if !self.arg_with_formatting.is_empty() {
723 "for information about formatting flags, visit \
724 https://doc.rust-lang.org/std/fmt/index.html",
731 /// Actually verifies and tracks a given format placeholder
732 /// (a.k.a. argument).
733 fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
734 if let Exact(arg) = arg {
735 if arg >= self.num_args() {
736 self.invalid_refs.push((arg, self.curpiece));
742 Exact(arg) | Capture(arg) => {
745 // record every (position, type) combination only once
746 let seen_ty = &mut self.arg_unique_types[arg];
747 let i = seen_ty.iter().position(|x| *x == ty).unwrap_or_else(|| {
748 let i = seen_ty.len();
752 self.arg_types[arg].push(i);
755 if let Entry::Vacant(e) = self.count_positions.entry(arg) {
756 let i = self.count_positions_count;
758 self.count_args.push(arg);
759 self.count_positions_count += 1;
765 Named(name, span) => {
766 match self.names.get(&name) {
768 // Treat as positional arg.
769 self.verify_arg_type(Capture(idx.0), ty)
772 // For the moment capturing variables from format strings expanded from macros is
773 // disabled (see RFC #2795)
775 // Treat this name as a variable to capture from the surrounding scope
776 let idx = self.args.len();
777 self.arg_types.push(Vec::new());
778 self.arg_unique_types.push(Vec::new());
779 let span = if self.is_literal {
780 self.fmtsp.from_inner(span)
784 self.num_captured_args += 1;
785 self.args.push(self.ecx.expr_ident(span, Ident::new(name, span)));
786 self.names.insert(name, (idx, span));
787 self.verify_arg_type(Capture(idx), ty)
789 let msg = format!("there is no argument named `{}`", name);
790 let sp = if self.is_literal {
791 self.fmtsp.from_inner(span)
795 let mut err = self.ecx.struct_span_err(sp, &msg);
798 "did you intend to capture a variable `{}` from \
799 the surrounding scope?",
803 "to avoid ambiguity, `format_args!` cannot capture variables \
804 when the format string is expanded from a macro",
815 /// Builds the mapping between format placeholders and argument objects.
816 fn build_index_map(&mut self) {
817 // NOTE: Keep the ordering the same as `into_expr`'s expansion would do!
818 let args_len = self.args.len();
819 self.arg_index_map.reserve(args_len);
821 let mut sofar = 0usize;
824 for i in 0..args_len {
825 let arg_types = &self.arg_types[i];
826 let arg_offsets = arg_types.iter().map(|offset| sofar + *offset).collect::<Vec<_>>();
827 self.arg_index_map.push(arg_offsets);
828 sofar += self.arg_unique_types[i].len();
831 // Record starting index for counts, which appear just after arguments
832 self.count_args_index_offset = sofar;
835 fn rtpath(ecx: &ExtCtxt<'_>, s: Symbol) -> Vec<Ident> {
836 ecx.std_path(&[sym::fmt, sym::rt, sym::v1, s])
839 fn build_count(&self, c: parse::Count<'_>) -> P<ast::Expr> {
841 let count = |c, arg| {
842 let mut path = Context::rtpath(self.ecx, sym::Count);
843 path.push(Ident::new(c, sp));
845 Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]),
846 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
850 parse::CountIs(i) => count(sym::Is, Some(self.ecx.expr_usize(sp, i))),
851 parse::CountIsParam(i) => {
852 // This needs mapping too, as `i` is referring to a macro
853 // argument. If `i` is not found in `count_positions` then
854 // the error had already been emitted elsewhere.
855 let i = self.count_positions.get(&i).cloned().unwrap_or(0)
856 + self.count_args_index_offset;
857 count(sym::Param, Some(self.ecx.expr_usize(sp, i)))
859 parse::CountImplied => count(sym::Implied, None),
860 // should never be the case, names are already resolved
861 parse::CountIsName(..) => panic!("should never happen"),
865 /// Build a literal expression from the accumulated string literals
866 fn build_literal_string(&mut self) -> P<ast::Expr> {
868 let s = Symbol::intern(&self.literal);
869 self.literal.clear();
870 self.ecx.expr_str(sp, s)
873 /// Builds a static `rt::Argument` from a `parse::Piece` or append
874 /// to the `literal` string.
877 piece: &parse::Piece<'a>,
878 arg_index_consumed: &mut Vec<usize>,
879 ) -> Option<P<ast::Expr>> {
882 parse::String(s) => {
883 self.literal.push_str(s);
886 parse::NextArgument(ref arg) => {
887 // Build the position
890 parse::ArgumentIs(i, ..) | parse::ArgumentImplicitlyIs(i) => {
891 // Map to index in final generated argument array
892 // in case of multiple types specified
893 let arg_idx = match arg_index_consumed.get_mut(i) {
894 None => 0, // error already emitted elsewhere
896 let idx_map = &self.arg_index_map[i];
897 // unwrap_or branch: error already emitted elsewhere
898 let arg_idx = *idx_map.get(*offset).unwrap_or(&0);
903 self.ecx.expr_usize(sp, arg_idx)
906 // should never be the case, because names are already
908 parse::ArgumentNamed(..) => panic!("should never happen"),
912 let simple_arg = parse::Argument {
914 // We don't have ArgumentNext any more, so we have to
915 // track the current argument ourselves.
920 position_span: arg.position_span,
921 format: parse::FormatSpec {
922 fill: arg.format.fill,
923 align: parse::AlignUnknown,
925 precision: parse::CountImplied,
926 precision_span: None,
927 width: parse::CountImplied,
930 ty_span: arg.format.ty_span,
934 let fill = arg.format.fill.unwrap_or(' ');
936 let pos_simple = arg.position.index() == simple_arg.position.index();
938 if arg.format.precision_span.is_some() || arg.format.width_span.is_some() {
939 self.arg_with_formatting.push(arg.format);
941 if !pos_simple || arg.format != simple_arg.format || fill != ' ' {
942 self.all_pieces_simple = false;
946 let fill = self.ecx.expr_lit(sp, ast::LitKind::Char(fill));
948 let mut p = Context::rtpath(self.ecx, sym::Alignment);
949 p.push(Ident::new(name, sp));
950 self.ecx.path_global(sp, p)
952 let align = match arg.format.align {
953 parse::AlignLeft => align(sym::Left),
954 parse::AlignRight => align(sym::Right),
955 parse::AlignCenter => align(sym::Center),
956 parse::AlignUnknown => align(sym::Unknown),
958 let align = self.ecx.expr_path(align);
959 let flags = self.ecx.expr_u32(sp, arg.format.flags);
960 let prec = self.build_count(arg.format.precision);
961 let width = self.build_count(arg.format.width);
962 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, sym::FormatSpec));
963 let fmt = self.ecx.expr_struct(
967 self.ecx.field_imm(sp, Ident::new(sym::fill, sp), fill),
968 self.ecx.field_imm(sp, Ident::new(sym::align, sp), align),
969 self.ecx.field_imm(sp, Ident::new(sym::flags, sp), flags),
970 self.ecx.field_imm(sp, Ident::new(sym::precision, sp), prec),
971 self.ecx.field_imm(sp, Ident::new(sym::width, sp), width),
975 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, sym::Argument));
976 Some(self.ecx.expr_struct(
980 self.ecx.field_imm(sp, Ident::new(sym::position, sp), pos),
981 self.ecx.field_imm(sp, Ident::new(sym::format, sp), fmt),
988 /// Actually builds the expression which the format_args! block will be
990 fn into_expr(self) -> P<ast::Expr> {
991 let mut original_args = self.args;
992 let mut fmt_args = Vec::with_capacity(
993 self.arg_unique_types.iter().map(|v| v.len()).sum::<usize>() + self.count_args.len(),
996 // First, build up the static array which will become our precompiled
998 let pieces = self.ecx.expr_array_ref(self.fmtsp, self.str_pieces);
1000 // We need to construct a &[ArgumentV1] to pass into the fmt::Arguments
1001 // constructor. In general the expressions in this slice might be
1002 // permuted from their order in original_args (such as in the case of
1003 // "{1} {0}"), or may have multiple entries referring to the same
1004 // element of original_args ("{0} {0}").
1006 // The following vector has one item per element of our output slice,
1007 // identifying the index of which element of original_args it's passing,
1008 // and that argument's type.
1009 let mut fmt_arg_index_and_ty = SmallVec::<[(usize, &ArgumentType); 8]>::new();
1010 for (i, unique_types) in self.arg_unique_types.iter().enumerate() {
1011 fmt_arg_index_and_ty.extend(unique_types.iter().map(|ty| (i, ty)));
1013 fmt_arg_index_and_ty.extend(self.count_args.iter().map(|&i| (i, &Count)));
1015 // Figure out whether there are permuted or repeated elements. If not,
1016 // we can generate simpler code.
1018 // The sequence has no indices out of order or repeated if: for every
1019 // adjacent pair of elements, the first one's index is less than the
1020 // second one's index.
1021 let nicely_ordered =
1022 fmt_arg_index_and_ty.array_windows().all(|[(i, _i_ty), (j, _j_ty)]| i < j);
1026 // [ArgumentV1::new(&$arg0, …), ArgumentV1::new(&$arg1, …), …]
1028 // However, it's only legal to do so if $arg0, $arg1, … were written in
1029 // exactly that order by the programmer. When arguments are permuted, we
1030 // want them evaluated in the order written by the programmer, not in
1031 // the order provided to fmt::Arguments. When arguments are repeated, we
1032 // want the expression evaluated only once.
1034 // Further, if any arg _after the first one_ contains a yield point such
1035 // as `await` or `yield`, the above short form is inconvenient for the
1036 // caller because it would keep a temporary of type ArgumentV1 alive
1037 // across the yield point. ArgumentV1 can't implement Send since it
1038 // holds a type-erased arbitrary type.
1040 // Thus in the not nicely ordered case, and in the yielding case, we
1041 // emit the following instead:
1043 // match (&$arg0, &$arg1, …) {
1044 // args => [ArgumentV1::new(args.$i, …), ArgumentV1::new(args.$j, …), …]
1047 // for the sequence of indices $i, $j, … governed by fmt_arg_index_and_ty.
1048 // This more verbose representation ensures that all arguments are
1049 // evaluated a single time each, in the order written by the programmer,
1050 // and that the surrounding future/generator (if any) is Send whenever
1052 let no_need_for_match =
1053 nicely_ordered && !original_args.iter().skip(1).any(|e| may_contain_yield_point(e));
1055 for (arg_index, arg_ty) in fmt_arg_index_and_ty {
1056 let e = &mut original_args[arg_index];
1058 let arg = if no_need_for_match {
1059 let expansion_span = e.span.with_ctxt(self.macsp.ctxt());
1060 // The indices are strictly ordered so e has not been taken yet.
1061 self.ecx.expr_addr_of(expansion_span, P(e.take()))
1063 let def_site = self.ecx.with_def_site_ctxt(span);
1064 let args_tuple = self.ecx.expr_ident(def_site, Ident::new(sym::args, def_site));
1065 let member = Ident::new(sym::integer(arg_index), def_site);
1066 self.ecx.expr(def_site, ast::ExprKind::Field(args_tuple, member))
1068 fmt_args.push(Context::format_arg(self.ecx, self.macsp, span, arg_ty, arg));
1071 let args_array = self.ecx.expr_array(self.macsp, fmt_args);
1072 let args_slice = self.ecx.expr_addr_of(
1074 if no_need_for_match {
1077 // In the !no_need_for_match case, none of the exprs were moved
1078 // away in the previous loop.
1080 // This uses the arg span for `&arg` so that borrowck errors
1081 // point to the specific expression passed to the macro (the
1082 // span is otherwise unavailable in the MIR used by borrowck).
1083 let heads = original_args
1085 .map(|e| self.ecx.expr_addr_of(e.span.with_ctxt(self.macsp.ctxt()), e))
1088 let pat = self.ecx.pat_ident(self.macsp, Ident::new(sym::args, self.macsp));
1089 let arm = self.ecx.arm(self.macsp, pat, args_array);
1090 let head = self.ecx.expr(self.macsp, ast::ExprKind::Tup(heads));
1091 self.ecx.expr_match(self.macsp, head, vec![arm])
1095 // Now create the fmt::Arguments struct with all our locals we created.
1096 let (fn_name, fn_args) = if self.all_pieces_simple {
1097 ("new_v1", vec![pieces, args_slice])
1099 // Build up the static array which will store our precompiled
1100 // nonstandard placeholders, if there are any.
1101 let fmt = self.ecx.expr_array_ref(self.macsp, self.pieces);
1103 let path = self.ecx.std_path(&[sym::fmt, sym::UnsafeArg, sym::new]);
1104 let unsafe_arg = self.ecx.expr_call_global(self.macsp, path, Vec::new());
1105 let unsafe_expr = self.ecx.expr_block(P(ast::Block {
1106 stmts: vec![self.ecx.stmt_expr(unsafe_arg)],
1107 id: ast::DUMMY_NODE_ID,
1108 rules: BlockCheckMode::Unsafe(UnsafeSource::CompilerGenerated),
1111 could_be_bare_literal: false,
1114 ("new_v1_formatted", vec![pieces, args_slice, fmt, unsafe_expr])
1117 let path = self.ecx.std_path(&[sym::fmt, sym::Arguments, Symbol::intern(fn_name)]);
1118 self.ecx.expr_call_global(self.macsp, path, fn_args)
1128 sp = ecx.with_def_site_ctxt(sp);
1129 let trait_ = match *ty {
1130 Placeholder(trait_) if trait_ == "<invalid>" => return DummyResult::raw_expr(sp, true),
1131 Placeholder(trait_) => trait_,
1133 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, sym::from_usize]);
1134 return ecx.expr_call_global(macsp, path, vec![arg]);
1137 let new_fn_name = match trait_ {
1138 "Display" => "new_display",
1139 "Debug" => "new_debug",
1140 "LowerExp" => "new_lower_exp",
1141 "UpperExp" => "new_upper_exp",
1142 "Octal" => "new_octal",
1143 "Pointer" => "new_pointer",
1144 "Binary" => "new_binary",
1145 "LowerHex" => "new_lower_hex",
1146 "UpperHex" => "new_upper_hex",
1147 _ => unreachable!(),
1150 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, Symbol::intern(new_fn_name)]);
1151 ecx.expr_call_global(sp, path, vec![arg])
1155 fn expand_format_args_impl<'cx>(
1156 ecx: &'cx mut ExtCtxt<'_>,
1160 ) -> Box<dyn base::MacResult + 'cx> {
1161 sp = ecx.with_def_site_ctxt(sp);
1162 match parse_args(ecx, sp, tts) {
1163 Ok((efmt, args, names)) => {
1164 MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt, args, names, nl))
1168 DummyResult::any(sp)
1173 pub fn expand_format_args<'cx>(
1174 ecx: &'cx mut ExtCtxt<'_>,
1177 ) -> Box<dyn base::MacResult + 'cx> {
1178 expand_format_args_impl(ecx, sp, tts, false)
1181 pub fn expand_format_args_nl<'cx>(
1182 ecx: &'cx mut ExtCtxt<'_>,
1185 ) -> Box<dyn base::MacResult + 'cx> {
1186 expand_format_args_impl(ecx, sp, tts, true)
1189 fn create_lints_for_named_arguments_used_positionally(cx: &mut Context<'_, '_>) {
1190 for named_arg in &cx.unused_names_lint.positional_named_args {
1191 let (position_sp_to_replace, position_sp_for_msg) = named_arg.get_positional_arg_spans(cx);
1193 let msg = format!("named argument `{}` is not used by name", named_arg.replacement);
1195 cx.ecx.buffered_early_lint.push(BufferedEarlyLint {
1196 span: MultiSpan::from_span(named_arg.positional_named_arg_span),
1198 node_id: ast::CRATE_NODE_ID,
1199 lint_id: LintId::of(&NAMED_ARGUMENTS_USED_POSITIONALLY),
1200 diagnostic: BuiltinLintDiagnostics::NamedArgumentUsedPositionally {
1201 position_sp_to_replace,
1202 position_sp_for_msg,
1203 named_arg_sp: named_arg.positional_named_arg_span,
1204 named_arg_name: named_arg.replacement.to_string(),
1205 is_formatting_arg: named_arg.ty != PositionalNamedArgType::Arg,
1211 /// Take the various parts of `format_args!(efmt, args..., name=names...)`
1212 /// and construct the appropriate formatting expression.
1213 pub fn expand_preparsed_format_args(
1214 ecx: &mut ExtCtxt<'_>,
1217 args: Vec<P<ast::Expr>>,
1218 names: FxHashMap<Symbol, (usize, Span)>,
1219 append_newline: bool,
1221 // NOTE: this verbose way of initializing `Vec<Vec<ArgumentType>>` is because
1222 // `ArgumentType` does not derive `Clone`.
1223 let arg_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
1224 let arg_unique_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
1226 let mut macsp = ecx.call_site();
1227 macsp = ecx.with_def_site_ctxt(macsp);
1229 let msg = "format argument must be a string literal";
1230 let fmt_sp = efmt.span;
1231 let efmt_kind_is_lit: bool = matches!(efmt.kind, ast::ExprKind::Lit(_));
1232 let (fmt_str, fmt_style, fmt_span) = match expr_to_spanned_string(ecx, efmt, msg) {
1233 Ok(mut fmt) if append_newline => {
1234 fmt.0 = Symbol::intern(&format!("{}\n", fmt.0));
1239 if let Some((mut err, suggested)) = err {
1240 let sugg_fmt = match args.len() {
1241 0 => "{}".to_string(),
1242 _ => format!("{}{{}}", "{} ".repeat(args.len())),
1245 err.span_suggestion(
1246 fmt_sp.shrink_to_lo(),
1247 "you might be missing a string literal to format with",
1248 format!("\"{}\", ", sugg_fmt),
1249 Applicability::MaybeIncorrect,
1254 return DummyResult::raw_expr(sp, true);
1258 let str_style = match fmt_style {
1259 ast::StrStyle::Cooked => None,
1260 ast::StrStyle::Raw(raw) => Some(raw as usize),
1263 let fmt_str = fmt_str.as_str(); // for the suggestions below
1264 let fmt_snippet = ecx.source_map().span_to_snippet(fmt_sp).ok();
1265 let mut parser = parse::Parser::new(
1270 parse::ParseMode::Format,
1273 let mut unverified_pieces = Vec::new();
1274 while let Some(piece) = parser.next() {
1275 if !parser.errors.is_empty() {
1278 unverified_pieces.push(piece);
1282 if !parser.errors.is_empty() {
1283 let err = parser.errors.remove(0);
1284 let sp = if efmt_kind_is_lit {
1285 fmt_span.from_inner(InnerSpan::new(err.span.start, err.span.end))
1287 // The format string could be another macro invocation, e.g.:
1288 // format!(concat!("abc", "{}"), 4);
1289 // However, `err.span` is an inner span relative to the *result* of
1290 // the macro invocation, which is why we would get a nonsensical
1291 // result calling `fmt_span.from_inner(err.span)` as above, and
1292 // might even end up inside a multibyte character (issue #86085).
1293 // Therefore, we conservatively report the error for the entire
1294 // argument span here.
1297 let mut e = ecx.struct_span_err(sp, &format!("invalid format string: {}", err.description));
1298 e.span_label(sp, err.label + " in format string");
1299 if let Some(note) = err.note {
1302 if let Some((label, span)) = err.secondary_label {
1303 if efmt_kind_is_lit {
1304 e.span_label(fmt_span.from_inner(InnerSpan::new(span.start, span.end)), label);
1308 return DummyResult::raw_expr(sp, true);
1311 let arg_spans = parser
1314 .map(|span| fmt_span.from_inner(InnerSpan::new(span.start, span.end)))
1317 let named_pos: FxHashSet<usize> = names.values().cloned().map(|(i, _)| i).collect();
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 named_pos.contains(&i) {
1391 "named argument never used"
1393 // positional argument
1394 "argument never used"
1396 (cx.args[i].span, msg)
1398 .collect::<Vec<_>>();
1400 let errs_len = errs.len();
1401 if !errs.is_empty() {
1402 let args_used = cx.arg_types.len() - errs_len;
1403 let args_unused = errs_len;
1406 if let [(sp, msg)] = &errs[..] {
1407 let mut diag = cx.ecx.struct_span_err(*sp, *msg);
1408 diag.span_label(*sp, *msg);
1411 let mut diag = cx.ecx.struct_span_err(
1412 errs.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
1413 "multiple unused formatting arguments",
1415 diag.span_label(cx.fmtsp, "multiple missing formatting specifiers");
1416 for (sp, msg) in errs {
1417 diag.span_label(sp, msg);
1423 // Used to ensure we only report translations for *one* kind of foreign format.
1424 let mut found_foreign = false;
1425 // Decide if we want to look for foreign formatting directives.
1426 if args_used < args_unused {
1427 use super::format_foreign as foreign;
1429 // The set of foreign substitutions we've explained. This prevents spamming the user
1430 // with `%d should be written as {}` over and over again.
1431 let mut explained = FxHashSet::default();
1433 macro_rules! check_foreign {
1435 let mut show_doc_note = false;
1437 let mut suggestions = vec![];
1438 // account for `"` and account for raw strings `r#`
1439 let padding = str_style.map(|i| i + 2).unwrap_or(1);
1440 for sub in foreign::$kind::iter_subs(fmt_str, padding) {
1441 let (trn, success) = match sub.translate() {
1442 Ok(trn) => (trn, true),
1443 Err(Some(msg)) => (msg, false),
1445 // If it has no translation, don't call it out specifically.
1449 let pos = sub.position();
1450 let sub = String::from(sub.as_str());
1451 if explained.contains(&sub) {
1454 explained.insert(sub.clone());
1457 found_foreign = true;
1458 show_doc_note = true;
1461 if let Some(inner_sp) = pos {
1462 let sp = fmt_sp.from_inner(inner_sp);
1465 suggestions.push((sp, trn));
1469 &format!("format specifiers use curly braces, and {}", trn),
1474 diag.help(&format!("`{}` should be written as `{}`", sub, trn));
1477 "`{}` should use curly braces, and {}",
1487 " formatting not supported; see the documentation for `std::fmt`",
1490 if suggestions.len() > 0 {
1491 diag.multipart_suggestion(
1492 "format specifiers use curly braces",
1494 Applicability::MachineApplicable,
1500 check_foreign!(printf);
1502 check_foreign!(shell);
1505 if !found_foreign && errs_len == 1 {
1506 diag.span_label(cx.fmtsp, "formatting specifier missing");
1510 } else if cx.invalid_refs.is_empty() && cx.ecx.sess.err_count() == 0 {
1511 // Only check for unused named argument names if there are no other errors to avoid causing
1512 // too much noise in output errors, such as when a named argument is entirely unused.
1513 create_lints_for_named_arguments_used_positionally(&mut cx);
1519 fn may_contain_yield_point(e: &ast::Expr) -> bool {
1520 struct MayContainYieldPoint(bool);
1522 impl Visitor<'_> for MayContainYieldPoint {
1523 fn visit_expr(&mut self, e: &ast::Expr) {
1524 if let ast::ExprKind::Await(_) | ast::ExprKind::Yield(_) = e.kind {
1527 visit::walk_expr(self, e);
1531 fn visit_mac_call(&mut self, _: &ast::MacCall) {
1535 fn visit_attribute(&mut self, _: &ast::Attribute) {
1536 // Conservatively assume this may be a proc macro attribute in
1537 // expression position.
1541 fn visit_item(&mut self, _: &ast::Item) {
1542 // Do not recurse into nested items.
1546 let mut visitor = MayContainYieldPoint(false);
1547 visitor.visit_expr(e);