]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_builtin_macros/src/format.rs
Rollup merge of #100026 - WaffleLapkin:array-chunks, r=scottmcm
[rust.git] / compiler / rustc_builtin_macros / src / format.rs
1 use ArgumentType::*;
2 use Position::*;
3
4 use rustc_ast as ast;
5 use rustc_ast::ptr::P;
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;
16
17 use rustc_lint_defs::builtin::NAMED_ARGUMENTS_USED_POSITIONALLY;
18 use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics, LintId};
19 use rustc_parse_format::Count;
20 use std::borrow::Cow;
21 use std::collections::hash_map::Entry;
22
23 #[derive(PartialEq)]
24 enum ArgumentType {
25     Placeholder(&'static str),
26     Count,
27 }
28
29 enum Position {
30     Exact(usize),
31     Capture(usize),
32     Named(Symbol, InnerSpan),
33 }
34
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 {
43     Arg,
44     Width,
45     Precision,
46 }
47
48 /// Contains information necessary to create a lint for a positional named argument
49 #[derive(Debug)]
50 struct PositionalNamedArg {
51     ty: PositionalNamedArgType,
52     /// The piece of the using this argument (multiple pieces can use the same argument)
53     cur_piece: usize,
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
58     replacement: Symbol,
59     /// The span for the positional named argument (so the lint can point a message to it)
60     positional_named_arg_span: Span,
61     has_formatting: bool,
62 }
63
64 impl PositionalNamedArg {
65     /// Determines:
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 {
70             let span =
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 {
86                     (
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))),
89                     )
90                 } else {
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))
95                 }
96             })
97         } else {
98             (None, None)
99         }
100     }
101 }
102
103 /// Encapsulates all the named arguments that have been used positionally
104 #[derive(Debug)]
105 struct PositionalNamedArgsLint {
106     positional_named_args: Vec<PositionalNamedArg>,
107 }
108
109 impl PositionalNamedArgsLint {
110     /// For a given positional argument, check if the index is for a named argument.
111     ///
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.
115     ///
116     /// Example:
117     /// println!("{} {} {2}", 0, a=1, b=2);
118     ///
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.
122     ///
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`.
125     ///
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`.
128     ///
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(
132         &mut self,
133         current_positional_arg: usize,
134         total_args_length: usize,
135         format_argument_index: usize,
136         ty: PositionalNamedArgType,
137         cur_piece: usize,
138         inner_span_to_replace: Option<rustc_parse_format::InnerSpan>,
139         names: &FxHashMap<Symbol, (usize, Span)>,
140         has_formatting: bool,
141     ) {
142         let start_of_named_args = total_args_length - names.len();
143         if current_positional_arg >= start_of_named_args {
144             self.maybe_push(
145                 format_argument_index,
146                 ty,
147                 cur_piece,
148                 inner_span_to_replace,
149                 names,
150                 has_formatting,
151             )
152         }
153     }
154
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.
158     fn maybe_push(
159         &mut self,
160         format_argument_index: usize,
161         ty: PositionalNamedArgType,
162         cur_piece: usize,
163         inner_span_to_replace: Option<rustc_parse_format::InnerSpan>,
164         names: &FxHashMap<Symbol, (usize, Span)>,
165         has_formatting: bool,
166     ) {
167         let named_arg = names
168             .iter()
169             .find(|&(_, &(index, _))| index == format_argument_index)
170             .map(|found| found.clone());
171
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
175             // `Precision`.
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 })
179             } else {
180                 inner_span_to_replace
181             };
182             self.positional_named_args.push(PositionalNamedArg {
183                 ty,
184                 cur_piece,
185                 inner_span_to_replace,
186                 replacement,
187                 positional_named_arg_span,
188                 has_formatting,
189             });
190         }
191     }
192 }
193
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.
198     macsp: Span,
199     /// The span of the format string literal.
200     fmtsp: Span,
201
202     /// List of parsed argument expressions.
203     /// Named expressions are resolved early, and are appended to the end of
204     /// argument expressions.
205     ///
206     /// Example showing the various data structures in motion:
207     ///
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)>,
223
224     /// The latest consecutive literal strings, or empty if there weren't any.
225     literal: String,
226
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,
233
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`.
240     ///
241     /// Again with the example described above in docstring for `args`:
242     ///
243     /// * `arg_index_map` (in JSON): `[[0, 1, 0], [2, 3, 3], [4, 5]]`
244     arg_index_map: Vec<Vec<usize>>,
245
246     /// Starting offset of count argument slots.
247     count_args_index_offset: usize,
248
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
252     /// format string:
253     ///
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,
264
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`.
268     curarg: usize,
269     /// Current piece being evaluated, used for error reporting.
270     curpiece: usize,
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>>,
277
278     /// Whether this format string came from a string literal, as opposed to a macro.
279     is_literal: bool,
280     unused_names_lint: PositionalNamedArgsLint,
281 }
282
283 pub struct FormatArg {
284     expr: P<ast::Expr>,
285     named: bool,
286 }
287
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!
290 /// expressions.
291 ///
292 /// If parsing succeeds, the return value is:
293 ///
294 /// ```text
295 /// Some((fmtstr, parsed arguments, index map for named arguments))
296 /// ```
297 fn parse_args<'a>(
298     ecx: &mut ExtCtxt<'a>,
299     sp: Span,
300     tts: TokenStream,
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();
304
305     let mut p = ecx.new_parser_from_tts(tts);
306
307     if p.token == token::Eof {
308         return Err(ecx.struct_span_err(sp, "requires at least a format string argument"));
309     }
310
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(_),
315             ..
316         }) => {
317             // If the first token is a string literal, then a format expression
318             // is constructed from it.
319             //
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()?
324         }
325         _ => {
326             // Otherwise, we fall back to the expression parser.
327             p.parse_expr()?
328         }
329     };
330
331     let mut first = true;
332     let mut named = false;
333
334     while p.token != token::Eof {
335         if !p.eat(&token::Comma) {
336             if first {
337                 p.clear_expected_tokens();
338             }
339
340             match p.expect(&token::Comma) {
341                 Err(mut err) => {
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.
346                             err.emit();
347                             p.bump();
348                         }
349                         // Otherwise stop the parsing and return the error.
350                         _ => return Err(err),
351                     }
352                 }
353                 Ok(recovered) => {
354                     assert!(recovered);
355                 }
356             }
357         }
358         first = false;
359         if p.token == token::Eof {
360             break;
361         } // accept trailing commas
362         match p.token.ident() {
363             Some((ident, _)) if p.look_ahead(1, |t| *t == token::Eq) => {
364                 named = true;
365                 p.bump();
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")
372                         .emit();
373                     continue;
374                 }
375
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 });
383             }
384             _ => {
385                 let e = p.parse_expr()?;
386                 if named {
387                     let mut err = ecx.struct_span_err(
388                         e.span,
389                         "positional arguments cannot follow named arguments",
390                     );
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");
394                     }
395                     err.emit();
396                 }
397                 args.push(FormatArg { expr: e, named: false });
398             }
399         }
400     }
401     Ok((fmtstr, args, names))
402 }
403
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
408     }
409
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}")`.
413         let lookup =
414             |s: &str| self.names.get(&Symbol::intern(s)).unwrap_or(&(0, Span::default())).0;
415
416         match *p {
417             parse::String(_) => {}
418             parse::NextArgument(ref mut arg) => {
419                 if let parse::ArgumentNamed(s) = arg.position {
420                     arg.position = parse::ArgumentIs(lookup(s));
421                 }
422                 if let parse::CountIsName(s, _) = arg.format.width {
423                     arg.format.width = parse::CountIsParam(lookup(s));
424                 }
425                 if let parse::CountIsName(s, _) = arg.format.precision {
426                     arg.format.precision = parse::CountIsParam(lookup(s));
427                 }
428             }
429         }
430     }
431
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<'_>) {
436         match *p {
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.
441                 self.verify_count(
442                     arg.format.width,
443                     &arg.format.width_span,
444                     PositionalNamedArgType::Width,
445                 );
446                 self.verify_count(
447                     arg.format.precision,
448                     &arg.format.precision_span,
449                     PositionalNamedArgType::Precision,
450                 );
451
452                 let has_precision = arg.format.precision != Count::CountImplied;
453                 let has_width = arg.format.width != Count::CountImplied;
454
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(
460                             i,
461                             self.args.len(),
462                             i,
463                             PositionalNamedArgType::Arg,
464                             self.curpiece,
465                             Some(arg.position_span),
466                             &self.names,
467                             has_precision || has_width,
468                         );
469
470                         Exact(i)
471                     }
472                     parse::ArgumentImplicitlyIs(i) => {
473                         self.unused_names_lint.maybe_add_positional_named_arg(
474                             i,
475                             self.args.len(),
476                             i,
477                             PositionalNamedArgType::Arg,
478                             self.curpiece,
479                             None,
480                             &self.names,
481                             has_precision || has_width,
482                         );
483                         Exact(i)
484                     }
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))
489                     }
490                 };
491
492                 let ty = Placeholder(match arg.format.ty {
493                     "" => "Display",
494                     "?" => "Debug",
495                     "e" => "LowerExp",
496                     "E" => "UpperExp",
497                     "o" => "Octal",
498                     "p" => "Pointer",
499                     "b" => "Binary",
500                     "x" => "LowerHex",
501                     "X" => "UpperHex",
502                     _ => {
503                         let fmtsp = self.fmtsp;
504                         let sp = arg
505                             .format
506                             .ty_span
507                             .map(|sp| fmtsp.from_inner(InnerSpan::new(sp.start, sp.end)));
508                         let mut err = self.ecx.struct_span_err(
509                             sp.unwrap_or(fmtsp),
510                             &format!("unknown format trait `{}`", arg.format.ty),
511                         );
512                         err.note(
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",
523                         );
524                         if let Some(sp) = sp {
525                             for (fmt, name) in &[
526                                 ("", "Display"),
527                                 ("?", "Debug"),
528                                 ("e", "LowerExp"),
529                                 ("E", "UpperExp"),
530                                 ("o", "Octal"),
531                                 ("p", "Pointer"),
532                                 ("b", "Binary"),
533                                 ("x", "LowerHex"),
534                                 ("X", "UpperHex"),
535                             ] {
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(
539                                     sp,
540                                     &format!("use the `{}` trait", name),
541                                     *fmt,
542                                     Applicability::MaybeIncorrect,
543                                 );
544                             }
545                         }
546                         err.emit();
547                         "<invalid>"
548                     }
549                 });
550                 self.verify_arg_type(pos, ty);
551                 self.curpiece += 1;
552             }
553         }
554     }
555
556     fn verify_count(
557         &mut self,
558         c: parse::Count<'_>,
559         inner_span: &Option<rustc_parse_format::InnerSpan>,
560         named_arg_type: PositionalNamedArgType,
561     ) {
562         match c {
563             parse::CountImplied | parse::CountIs(..) => {}
564             parse::CountIsParam(i) => {
565                 self.unused_names_lint.maybe_add_positional_named_arg(
566                     i,
567                     self.args.len(),
568                     i,
569                     named_arg_type,
570                     self.curpiece,
571                     *inner_span,
572                     &self.names,
573                     true,
574                 );
575                 self.verify_arg_type(Exact(i), Count);
576             }
577             parse::CountIsName(s, span) => {
578                 self.verify_arg_type(
579                     Named(Symbol::intern(s), InnerSpan::new(span.start, span.end)),
580                     Count,
581                 );
582             }
583         }
584     }
585
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(),
591         }
592     }
593
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
597     /// format string.
598     fn report_invalid_references(&self, numbered_position_args: bool) {
599         let mut e;
600         let sp = if !self.arg_spans.is_empty() {
601             // Point at the formatting arguments.
602             MultiSpan::from_spans(self.arg_spans.clone())
603         } else {
604             MultiSpan::from_span(self.fmtsp)
605         };
606         let refs =
607             self.invalid_refs.iter().map(|(r, pos)| (r.to_string(), self.arg_spans.get(*pos)));
608
609         let mut zero_based_note = false;
610
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(
615                 sp,
616                 &format!(
617                     "{} positional argument{} in format string, but {}",
618                     count,
619                     pluralize!(count),
620                     self.describe_num_args(),
621                 ),
622             );
623             for arg in &self.args {
624                 // Point at the arguments that will be formatted.
625                 e.span_label(arg.span, "");
626             }
627         } else {
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);`
631             refs.sort();
632             refs.dedup();
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)
636             } else {
637                 MultiSpan::from_spans(spans)
638             };
639             let arg_list = if refs.len() == 1 {
640                 format!("argument {}", refs[0])
641             } else {
642                 let reg = refs.pop().unwrap();
643                 format!("arguments {head} and {tail}", head = refs.join(", "), tail = reg)
644             };
645
646             e = self.ecx.struct_span_err(
647                 sp,
648                 &format!(
649                     "invalid reference to positional {} ({})",
650                     arg_list,
651                     self.describe_num_args()
652                 ),
653             );
654             zero_based_note = true;
655         };
656
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() => {
662                         e.span_label(
663                             span,
664                             &format!(
665                                 "this precision flag expects an `usize` argument at position {}, \
666                              but {}",
667                                 pos,
668                                 self.describe_num_args(),
669                             ),
670                         );
671                         zero_based_note = true;
672                     }
673                     parse::CountIsParam(pos) => {
674                         let count = self.pieces.len()
675                             + self
676                                 .arg_with_formatting
677                                 .iter()
678                                 .filter(|fmt| fmt.precision_span.is_some())
679                                 .count();
680                         e.span_label(
681                             span,
682                             &format!(
683                             "this precision flag adds an extra required argument at position {}, \
684                              which is why there {} expected",
685                             pos,
686                             if count == 1 {
687                                 "is 1 argument".to_string()
688                             } else {
689                                 format!("are {} arguments", count)
690                             },
691                         ),
692                         );
693                         if let Some(arg) = self.args.get(pos) {
694                             e.span_label(
695                                 arg.span,
696                                 "this parameter corresponds to the precision flag",
697                             );
698                         }
699                         zero_based_note = true;
700                     }
701                     _ => {}
702                 }
703             }
704             if let Some(span) = fmt.width_span {
705                 let span = self.fmtsp.from_inner(InnerSpan::new(span.start, span.end));
706                 match fmt.width {
707                     parse::CountIsParam(pos) if pos >= self.num_args() => {
708                         e.span_label(
709                             span,
710                             &format!(
711                                 "this width flag expects an `usize` argument at position {}, \
712                              but {}",
713                                 pos,
714                                 self.describe_num_args(),
715                             ),
716                         );
717                         zero_based_note = true;
718                     }
719                     _ => {}
720                 }
721             }
722         }
723         if zero_based_note {
724             e.note("positional arguments are zero-based");
725         }
726         if !self.arg_with_formatting.is_empty() {
727             e.note(
728                 "for information about formatting flags, visit \
729                     https://doc.rust-lang.org/std/fmt/index.html",
730             );
731         }
732
733         e.emit();
734     }
735
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));
742                 return;
743             }
744         }
745
746         match arg {
747             Exact(arg) | Capture(arg) => {
748                 match ty {
749                     Placeholder(_) => {
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();
754                             seen_ty.push(ty);
755                             i
756                         });
757                         self.arg_types[arg].push(i);
758                     }
759                     Count => {
760                         if let Entry::Vacant(e) = self.count_positions.entry(arg) {
761                             let i = self.count_positions_count;
762                             e.insert(i);
763                             self.count_args.push(arg);
764                             self.count_positions_count += 1;
765                         }
766                     }
767                 }
768             }
769
770             Named(name, span) => {
771                 match self.names.get(&name) {
772                     Some(&idx) => {
773                         // Treat as positional arg.
774                         self.verify_arg_type(Capture(idx.0), ty)
775                     }
776                     None => {
777                         // For the moment capturing variables from format strings expanded from macros is
778                         // disabled (see RFC #2795)
779                         if self.is_literal {
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)
786                             } else {
787                                 self.fmtsp
788                             };
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)
793                         } else {
794                             let msg = format!("there is no argument named `{}`", name);
795                             let sp = if self.is_literal {
796                                 self.fmtsp.from_inner(span)
797                             } else {
798                                 self.fmtsp
799                             };
800                             let mut err = self.ecx.struct_span_err(sp, &msg);
801
802                             err.note(&format!(
803                                 "did you intend to capture a variable `{}` from \
804                                  the surrounding scope?",
805                                 name
806                             ));
807                             err.note(
808                                 "to avoid ambiguity, `format_args!` cannot capture variables \
809                                  when the format string is expanded from a macro",
810                             );
811
812                             err.emit();
813                         }
814                     }
815                 }
816             }
817         }
818     }
819
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);
825
826         let mut sofar = 0usize;
827
828         // Map the arguments
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();
834         }
835
836         // Record starting index for counts, which appear just after arguments
837         self.count_args_index_offset = sofar;
838     }
839
840     fn rtpath(ecx: &ExtCtxt<'_>, s: Symbol) -> Vec<Ident> {
841         ecx.std_path(&[sym::fmt, sym::rt, sym::v1, s])
842     }
843
844     fn build_count(&self, c: parse::Count<'_>) -> P<ast::Expr> {
845         let sp = self.macsp;
846         let count = |c, arg| {
847             let mut path = Context::rtpath(self.ecx, sym::Count);
848             path.push(Ident::new(c, sp));
849             match arg {
850                 Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]),
851                 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
852             }
853         };
854         match c {
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)))
863             }
864             parse::CountImplied => count(sym::Implied, None),
865             // should never be the case, names are already resolved
866             parse::CountIsName(..) => panic!("should never happen"),
867         }
868     }
869
870     /// Build a literal expression from the accumulated string literals
871     fn build_literal_string(&mut self) -> P<ast::Expr> {
872         let sp = self.fmtsp;
873         let s = Symbol::intern(&self.literal);
874         self.literal.clear();
875         self.ecx.expr_str(sp, s)
876     }
877
878     /// Builds a static `rt::Argument` from a `parse::Piece` or append
879     /// to the `literal` string.
880     fn build_piece(
881         &mut self,
882         piece: &parse::Piece<'a>,
883         arg_index_consumed: &mut Vec<usize>,
884     ) -> Option<P<ast::Expr>> {
885         let sp = self.macsp;
886         match *piece {
887             parse::String(s) => {
888                 self.literal.push_str(s);
889                 None
890             }
891             parse::NextArgument(ref arg) => {
892                 // Build the position
893                 let pos = {
894                     match arg.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
900                                 Some(offset) => {
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);
904                                     *offset += 1;
905                                     arg_idx
906                                 }
907                             };
908                             self.ecx.expr_usize(sp, arg_idx)
909                         }
910
911                         // should never be the case, because names are already
912                         // resolved.
913                         parse::ArgumentNamed(..) => panic!("should never happen"),
914                     }
915                 };
916
917                 let simple_arg = parse::Argument {
918                     position: {
919                         // We don't have ArgumentNext any more, so we have to
920                         // track the current argument ourselves.
921                         let i = self.curarg;
922                         self.curarg += 1;
923                         parse::ArgumentIs(i)
924                     },
925                     position_span: arg.position_span,
926                     format: parse::FormatSpec {
927                         fill: arg.format.fill,
928                         align: parse::AlignUnknown,
929                         flags: 0,
930                         precision: parse::CountImplied,
931                         precision_span: None,
932                         width: parse::CountImplied,
933                         width_span: None,
934                         ty: arg.format.ty,
935                         ty_span: arg.format.ty_span,
936                     },
937                 };
938
939                 let fill = arg.format.fill.unwrap_or(' ');
940
941                 let pos_simple = arg.position.index() == simple_arg.position.index();
942
943                 if arg.format.precision_span.is_some() || arg.format.width_span.is_some() {
944                     self.arg_with_formatting.push(arg.format);
945                 }
946                 if !pos_simple || arg.format != simple_arg.format || fill != ' ' {
947                     self.all_pieces_simple = false;
948                 }
949
950                 // Build the format
951                 let fill = self.ecx.expr_lit(sp, ast::LitKind::Char(fill));
952                 let align = |name| {
953                     let mut p = Context::rtpath(self.ecx, sym::Alignment);
954                     p.push(Ident::new(name, sp));
955                     self.ecx.path_global(sp, p)
956                 };
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),
962                 };
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(
969                     sp,
970                     path,
971                     vec![
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),
977                     ],
978                 );
979
980                 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, sym::Argument));
981                 Some(self.ecx.expr_struct(
982                     sp,
983                     path,
984                     vec![
985                         self.ecx.field_imm(sp, Ident::new(sym::position, sp), pos),
986                         self.ecx.field_imm(sp, Ident::new(sym::format, sp), fmt),
987                     ],
988                 ))
989             }
990         }
991     }
992
993     /// Actually builds the expression which the format_args! block will be
994     /// expanded to.
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(),
999         );
1000
1001         // First, build up the static array which will become our precompiled
1002         // format "string"
1003         let pieces = self.ecx.expr_array_ref(self.fmtsp, self.str_pieces);
1004
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}").
1010         //
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)));
1017         }
1018         fmt_arg_index_and_ty.extend(self.count_args.iter().map(|&i| (i, &Count)));
1019
1020         // Figure out whether there are permuted or repeated elements. If not,
1021         // we can generate simpler code.
1022         //
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);
1028
1029         // We want to emit:
1030         //
1031         //     [ArgumentV1::new(&$arg0, â€¦), ArgumentV1::new(&$arg1, â€¦), â€¦]
1032         //
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.
1038         //
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.
1044         //
1045         // Thus in the not nicely ordered case, and in the yielding case, we
1046         // emit the following instead:
1047         //
1048         //     match (&$arg0, &$arg1, â€¦) {
1049         //         args => [ArgumentV1::new(args.$i, â€¦), ArgumentV1::new(args.$j, â€¦), â€¦]
1050         //     }
1051         //
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
1056         // possible.
1057         let no_need_for_match =
1058             nicely_ordered && !original_args.iter().skip(1).any(|e| may_contain_yield_point(e));
1059
1060         for (arg_index, arg_ty) in fmt_arg_index_and_ty {
1061             let e = &mut original_args[arg_index];
1062             let span = e.span;
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()))
1067             } else {
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))
1072             };
1073             fmt_args.push(Context::format_arg(self.ecx, self.macsp, span, arg_ty, arg));
1074         }
1075
1076         let args_array = self.ecx.expr_array(self.macsp, fmt_args);
1077         let args_slice = self.ecx.expr_addr_of(
1078             self.macsp,
1079             if no_need_for_match {
1080                 args_array
1081             } else {
1082                 // In the !no_need_for_match case, none of the exprs were moved
1083                 // away in the previous loop.
1084                 //
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
1089                     .into_iter()
1090                     .map(|e| self.ecx.expr_addr_of(e.span.with_ctxt(self.macsp.ctxt()), e))
1091                     .collect();
1092
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])
1097             },
1098         );
1099
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])
1103         } else {
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);
1107
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),
1114                 span: self.macsp,
1115                 tokens: None,
1116                 could_be_bare_literal: false,
1117             }));
1118
1119             ("new_v1_formatted", vec![pieces, args_slice, fmt, unsafe_expr])
1120         };
1121
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)
1124     }
1125
1126     fn format_arg(
1127         ecx: &ExtCtxt<'_>,
1128         macsp: Span,
1129         mut sp: Span,
1130         ty: &ArgumentType,
1131         arg: P<ast::Expr>,
1132     ) -> P<ast::Expr> {
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_,
1137             Count => {
1138                 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, sym::from_usize]);
1139                 return ecx.expr_call_global(macsp, path, vec![arg]);
1140             }
1141         };
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!(),
1153         };
1154
1155         let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, Symbol::intern(new_fn_name)]);
1156         ecx.expr_call_global(sp, path, vec![arg])
1157     }
1158 }
1159
1160 fn expand_format_args_impl<'cx>(
1161     ecx: &'cx mut ExtCtxt<'_>,
1162     mut sp: Span,
1163     tts: TokenStream,
1164     nl: bool,
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))
1170         }
1171         Err(mut err) => {
1172             err.emit();
1173             DummyResult::any(sp)
1174         }
1175     }
1176 }
1177
1178 pub fn expand_format_args<'cx>(
1179     ecx: &'cx mut ExtCtxt<'_>,
1180     sp: Span,
1181     tts: TokenStream,
1182 ) -> Box<dyn base::MacResult + 'cx> {
1183     expand_format_args_impl(ecx, sp, tts, false)
1184 }
1185
1186 pub fn expand_format_args_nl<'cx>(
1187     ecx: &'cx mut ExtCtxt<'_>,
1188     sp: Span,
1189     tts: TokenStream,
1190 ) -> Box<dyn base::MacResult + 'cx> {
1191     expand_format_args_impl(ecx, sp, tts, true)
1192 }
1193
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);
1197
1198         let msg = format!("named argument `{}` is not used by name", named_arg.replacement);
1199
1200         cx.ecx.buffered_early_lint.push(BufferedEarlyLint {
1201             span: MultiSpan::from_span(named_arg.positional_named_arg_span),
1202             msg: msg.clone(),
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,
1211             },
1212         });
1213     }
1214 }
1215
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<'_>,
1220     sp: Span,
1221     efmt: P<ast::Expr>,
1222     args: Vec<FormatArg>,
1223     names: FxHashMap<Symbol, (usize, Span)>,
1224     append_newline: bool,
1225 ) -> P<ast::Expr> {
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();
1230
1231     let mut macsp = ecx.call_site();
1232     macsp = ecx.with_def_site_ctxt(macsp);
1233
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));
1240             fmt
1241         }
1242         Ok(fmt) => fmt,
1243         Err(err) => {
1244             if let Some((mut err, suggested)) = err {
1245                 let sugg_fmt = match args.len() {
1246                     0 => "{}".to_string(),
1247                     _ => format!("{}{{}}", "{} ".repeat(args.len())),
1248                 };
1249                 if !suggested {
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,
1255                     );
1256                 }
1257                 err.emit();
1258             }
1259             return DummyResult::raw_expr(sp, true);
1260         }
1261     };
1262
1263     let str_style = match fmt_style {
1264         ast::StrStyle::Cooked => None,
1265         ast::StrStyle::Raw(raw) => Some(raw as usize),
1266     };
1267
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(
1271         fmt_str,
1272         str_style,
1273         fmt_snippet,
1274         append_newline,
1275         parse::ParseMode::Format,
1276     );
1277
1278     let mut unverified_pieces = Vec::new();
1279     while let Some(piece) = parser.next() {
1280         if !parser.errors.is_empty() {
1281             break;
1282         } else {
1283             unverified_pieces.push(piece);
1284         }
1285     }
1286
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))
1291         } else {
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.
1300             fmt_span
1301         };
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 {
1305             e.note(&note);
1306         }
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);
1310             }
1311         }
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,
1319                     None => fmt_sp,
1320                 };
1321                 e.multipart_suggestion_verbose(
1322                     "consider using a positional formatting argument instead",
1323                     vec![
1324                         (captured_arg_span, positional_args.len().to_string()),
1325                         (span.shrink_to_hi(), format!(", {}", arg)),
1326                     ],
1327                     Applicability::MachineApplicable,
1328                 );
1329             }
1330         }
1331         e.emit();
1332         return DummyResult::raw_expr(sp, true);
1333     }
1334
1335     let arg_spans = parser
1336         .arg_places
1337         .iter()
1338         .map(|span| fmt_span.from_inner(InnerSpan::new(span.start, span.end)))
1339         .collect();
1340
1341     let named_pos: FxHashSet<usize> = names.values().cloned().map(|(i, _)| i).collect();
1342
1343     let mut cx = Context {
1344         ecx,
1345         args: args.into_iter().map(|arg| arg.expr).collect(),
1346         num_captured_args: 0,
1347         arg_types,
1348         arg_unique_types,
1349         names,
1350         curarg: 0,
1351         curpiece: 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,
1361         macsp,
1362         fmtsp: fmt_span,
1363         invalid_refs: Vec::new(),
1364         arg_spans,
1365         arg_with_formatting: Vec::new(),
1366         is_literal: parser.is_literal,
1367         unused_names_lint: PositionalNamedArgsLint { positional_named_args: vec![] },
1368     };
1369
1370     // This needs to happen *after* the Parser has consumed all pieces to create all the spans
1371     let pieces = unverified_pieces
1372         .into_iter()
1373         .map(|mut piece| {
1374             cx.verify_piece(&piece);
1375             cx.resolve_name_inplace(&mut piece);
1376             piece
1377         })
1378         .collect::<Vec<_>>();
1379
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(..)),
1383     });
1384
1385     cx.build_index_map();
1386
1387     let mut arg_index_consumed = vec![0usize; cx.arg_index_map.len()];
1388
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);
1394         }
1395     }
1396
1397     if !cx.literal.is_empty() {
1398         let s = cx.build_literal_string();
1399         cx.str_pieces.push(s);
1400     }
1401
1402     if !cx.invalid_refs.is_empty() {
1403         cx.report_invalid_references(numbered_position_args);
1404     }
1405
1406     // Make sure that all arguments were used and all arguments have types.
1407     let errs = cx
1408         .arg_types
1409         .iter()
1410         .enumerate()
1411         .filter(|(i, ty)| ty.is_empty() && !cx.count_positions.contains_key(&i))
1412         .map(|(i, _)| {
1413             let msg = if named_pos.contains(&i) {
1414                 // named argument
1415                 "named argument never used"
1416             } else {
1417                 // positional argument
1418                 "argument never used"
1419             };
1420             (cx.args[i].span, msg)
1421         })
1422         .collect::<Vec<_>>();
1423
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;
1428
1429         let mut diag = {
1430             if let [(sp, msg)] = &errs[..] {
1431                 let mut diag = cx.ecx.struct_span_err(*sp, *msg);
1432                 diag.span_label(*sp, *msg);
1433                 diag
1434             } else {
1435                 let mut diag = cx.ecx.struct_span_err(
1436                     errs.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
1437                     "multiple unused formatting arguments",
1438                 );
1439                 diag.span_label(cx.fmtsp, "multiple missing formatting specifiers");
1440                 for (sp, msg) in errs {
1441                     diag.span_label(sp, msg);
1442                 }
1443                 diag
1444             }
1445         };
1446
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;
1452
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();
1456
1457             macro_rules! check_foreign {
1458                 ($kind:ident) => {{
1459                     let mut show_doc_note = false;
1460
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),
1468
1469                             // If it has no translation, don't call it out specifically.
1470                             _ => continue,
1471                         };
1472
1473                         let pos = sub.position();
1474                         let sub = String::from(sub.as_str());
1475                         if explained.contains(&sub) {
1476                             continue;
1477                         }
1478                         explained.insert(sub.clone());
1479
1480                         if !found_foreign {
1481                             found_foreign = true;
1482                             show_doc_note = true;
1483                         }
1484
1485                         if let Some(inner_sp) = pos {
1486                             let sp = fmt_sp.from_inner(inner_sp);
1487
1488                             if success {
1489                                 suggestions.push((sp, trn));
1490                             } else {
1491                                 diag.span_note(
1492                                     sp,
1493                                     &format!("format specifiers use curly braces, and {}", trn),
1494                                 );
1495                             }
1496                         } else {
1497                             if success {
1498                                 diag.help(&format!("`{}` should be written as `{}`", sub, trn));
1499                             } else {
1500                                 diag.note(&format!(
1501                                     "`{}` should use curly braces, and {}",
1502                                     sub, trn
1503                                 ));
1504                             }
1505                         }
1506                     }
1507
1508                     if show_doc_note {
1509                         diag.note(concat!(
1510                             stringify!($kind),
1511                             " formatting not supported; see the documentation for `std::fmt`",
1512                         ));
1513                     }
1514                     if suggestions.len() > 0 {
1515                         diag.multipart_suggestion(
1516                             "format specifiers use curly braces",
1517                             suggestions,
1518                             Applicability::MachineApplicable,
1519                         );
1520                     }
1521                 }};
1522             }
1523
1524             check_foreign!(printf);
1525             if !found_foreign {
1526                 check_foreign!(shell);
1527             }
1528         }
1529         if !found_foreign && errs_len == 1 {
1530             diag.span_label(cx.fmtsp, "formatting specifier missing");
1531         }
1532
1533         diag.emit();
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);
1538     }
1539
1540     cx.into_expr()
1541 }
1542
1543 fn may_contain_yield_point(e: &ast::Expr) -> bool {
1544     struct MayContainYieldPoint(bool);
1545
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 {
1549                 self.0 = true;
1550             } else {
1551                 visit::walk_expr(self, e);
1552             }
1553         }
1554
1555         fn visit_mac_call(&mut self, _: &ast::MacCall) {
1556             self.0 = true;
1557         }
1558
1559         fn visit_attribute(&mut self, _: &ast::Attribute) {
1560             // Conservatively assume this may be a proc macro attribute in
1561             // expression position.
1562             self.0 = true;
1563         }
1564
1565         fn visit_item(&mut self, _: &ast::Item) {
1566             // Do not recurse into nested items.
1567         }
1568     }
1569
1570     let mut visitor = MayContainYieldPoint(false);
1571     visitor.visit_expr(e);
1572     visitor.0
1573 }