]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_builtin_macros/src/format.rs
Rollup merge of #100738 - nidnogg:diagnostics_migr_const_eval, r=davidtwco
[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         arg: Option<&FormatArg>,
134         ty: PositionalNamedArgType,
135         cur_piece: usize,
136         inner_span_to_replace: Option<rustc_parse_format::InnerSpan>,
137         has_formatting: bool,
138     ) {
139         if let Some(arg) = arg {
140             if let Some(name) = arg.name {
141                 self.push(name, ty, cur_piece, inner_span_to_replace, has_formatting)
142             }
143         }
144     }
145
146     /// Construct a PositionalNamedArg struct and push it into the vec of positional
147     /// named arguments.
148     fn push(
149         &mut self,
150         arg_name: Ident,
151         ty: PositionalNamedArgType,
152         cur_piece: usize,
153         inner_span_to_replace: Option<rustc_parse_format::InnerSpan>,
154         has_formatting: bool,
155     ) {
156         // In FormatSpec, `precision_span` starts at the leading `.`, which we want to keep in
157         // the lint suggestion, so increment `start` by 1 when `PositionalArgumentType` is
158         // `Precision`.
159         let inner_span_to_replace = if ty == PositionalNamedArgType::Precision {
160             inner_span_to_replace
161                 .map(|is| rustc_parse_format::InnerSpan { start: is.start + 1, end: is.end })
162         } else {
163             inner_span_to_replace
164         };
165         self.positional_named_args.push(PositionalNamedArg {
166             ty,
167             cur_piece,
168             inner_span_to_replace,
169             replacement: arg_name.name,
170             positional_named_arg_span: arg_name.span,
171             has_formatting,
172         });
173     }
174 }
175
176 struct Context<'a, 'b> {
177     ecx: &'a mut ExtCtxt<'b>,
178     /// The macro's call site. References to unstable formatting internals must
179     /// use this span to pass the stability checker.
180     macsp: Span,
181     /// The span of the format string literal.
182     fmtsp: Span,
183
184     /// List of parsed argument expressions.
185     /// Named expressions are resolved early, and are appended to the end of
186     /// argument expressions.
187     ///
188     /// Example showing the various data structures in motion:
189     ///
190     /// * Original: `"{foo:o} {:o} {foo:x} {0:x} {1:o} {:x} {1:x} {0:o}"`
191     /// * Implicit argument resolution: `"{foo:o} {0:o} {foo:x} {0:x} {1:o} {1:x} {1:x} {0:o}"`
192     /// * Name resolution: `"{2:o} {0:o} {2:x} {0:x} {1:o} {1:x} {1:x} {0:o}"`
193     /// * `arg_types` (in JSON): `[[0, 1, 0], [0, 1, 1], [0, 1]]`
194     /// * `arg_unique_types` (in simplified JSON): `[["o", "x"], ["o", "x"], ["o", "x"]]`
195     /// * `names` (in JSON): `{"foo": 2}`
196     args: Vec<FormatArg>,
197     /// The number of arguments that were added by implicit capturing.
198     num_captured_args: usize,
199     /// Placeholder slot numbers indexed by argument.
200     arg_types: Vec<Vec<usize>>,
201     /// Unique format specs seen for each argument.
202     arg_unique_types: Vec<Vec<ArgumentType>>,
203     /// Map from named arguments to their resolved indices.
204     names: FxHashMap<Symbol, usize>,
205
206     /// The latest consecutive literal strings, or empty if there weren't any.
207     literal: String,
208
209     /// Collection of the compiled `rt::Argument` structures
210     pieces: Vec<P<ast::Expr>>,
211     /// Collection of string literals
212     str_pieces: Vec<P<ast::Expr>>,
213     /// Stays `true` if all formatting parameters are default (as in "{}{}").
214     all_pieces_simple: bool,
215
216     /// Mapping between positional argument references and indices into the
217     /// final generated static argument array. We record the starting indices
218     /// corresponding to each positional argument, and number of references
219     /// consumed so far for each argument, to facilitate correct `Position`
220     /// mapping in `build_piece`. In effect this can be seen as a "flattened"
221     /// version of `arg_unique_types`.
222     ///
223     /// Again with the example described above in docstring for `args`:
224     ///
225     /// * `arg_index_map` (in JSON): `[[0, 1, 0], [2, 3, 3], [4, 5]]`
226     arg_index_map: Vec<Vec<usize>>,
227
228     /// Starting offset of count argument slots.
229     count_args_index_offset: usize,
230
231     /// Count argument slots and tracking data structures.
232     /// Count arguments are separately tracked for de-duplication in case
233     /// multiple references are made to one argument. For example, in this
234     /// format string:
235     ///
236     /// * Original: `"{:.*} {:.foo$} {1:.*} {:.0$}"`
237     /// * Implicit argument resolution: `"{1:.0$} {2:.foo$} {1:.3$} {4:.0$}"`
238     /// * Name resolution: `"{1:.0$} {2:.5$} {1:.3$} {4:.0$}"`
239     /// * `count_positions` (in JSON): `{0: 0, 5: 1, 3: 2}`
240     /// * `count_args`: `vec![0, 5, 3]`
241     count_args: Vec<usize>,
242     /// Relative slot numbers for count arguments.
243     count_positions: FxHashMap<usize, usize>,
244     /// Number of count slots assigned.
245     count_positions_count: usize,
246
247     /// Current position of the implicit positional arg pointer, as if it
248     /// still existed in this phase of processing.
249     /// Used only for `all_pieces_simple` tracking in `build_piece`.
250     curarg: usize,
251     /// Current piece being evaluated, used for error reporting.
252     curpiece: usize,
253     /// Keep track of invalid references to positional arguments.
254     invalid_refs: Vec<(usize, usize)>,
255     /// Spans of all the formatting arguments, in order.
256     arg_spans: Vec<Span>,
257     /// All the formatting arguments that have formatting flags set, in order for diagnostics.
258     arg_with_formatting: Vec<parse::FormatSpec<'a>>,
259
260     /// Whether this format string came from a string literal, as opposed to a macro.
261     is_literal: bool,
262     unused_names_lint: PositionalNamedArgsLint,
263 }
264
265 pub struct FormatArg {
266     expr: P<ast::Expr>,
267     name: Option<Ident>,
268 }
269
270 /// Parses the arguments from the given list of tokens, returning the diagnostic
271 /// if there's a parse error so we can continue parsing other format!
272 /// expressions.
273 ///
274 /// If parsing succeeds, the return value is:
275 ///
276 /// ```text
277 /// Some((fmtstr, parsed arguments, index map for named arguments))
278 /// ```
279 fn parse_args<'a>(
280     ecx: &mut ExtCtxt<'a>,
281     sp: Span,
282     tts: TokenStream,
283 ) -> PResult<'a, (P<ast::Expr>, Vec<FormatArg>, FxHashMap<Symbol, usize>)> {
284     let mut args = Vec::<FormatArg>::new();
285     let mut names = FxHashMap::<Symbol, usize>::default();
286
287     let mut p = ecx.new_parser_from_tts(tts);
288
289     if p.token == token::Eof {
290         return Err(ecx.struct_span_err(sp, "requires at least a format string argument"));
291     }
292
293     let first_token = &p.token;
294     let fmtstr = match first_token.kind {
295         token::TokenKind::Literal(token::Lit {
296             kind: token::LitKind::Str | token::LitKind::StrRaw(_),
297             ..
298         }) => {
299             // If the first token is a string literal, then a format expression
300             // is constructed from it.
301             //
302             // This allows us to properly handle cases when the first comma
303             // after the format string is mistakenly replaced with any operator,
304             // which cause the expression parser to eat too much tokens.
305             p.parse_literal_maybe_minus()?
306         }
307         _ => {
308             // Otherwise, we fall back to the expression parser.
309             p.parse_expr()?
310         }
311     };
312
313     let mut first = true;
314     let mut named = false;
315
316     while p.token != token::Eof {
317         if !p.eat(&token::Comma) {
318             if first {
319                 p.clear_expected_tokens();
320             }
321
322             match p.expect(&token::Comma) {
323                 Err(mut err) => {
324                     match token::TokenKind::Comma.similar_tokens() {
325                         Some(tks) if tks.contains(&p.token.kind) => {
326                             // If a similar token is found, then it may be a typo. We
327                             // consider it as a comma, and continue parsing.
328                             err.emit();
329                             p.bump();
330                         }
331                         // Otherwise stop the parsing and return the error.
332                         _ => return Err(err),
333                     }
334                 }
335                 Ok(recovered) => {
336                     assert!(recovered);
337                 }
338             }
339         }
340         first = false;
341         if p.token == token::Eof {
342             break;
343         } // accept trailing commas
344         match p.token.ident() {
345             Some((ident, _)) if p.look_ahead(1, |t| *t == token::Eq) => {
346                 named = true;
347                 p.bump();
348                 p.expect(&token::Eq)?;
349                 let e = p.parse_expr()?;
350                 if let Some(&prev) = names.get(&ident.name) {
351                     ecx.struct_span_err(e.span, &format!("duplicate argument named `{}`", ident))
352                         .span_label(args[prev].expr.span, "previously here")
353                         .span_label(e.span, "duplicate argument")
354                         .emit();
355                     continue;
356                 }
357
358                 // Resolve names into slots early.
359                 // Since all the positional args are already seen at this point
360                 // if the input is valid, we can simply append to the positional
361                 // args. And remember the names.
362                 let slot = args.len();
363                 names.insert(ident.name, slot);
364                 args.push(FormatArg { expr: e, name: Some(ident) });
365             }
366             _ => {
367                 let e = p.parse_expr()?;
368                 if named {
369                     let mut err = ecx.struct_span_err(
370                         e.span,
371                         "positional arguments cannot follow named arguments",
372                     );
373                     err.span_label(e.span, "positional arguments must be before named arguments");
374                     for &pos in names.values() {
375                         err.span_label(args[pos].expr.span, "named argument");
376                     }
377                     err.emit();
378                 }
379                 args.push(FormatArg { expr: e, name: None });
380             }
381         }
382     }
383     Ok((fmtstr, args, names))
384 }
385
386 impl<'a, 'b> Context<'a, 'b> {
387     /// The number of arguments that were explicitly given.
388     fn num_args(&self) -> usize {
389         self.args.len() - self.num_captured_args
390     }
391
392     fn resolve_name_inplace(&mut self, p: &mut parse::Piece<'_>) {
393         // NOTE: the `unwrap_or` branch is needed in case of invalid format
394         // arguments, e.g., `format_args!("{foo}")`.
395         let lookup = |s: &str| self.names.get(&Symbol::intern(s)).copied().unwrap_or(0);
396
397         match *p {
398             parse::String(_) => {}
399             parse::NextArgument(ref mut arg) => {
400                 if let parse::ArgumentNamed(s) = arg.position {
401                     arg.position = parse::ArgumentIs(lookup(s));
402                 }
403                 if let parse::CountIsName(s, _) = arg.format.width {
404                     arg.format.width = parse::CountIsParam(lookup(s));
405                 }
406                 if let parse::CountIsName(s, _) = arg.format.precision {
407                     arg.format.precision = parse::CountIsParam(lookup(s));
408                 }
409             }
410         }
411     }
412
413     /// Verifies one piece of a parse string, and remembers it if valid.
414     /// All errors are not emitted as fatal so we can continue giving errors
415     /// about this and possibly other format strings.
416     fn verify_piece(&mut self, p: &parse::Piece<'a>) {
417         match *p {
418             parse::String(..) => {}
419             parse::NextArgument(ref arg) => {
420                 // width/precision first, if they have implicit positional
421                 // parameters it makes more sense to consume them first.
422                 self.verify_count(
423                     arg.format.width,
424                     &arg.format.width_span,
425                     PositionalNamedArgType::Width,
426                 );
427                 self.verify_count(
428                     arg.format.precision,
429                     &arg.format.precision_span,
430                     PositionalNamedArgType::Precision,
431                 );
432
433                 let has_precision = arg.format.precision != Count::CountImplied;
434                 let has_width = arg.format.width != Count::CountImplied;
435
436                 if has_precision || has_width {
437                     // push before named params are resolved to aid diagnostics
438                     self.arg_with_formatting.push(arg.format);
439                 }
440
441                 // argument second, if it's an implicit positional parameter
442                 // it's written second, so it should come after width/precision.
443                 let pos = match arg.position {
444                     parse::ArgumentIs(i) => {
445                         self.unused_names_lint.maybe_add_positional_named_arg(
446                             self.args.get(i),
447                             PositionalNamedArgType::Arg,
448                             self.curpiece,
449                             Some(arg.position_span),
450                             has_precision || has_width,
451                         );
452
453                         Exact(i)
454                     }
455                     parse::ArgumentImplicitlyIs(i) => {
456                         self.unused_names_lint.maybe_add_positional_named_arg(
457                             self.args.get(i),
458                             PositionalNamedArgType::Arg,
459                             self.curpiece,
460                             None,
461                             has_precision || has_width,
462                         );
463                         Exact(i)
464                     }
465                     parse::ArgumentNamed(s) => {
466                         let symbol = Symbol::intern(s);
467                         let span = arg.position_span;
468                         Named(symbol, InnerSpan::new(span.start, span.end))
469                     }
470                 };
471
472                 let ty = Placeholder(match arg.format.ty {
473                     "" => "Display",
474                     "?" => "Debug",
475                     "e" => "LowerExp",
476                     "E" => "UpperExp",
477                     "o" => "Octal",
478                     "p" => "Pointer",
479                     "b" => "Binary",
480                     "x" => "LowerHex",
481                     "X" => "UpperHex",
482                     _ => {
483                         let fmtsp = self.fmtsp;
484                         let sp = arg
485                             .format
486                             .ty_span
487                             .map(|sp| fmtsp.from_inner(InnerSpan::new(sp.start, sp.end)));
488                         let mut err = self.ecx.struct_span_err(
489                             sp.unwrap_or(fmtsp),
490                             &format!("unknown format trait `{}`", arg.format.ty),
491                         );
492                         err.note(
493                             "the only appropriate formatting traits are:\n\
494                                 - ``, which uses the `Display` trait\n\
495                                 - `?`, which uses the `Debug` trait\n\
496                                 - `e`, which uses the `LowerExp` trait\n\
497                                 - `E`, which uses the `UpperExp` trait\n\
498                                 - `o`, which uses the `Octal` trait\n\
499                                 - `p`, which uses the `Pointer` trait\n\
500                                 - `b`, which uses the `Binary` trait\n\
501                                 - `x`, which uses the `LowerHex` trait\n\
502                                 - `X`, which uses the `UpperHex` trait",
503                         );
504                         if let Some(sp) = sp {
505                             for (fmt, name) in &[
506                                 ("", "Display"),
507                                 ("?", "Debug"),
508                                 ("e", "LowerExp"),
509                                 ("E", "UpperExp"),
510                                 ("o", "Octal"),
511                                 ("p", "Pointer"),
512                                 ("b", "Binary"),
513                                 ("x", "LowerHex"),
514                                 ("X", "UpperHex"),
515                             ] {
516                                 // FIXME: rustfix (`run-rustfix`) fails to apply suggestions.
517                                 // > "Cannot replace slice of data that was already replaced"
518                                 err.tool_only_span_suggestion(
519                                     sp,
520                                     &format!("use the `{}` trait", name),
521                                     *fmt,
522                                     Applicability::MaybeIncorrect,
523                                 );
524                             }
525                         }
526                         err.emit();
527                         "<invalid>"
528                     }
529                 });
530                 self.verify_arg_type(pos, ty);
531                 self.curpiece += 1;
532             }
533         }
534     }
535
536     fn verify_count(
537         &mut self,
538         c: parse::Count<'_>,
539         inner_span: &Option<rustc_parse_format::InnerSpan>,
540         named_arg_type: PositionalNamedArgType,
541     ) {
542         match c {
543             parse::CountImplied | parse::CountIs(..) => {}
544             parse::CountIsParam(i) => {
545                 self.unused_names_lint.maybe_add_positional_named_arg(
546                     self.args.get(i),
547                     named_arg_type,
548                     self.curpiece,
549                     *inner_span,
550                     true,
551                 );
552                 self.verify_arg_type(Exact(i), Count);
553             }
554             parse::CountIsName(s, span) => {
555                 self.verify_arg_type(
556                     Named(Symbol::intern(s), InnerSpan::new(span.start, span.end)),
557                     Count,
558                 );
559             }
560         }
561     }
562
563     fn describe_num_args(&self) -> Cow<'_, str> {
564         match self.num_args() {
565             0 => "no arguments were given".into(),
566             1 => "there is 1 argument".into(),
567             x => format!("there are {} arguments", x).into(),
568         }
569     }
570
571     /// Handle invalid references to positional arguments. Output different
572     /// errors for the case where all arguments are positional and for when
573     /// there are named arguments or numbered positional arguments in the
574     /// format string.
575     fn report_invalid_references(&self, numbered_position_args: bool) {
576         let mut e;
577         let sp = if !self.arg_spans.is_empty() {
578             // Point at the formatting arguments.
579             MultiSpan::from_spans(self.arg_spans.clone())
580         } else {
581             MultiSpan::from_span(self.fmtsp)
582         };
583         let refs =
584             self.invalid_refs.iter().map(|(r, pos)| (r.to_string(), self.arg_spans.get(*pos)));
585
586         let mut zero_based_note = false;
587
588         let count = self.pieces.len()
589             + self
590                 .arg_with_formatting
591                 .iter()
592                 .filter(|fmt| matches!(fmt.precision, parse::CountIsParam(_)))
593                 .count();
594         if self.names.is_empty() && !numbered_position_args && count != self.num_args() {
595             e = self.ecx.struct_span_err(
596                 sp,
597                 &format!(
598                     "{} positional argument{} in format string, but {}",
599                     count,
600                     pluralize!(count),
601                     self.describe_num_args(),
602                 ),
603             );
604             for arg in &self.args {
605                 // Point at the arguments that will be formatted.
606                 e.span_label(arg.expr.span, "");
607             }
608         } else {
609             let (mut refs, spans): (Vec<_>, Vec<_>) = refs.unzip();
610             // Avoid `invalid reference to positional arguments 7 and 7 (there is 1 argument)`
611             // for `println!("{7:7$}", 1);`
612             refs.sort();
613             refs.dedup();
614             let spans: Vec<_> = spans.into_iter().filter_map(|sp| sp.copied()).collect();
615             let sp = if self.arg_spans.is_empty() || spans.is_empty() {
616                 MultiSpan::from_span(self.fmtsp)
617             } else {
618                 MultiSpan::from_spans(spans)
619             };
620             let arg_list = if refs.len() == 1 {
621                 format!("argument {}", refs[0])
622             } else {
623                 let reg = refs.pop().unwrap();
624                 format!("arguments {head} and {tail}", head = refs.join(", "), tail = reg)
625             };
626
627             e = self.ecx.struct_span_err(
628                 sp,
629                 &format!(
630                     "invalid reference to positional {} ({})",
631                     arg_list,
632                     self.describe_num_args()
633                 ),
634             );
635             zero_based_note = true;
636         };
637
638         for fmt in &self.arg_with_formatting {
639             if let Some(span) = fmt.precision_span {
640                 let span = self.fmtsp.from_inner(InnerSpan::new(span.start, span.end));
641                 match fmt.precision {
642                     parse::CountIsParam(pos) if pos > self.num_args() => {
643                         e.span_label(
644                             span,
645                             &format!(
646                                 "this precision flag expects an `usize` argument at position {}, \
647                              but {}",
648                                 pos,
649                                 self.describe_num_args(),
650                             ),
651                         );
652                         zero_based_note = true;
653                     }
654                     parse::CountIsParam(pos) => {
655                         let count = self.pieces.len()
656                             + self
657                                 .arg_with_formatting
658                                 .iter()
659                                 .filter(|fmt| matches!(fmt.precision, parse::CountIsParam(_)))
660                                 .count();
661                         e.span_label(
662                             span,
663                             &format!(
664                             "this precision flag adds an extra required argument at position {}, \
665                              which is why there {} expected",
666                             pos,
667                             if count == 1 {
668                                 "is 1 argument".to_string()
669                             } else {
670                                 format!("are {} arguments", count)
671                             },
672                         ),
673                         );
674                         if let Some(arg) = self.args.get(pos) {
675                             e.span_label(
676                                 arg.expr.span,
677                                 "this parameter corresponds to the precision flag",
678                             );
679                         }
680                         zero_based_note = true;
681                     }
682                     _ => {}
683                 }
684             }
685             if let Some(span) = fmt.width_span {
686                 let span = self.fmtsp.from_inner(InnerSpan::new(span.start, span.end));
687                 match fmt.width {
688                     parse::CountIsParam(pos) if pos >= self.num_args() => {
689                         e.span_label(
690                             span,
691                             &format!(
692                                 "this width flag expects an `usize` argument at position {}, \
693                              but {}",
694                                 pos,
695                                 self.describe_num_args(),
696                             ),
697                         );
698                         zero_based_note = true;
699                     }
700                     _ => {}
701                 }
702             }
703         }
704         if zero_based_note {
705             e.note("positional arguments are zero-based");
706         }
707         if !self.arg_with_formatting.is_empty() {
708             e.note(
709                 "for information about formatting flags, visit \
710                     https://doc.rust-lang.org/std/fmt/index.html",
711             );
712         }
713
714         e.emit();
715     }
716
717     /// Actually verifies and tracks a given format placeholder
718     /// (a.k.a. argument).
719     fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
720         if let Exact(arg) = arg {
721             if arg >= self.num_args() {
722                 self.invalid_refs.push((arg, self.curpiece));
723                 return;
724             }
725         }
726
727         match arg {
728             Exact(arg) | Capture(arg) => {
729                 match ty {
730                     Placeholder(_) => {
731                         // record every (position, type) combination only once
732                         let seen_ty = &mut self.arg_unique_types[arg];
733                         let i = seen_ty.iter().position(|x| *x == ty).unwrap_or_else(|| {
734                             let i = seen_ty.len();
735                             seen_ty.push(ty);
736                             i
737                         });
738                         self.arg_types[arg].push(i);
739                     }
740                     Count => {
741                         if let Entry::Vacant(e) = self.count_positions.entry(arg) {
742                             let i = self.count_positions_count;
743                             e.insert(i);
744                             self.count_args.push(arg);
745                             self.count_positions_count += 1;
746                         }
747                     }
748                 }
749             }
750
751             Named(name, span) => {
752                 match self.names.get(&name) {
753                     Some(&idx) => {
754                         // Treat as positional arg.
755                         self.verify_arg_type(Capture(idx), ty)
756                     }
757                     None => {
758                         // For the moment capturing variables from format strings expanded from macros is
759                         // disabled (see RFC #2795)
760                         if self.is_literal {
761                             // Treat this name as a variable to capture from the surrounding scope
762                             let idx = self.args.len();
763                             self.arg_types.push(Vec::new());
764                             self.arg_unique_types.push(Vec::new());
765                             let span = if self.is_literal {
766                                 self.fmtsp.from_inner(span)
767                             } else {
768                                 self.fmtsp
769                             };
770                             self.num_captured_args += 1;
771                             self.args.push(FormatArg {
772                                 expr: self.ecx.expr_ident(span, Ident::new(name, span)),
773                                 name: Some(Ident::new(name, span)),
774                             });
775                             self.names.insert(name, idx);
776                             self.verify_arg_type(Capture(idx), ty)
777                         } else {
778                             let msg = format!("there is no argument named `{}`", name);
779                             let sp = if self.is_literal {
780                                 self.fmtsp.from_inner(span)
781                             } else {
782                                 self.fmtsp
783                             };
784                             let mut err = self.ecx.struct_span_err(sp, &msg);
785
786                             err.note(&format!(
787                                 "did you intend to capture a variable `{}` from \
788                                  the surrounding scope?",
789                                 name
790                             ));
791                             err.note(
792                                 "to avoid ambiguity, `format_args!` cannot capture variables \
793                                  when the format string is expanded from a macro",
794                             );
795
796                             err.emit();
797                         }
798                     }
799                 }
800             }
801         }
802     }
803
804     /// Builds the mapping between format placeholders and argument objects.
805     fn build_index_map(&mut self) {
806         // NOTE: Keep the ordering the same as `into_expr`'s expansion would do!
807         let args_len = self.args.len();
808         self.arg_index_map.reserve(args_len);
809
810         let mut sofar = 0usize;
811
812         // Map the arguments
813         for i in 0..args_len {
814             let arg_types = &self.arg_types[i];
815             let arg_offsets = arg_types.iter().map(|offset| sofar + *offset).collect::<Vec<_>>();
816             self.arg_index_map.push(arg_offsets);
817             sofar += self.arg_unique_types[i].len();
818         }
819
820         // Record starting index for counts, which appear just after arguments
821         self.count_args_index_offset = sofar;
822     }
823
824     fn rtpath(ecx: &ExtCtxt<'_>, s: Symbol) -> Vec<Ident> {
825         ecx.std_path(&[sym::fmt, sym::rt, sym::v1, s])
826     }
827
828     fn build_count(&self, c: parse::Count<'_>) -> P<ast::Expr> {
829         let sp = self.macsp;
830         let count = |c, arg| {
831             let mut path = Context::rtpath(self.ecx, sym::Count);
832             path.push(Ident::new(c, sp));
833             match arg {
834                 Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]),
835                 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
836             }
837         };
838         match c {
839             parse::CountIs(i) => count(sym::Is, Some(self.ecx.expr_usize(sp, i))),
840             parse::CountIsParam(i) => {
841                 // This needs mapping too, as `i` is referring to a macro
842                 // argument. If `i` is not found in `count_positions` then
843                 // the error had already been emitted elsewhere.
844                 let i = self.count_positions.get(&i).cloned().unwrap_or(0)
845                     + self.count_args_index_offset;
846                 count(sym::Param, Some(self.ecx.expr_usize(sp, i)))
847             }
848             parse::CountImplied => count(sym::Implied, None),
849             // should never be the case, names are already resolved
850             parse::CountIsName(..) => panic!("should never happen"),
851         }
852     }
853
854     /// Build a literal expression from the accumulated string literals
855     fn build_literal_string(&mut self) -> P<ast::Expr> {
856         let sp = self.fmtsp;
857         let s = Symbol::intern(&self.literal);
858         self.literal.clear();
859         self.ecx.expr_str(sp, s)
860     }
861
862     /// Builds a static `rt::Argument` from a `parse::Piece` or append
863     /// to the `literal` string.
864     fn build_piece(
865         &mut self,
866         piece: &parse::Piece<'a>,
867         arg_index_consumed: &mut Vec<usize>,
868     ) -> Option<P<ast::Expr>> {
869         let sp = self.macsp;
870         match *piece {
871             parse::String(s) => {
872                 self.literal.push_str(s);
873                 None
874             }
875             parse::NextArgument(ref arg) => {
876                 // Build the position
877                 let pos = {
878                     match arg.position {
879                         parse::ArgumentIs(i, ..) | parse::ArgumentImplicitlyIs(i) => {
880                             // Map to index in final generated argument array
881                             // in case of multiple types specified
882                             let arg_idx = match arg_index_consumed.get_mut(i) {
883                                 None => 0, // error already emitted elsewhere
884                                 Some(offset) => {
885                                     let idx_map = &self.arg_index_map[i];
886                                     // unwrap_or branch: error already emitted elsewhere
887                                     let arg_idx = *idx_map.get(*offset).unwrap_or(&0);
888                                     *offset += 1;
889                                     arg_idx
890                                 }
891                             };
892                             self.ecx.expr_usize(sp, arg_idx)
893                         }
894
895                         // should never be the case, because names are already
896                         // resolved.
897                         parse::ArgumentNamed(..) => panic!("should never happen"),
898                     }
899                 };
900
901                 let simple_arg = parse::Argument {
902                     position: {
903                         // We don't have ArgumentNext any more, so we have to
904                         // track the current argument ourselves.
905                         let i = self.curarg;
906                         self.curarg += 1;
907                         parse::ArgumentIs(i)
908                     },
909                     position_span: arg.position_span,
910                     format: parse::FormatSpec {
911                         fill: None,
912                         align: parse::AlignUnknown,
913                         flags: 0,
914                         precision: parse::CountImplied,
915                         precision_span: arg.format.precision_span,
916                         width: parse::CountImplied,
917                         width_span: arg.format.width_span,
918                         ty: arg.format.ty,
919                         ty_span: arg.format.ty_span,
920                     },
921                 };
922
923                 let fill = arg.format.fill.unwrap_or(' ');
924                 let pos_simple = arg.position.index() == simple_arg.position.index();
925
926                 if !pos_simple || arg.format != simple_arg.format {
927                     self.all_pieces_simple = false;
928                 }
929
930                 // Build the format
931                 let fill = self.ecx.expr_char(sp, fill);
932                 let align = |name| {
933                     let mut p = Context::rtpath(self.ecx, sym::Alignment);
934                     p.push(Ident::new(name, sp));
935                     self.ecx.path_global(sp, p)
936                 };
937                 let align = match arg.format.align {
938                     parse::AlignLeft => align(sym::Left),
939                     parse::AlignRight => align(sym::Right),
940                     parse::AlignCenter => align(sym::Center),
941                     parse::AlignUnknown => align(sym::Unknown),
942                 };
943                 let align = self.ecx.expr_path(align);
944                 let flags = self.ecx.expr_u32(sp, arg.format.flags);
945                 let prec = self.build_count(arg.format.precision);
946                 let width = self.build_count(arg.format.width);
947                 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, sym::FormatSpec));
948                 let fmt = self.ecx.expr_struct(
949                     sp,
950                     path,
951                     vec![
952                         self.ecx.field_imm(sp, Ident::new(sym::fill, sp), fill),
953                         self.ecx.field_imm(sp, Ident::new(sym::align, sp), align),
954                         self.ecx.field_imm(sp, Ident::new(sym::flags, sp), flags),
955                         self.ecx.field_imm(sp, Ident::new(sym::precision, sp), prec),
956                         self.ecx.field_imm(sp, Ident::new(sym::width, sp), width),
957                     ],
958                 );
959
960                 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, sym::Argument));
961                 Some(self.ecx.expr_struct(
962                     sp,
963                     path,
964                     vec![
965                         self.ecx.field_imm(sp, Ident::new(sym::position, sp), pos),
966                         self.ecx.field_imm(sp, Ident::new(sym::format, sp), fmt),
967                     ],
968                 ))
969             }
970         }
971     }
972
973     /// Actually builds the expression which the format_args! block will be
974     /// expanded to.
975     fn into_expr(self) -> P<ast::Expr> {
976         let mut original_args = self.args;
977         let mut fmt_args = Vec::with_capacity(
978             self.arg_unique_types.iter().map(|v| v.len()).sum::<usize>() + self.count_args.len(),
979         );
980
981         // First, build up the static array which will become our precompiled
982         // format "string"
983         let pieces = self.ecx.expr_array_ref(self.fmtsp, self.str_pieces);
984
985         // We need to construct a &[ArgumentV1] to pass into the fmt::Arguments
986         // constructor. In general the expressions in this slice might be
987         // permuted from their order in original_args (such as in the case of
988         // "{1} {0}"), or may have multiple entries referring to the same
989         // element of original_args ("{0} {0}").
990         //
991         // The following vector has one item per element of our output slice,
992         // identifying the index of which element of original_args it's passing,
993         // and that argument's type.
994         let mut fmt_arg_index_and_ty = SmallVec::<[(usize, &ArgumentType); 8]>::new();
995         for (i, unique_types) in self.arg_unique_types.iter().enumerate() {
996             fmt_arg_index_and_ty.extend(unique_types.iter().map(|ty| (i, ty)));
997         }
998         fmt_arg_index_and_ty.extend(self.count_args.iter().map(|&i| (i, &Count)));
999
1000         // Figure out whether there are permuted or repeated elements. If not,
1001         // we can generate simpler code.
1002         //
1003         // The sequence has no indices out of order or repeated if: for every
1004         // adjacent pair of elements, the first one's index is less than the
1005         // second one's index.
1006         let nicely_ordered =
1007             fmt_arg_index_and_ty.array_windows().all(|[(i, _i_ty), (j, _j_ty)]| i < j);
1008
1009         // We want to emit:
1010         //
1011         //     [ArgumentV1::new(&$arg0, â€¦), ArgumentV1::new(&$arg1, â€¦), â€¦]
1012         //
1013         // However, it's only legal to do so if $arg0, $arg1, â€¦ were written in
1014         // exactly that order by the programmer. When arguments are permuted, we
1015         // want them evaluated in the order written by the programmer, not in
1016         // the order provided to fmt::Arguments. When arguments are repeated, we
1017         // want the expression evaluated only once.
1018         //
1019         // Further, if any arg _after the first one_ contains a yield point such
1020         // as `await` or `yield`, the above short form is inconvenient for the
1021         // caller because it would keep a temporary of type ArgumentV1 alive
1022         // across the yield point. ArgumentV1 can't implement Send since it
1023         // holds a type-erased arbitrary type.
1024         //
1025         // Thus in the not nicely ordered case, and in the yielding case, we
1026         // emit the following instead:
1027         //
1028         //     match (&$arg0, &$arg1, â€¦) {
1029         //         args => [ArgumentV1::new(args.$i, â€¦), ArgumentV1::new(args.$j, â€¦), â€¦]
1030         //     }
1031         //
1032         // for the sequence of indices $i, $j, â€¦ governed by fmt_arg_index_and_ty.
1033         // This more verbose representation ensures that all arguments are
1034         // evaluated a single time each, in the order written by the programmer,
1035         // and that the surrounding future/generator (if any) is Send whenever
1036         // possible.
1037         let no_need_for_match = nicely_ordered
1038             && !original_args.iter().skip(1).any(|arg| may_contain_yield_point(&arg.expr));
1039
1040         for (arg_index, arg_ty) in fmt_arg_index_and_ty {
1041             let e = &mut original_args[arg_index].expr;
1042             let span = e.span;
1043             let arg = if no_need_for_match {
1044                 let expansion_span = e.span.with_ctxt(self.macsp.ctxt());
1045                 // The indices are strictly ordered so e has not been taken yet.
1046                 self.ecx.expr_addr_of(expansion_span, P(e.take()))
1047             } else {
1048                 let def_site = self.ecx.with_def_site_ctxt(span);
1049                 let args_tuple = self.ecx.expr_ident(def_site, Ident::new(sym::args, def_site));
1050                 let member = Ident::new(sym::integer(arg_index), def_site);
1051                 self.ecx.expr(def_site, ast::ExprKind::Field(args_tuple, member))
1052             };
1053             fmt_args.push(Context::format_arg(self.ecx, self.macsp, span, arg_ty, arg));
1054         }
1055
1056         let args_array = self.ecx.expr_array(self.macsp, fmt_args);
1057         let args_slice = self.ecx.expr_addr_of(
1058             self.macsp,
1059             if no_need_for_match {
1060                 args_array
1061             } else {
1062                 // In the !no_need_for_match case, none of the exprs were moved
1063                 // away in the previous loop.
1064                 //
1065                 // This uses the arg span for `&arg` so that borrowck errors
1066                 // point to the specific expression passed to the macro (the
1067                 // span is otherwise unavailable in the MIR used by borrowck).
1068                 let heads = original_args
1069                     .into_iter()
1070                     .map(|arg| {
1071                         self.ecx.expr_addr_of(arg.expr.span.with_ctxt(self.macsp.ctxt()), arg.expr)
1072                     })
1073                     .collect();
1074
1075                 let pat = self.ecx.pat_ident(self.macsp, Ident::new(sym::args, self.macsp));
1076                 let arm = self.ecx.arm(self.macsp, pat, args_array);
1077                 let head = self.ecx.expr(self.macsp, ast::ExprKind::Tup(heads));
1078                 self.ecx.expr_match(self.macsp, head, vec![arm])
1079             },
1080         );
1081
1082         // Now create the fmt::Arguments struct with all our locals we created.
1083         let (fn_name, fn_args) = if self.all_pieces_simple {
1084             ("new_v1", vec![pieces, args_slice])
1085         } else {
1086             // Build up the static array which will store our precompiled
1087             // nonstandard placeholders, if there are any.
1088             let fmt = self.ecx.expr_array_ref(self.macsp, self.pieces);
1089
1090             let path = self.ecx.std_path(&[sym::fmt, sym::UnsafeArg, sym::new]);
1091             let unsafe_arg = self.ecx.expr_call_global(self.macsp, path, Vec::new());
1092             let unsafe_expr = self.ecx.expr_block(P(ast::Block {
1093                 stmts: vec![self.ecx.stmt_expr(unsafe_arg)],
1094                 id: ast::DUMMY_NODE_ID,
1095                 rules: BlockCheckMode::Unsafe(UnsafeSource::CompilerGenerated),
1096                 span: self.macsp,
1097                 tokens: None,
1098                 could_be_bare_literal: false,
1099             }));
1100
1101             ("new_v1_formatted", vec![pieces, args_slice, fmt, unsafe_expr])
1102         };
1103
1104         let path = self.ecx.std_path(&[sym::fmt, sym::Arguments, Symbol::intern(fn_name)]);
1105         self.ecx.expr_call_global(self.macsp, path, fn_args)
1106     }
1107
1108     fn format_arg(
1109         ecx: &ExtCtxt<'_>,
1110         macsp: Span,
1111         mut sp: Span,
1112         ty: &ArgumentType,
1113         arg: P<ast::Expr>,
1114     ) -> P<ast::Expr> {
1115         sp = ecx.with_def_site_ctxt(sp);
1116         let trait_ = match *ty {
1117             Placeholder(trait_) if trait_ == "<invalid>" => return DummyResult::raw_expr(sp, true),
1118             Placeholder(trait_) => trait_,
1119             Count => {
1120                 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, sym::from_usize]);
1121                 return ecx.expr_call_global(macsp, path, vec![arg]);
1122             }
1123         };
1124         let new_fn_name = match trait_ {
1125             "Display" => "new_display",
1126             "Debug" => "new_debug",
1127             "LowerExp" => "new_lower_exp",
1128             "UpperExp" => "new_upper_exp",
1129             "Octal" => "new_octal",
1130             "Pointer" => "new_pointer",
1131             "Binary" => "new_binary",
1132             "LowerHex" => "new_lower_hex",
1133             "UpperHex" => "new_upper_hex",
1134             _ => unreachable!(),
1135         };
1136
1137         let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, Symbol::intern(new_fn_name)]);
1138         ecx.expr_call_global(sp, path, vec![arg])
1139     }
1140 }
1141
1142 fn expand_format_args_impl<'cx>(
1143     ecx: &'cx mut ExtCtxt<'_>,
1144     mut sp: Span,
1145     tts: TokenStream,
1146     nl: bool,
1147 ) -> Box<dyn base::MacResult + 'cx> {
1148     sp = ecx.with_def_site_ctxt(sp);
1149     match parse_args(ecx, sp, tts) {
1150         Ok((efmt, args, names)) => {
1151             MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt, args, names, nl))
1152         }
1153         Err(mut err) => {
1154             err.emit();
1155             DummyResult::any(sp)
1156         }
1157     }
1158 }
1159
1160 pub fn expand_format_args<'cx>(
1161     ecx: &'cx mut ExtCtxt<'_>,
1162     sp: Span,
1163     tts: TokenStream,
1164 ) -> Box<dyn base::MacResult + 'cx> {
1165     expand_format_args_impl(ecx, sp, tts, false)
1166 }
1167
1168 pub fn expand_format_args_nl<'cx>(
1169     ecx: &'cx mut ExtCtxt<'_>,
1170     sp: Span,
1171     tts: TokenStream,
1172 ) -> Box<dyn base::MacResult + 'cx> {
1173     expand_format_args_impl(ecx, sp, tts, true)
1174 }
1175
1176 fn create_lints_for_named_arguments_used_positionally(cx: &mut Context<'_, '_>) {
1177     for named_arg in &cx.unused_names_lint.positional_named_args {
1178         let (position_sp_to_replace, position_sp_for_msg) = named_arg.get_positional_arg_spans(cx);
1179
1180         let msg = format!("named argument `{}` is not used by name", named_arg.replacement);
1181
1182         cx.ecx.buffered_early_lint.push(BufferedEarlyLint {
1183             span: MultiSpan::from_span(named_arg.positional_named_arg_span),
1184             msg: msg.into(),
1185             node_id: ast::CRATE_NODE_ID,
1186             lint_id: LintId::of(&NAMED_ARGUMENTS_USED_POSITIONALLY),
1187             diagnostic: BuiltinLintDiagnostics::NamedArgumentUsedPositionally {
1188                 position_sp_to_replace,
1189                 position_sp_for_msg,
1190                 named_arg_sp: named_arg.positional_named_arg_span,
1191                 named_arg_name: named_arg.replacement.to_string(),
1192                 is_formatting_arg: named_arg.ty != PositionalNamedArgType::Arg,
1193             },
1194         });
1195     }
1196 }
1197
1198 /// Take the various parts of `format_args!(efmt, args..., name=names...)`
1199 /// and construct the appropriate formatting expression.
1200 pub fn expand_preparsed_format_args(
1201     ecx: &mut ExtCtxt<'_>,
1202     sp: Span,
1203     efmt: P<ast::Expr>,
1204     args: Vec<FormatArg>,
1205     names: FxHashMap<Symbol, usize>,
1206     append_newline: bool,
1207 ) -> P<ast::Expr> {
1208     // NOTE: this verbose way of initializing `Vec<Vec<ArgumentType>>` is because
1209     // `ArgumentType` does not derive `Clone`.
1210     let arg_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
1211     let arg_unique_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
1212
1213     let mut macsp = ecx.call_site();
1214     macsp = ecx.with_def_site_ctxt(macsp);
1215
1216     let msg = "format argument must be a string literal";
1217     let fmt_sp = efmt.span;
1218     let efmt_kind_is_lit: bool = matches!(efmt.kind, ast::ExprKind::Lit(_));
1219     let (fmt_str, fmt_style, fmt_span) = match expr_to_spanned_string(ecx, efmt, msg) {
1220         Ok(mut fmt) if append_newline => {
1221             fmt.0 = Symbol::intern(&format!("{}\n", fmt.0));
1222             fmt
1223         }
1224         Ok(fmt) => fmt,
1225         Err(err) => {
1226             if let Some((mut err, suggested)) = err {
1227                 let sugg_fmt = match args.len() {
1228                     0 => "{}".to_string(),
1229                     _ => format!("{}{{}}", "{} ".repeat(args.len())),
1230                 };
1231                 if !suggested {
1232                     err.span_suggestion(
1233                         fmt_sp.shrink_to_lo(),
1234                         "you might be missing a string literal to format with",
1235                         format!("\"{}\", ", sugg_fmt),
1236                         Applicability::MaybeIncorrect,
1237                     );
1238                 }
1239                 err.emit();
1240             }
1241             return DummyResult::raw_expr(sp, true);
1242         }
1243     };
1244
1245     let str_style = match fmt_style {
1246         ast::StrStyle::Cooked => None,
1247         ast::StrStyle::Raw(raw) => Some(raw as usize),
1248     };
1249
1250     let fmt_str = fmt_str.as_str(); // for the suggestions below
1251     let fmt_snippet = ecx.source_map().span_to_snippet(fmt_sp).ok();
1252     let mut parser = parse::Parser::new(
1253         fmt_str,
1254         str_style,
1255         fmt_snippet,
1256         append_newline,
1257         parse::ParseMode::Format,
1258     );
1259
1260     let mut unverified_pieces = Vec::new();
1261     while let Some(piece) = parser.next() {
1262         if !parser.errors.is_empty() {
1263             break;
1264         } else {
1265             unverified_pieces.push(piece);
1266         }
1267     }
1268
1269     if !parser.errors.is_empty() {
1270         let err = parser.errors.remove(0);
1271         let sp = if efmt_kind_is_lit {
1272             fmt_span.from_inner(InnerSpan::new(err.span.start, err.span.end))
1273         } else {
1274             // The format string could be another macro invocation, e.g.:
1275             //     format!(concat!("abc", "{}"), 4);
1276             // However, `err.span` is an inner span relative to the *result* of
1277             // the macro invocation, which is why we would get a nonsensical
1278             // result calling `fmt_span.from_inner(err.span)` as above, and
1279             // might even end up inside a multibyte character (issue #86085).
1280             // Therefore, we conservatively report the error for the entire
1281             // argument span here.
1282             fmt_span
1283         };
1284         let mut e = ecx.struct_span_err(sp, &format!("invalid format string: {}", err.description));
1285         e.span_label(sp, err.label + " in format string");
1286         if let Some(note) = err.note {
1287             e.note(&note);
1288         }
1289         if let Some((label, span)) = err.secondary_label {
1290             if efmt_kind_is_lit {
1291                 e.span_label(fmt_span.from_inner(InnerSpan::new(span.start, span.end)), label);
1292             }
1293         }
1294         if err.should_be_replaced_with_positional_argument {
1295             let captured_arg_span =
1296                 fmt_span.from_inner(InnerSpan::new(err.span.start, err.span.end));
1297             let n_positional_args =
1298                 args.iter().rposition(|arg| arg.name.is_none()).map_or(0, |i| i + 1);
1299             if let Ok(arg) = ecx.source_map().span_to_snippet(captured_arg_span) {
1300                 let span = match args[..n_positional_args].last() {
1301                     Some(arg) => arg.expr.span,
1302                     None => fmt_sp,
1303                 };
1304                 e.multipart_suggestion_verbose(
1305                     "consider using a positional formatting argument instead",
1306                     vec![
1307                         (captured_arg_span, n_positional_args.to_string()),
1308                         (span.shrink_to_hi(), format!(", {}", arg)),
1309                     ],
1310                     Applicability::MachineApplicable,
1311                 );
1312             }
1313         }
1314         e.emit();
1315         return DummyResult::raw_expr(sp, true);
1316     }
1317
1318     let arg_spans = parser
1319         .arg_places
1320         .iter()
1321         .map(|span| fmt_span.from_inner(InnerSpan::new(span.start, span.end)))
1322         .collect();
1323
1324     let mut cx = Context {
1325         ecx,
1326         args,
1327         num_captured_args: 0,
1328         arg_types,
1329         arg_unique_types,
1330         names,
1331         curarg: 0,
1332         curpiece: 0,
1333         arg_index_map: Vec::new(),
1334         count_args: Vec::new(),
1335         count_positions: FxHashMap::default(),
1336         count_positions_count: 0,
1337         count_args_index_offset: 0,
1338         literal: String::new(),
1339         pieces: Vec::with_capacity(unverified_pieces.len()),
1340         str_pieces: Vec::with_capacity(unverified_pieces.len()),
1341         all_pieces_simple: true,
1342         macsp,
1343         fmtsp: fmt_span,
1344         invalid_refs: Vec::new(),
1345         arg_spans,
1346         arg_with_formatting: Vec::new(),
1347         is_literal: parser.is_literal,
1348         unused_names_lint: PositionalNamedArgsLint { positional_named_args: vec![] },
1349     };
1350
1351     // This needs to happen *after* the Parser has consumed all pieces to create all the spans
1352     let pieces = unverified_pieces
1353         .into_iter()
1354         .map(|mut piece| {
1355             cx.verify_piece(&piece);
1356             cx.resolve_name_inplace(&mut piece);
1357             piece
1358         })
1359         .collect::<Vec<_>>();
1360
1361     let numbered_position_args = pieces.iter().any(|arg: &parse::Piece<'_>| match *arg {
1362         parse::String(_) => false,
1363         parse::NextArgument(arg) => matches!(arg.position, parse::Position::ArgumentIs(..)),
1364     });
1365
1366     cx.build_index_map();
1367
1368     let mut arg_index_consumed = vec![0usize; cx.arg_index_map.len()];
1369
1370     for piece in pieces {
1371         if let Some(piece) = cx.build_piece(&piece, &mut arg_index_consumed) {
1372             let s = cx.build_literal_string();
1373             cx.str_pieces.push(s);
1374             cx.pieces.push(piece);
1375         }
1376     }
1377
1378     if !cx.literal.is_empty() {
1379         let s = cx.build_literal_string();
1380         cx.str_pieces.push(s);
1381     }
1382
1383     if !cx.invalid_refs.is_empty() {
1384         cx.report_invalid_references(numbered_position_args);
1385     }
1386
1387     // Make sure that all arguments were used and all arguments have types.
1388     let errs = cx
1389         .arg_types
1390         .iter()
1391         .enumerate()
1392         .filter(|(i, ty)| ty.is_empty() && !cx.count_positions.contains_key(&i))
1393         .map(|(i, _)| {
1394             let msg = if cx.args[i].name.is_some() {
1395                 "named argument never used"
1396             } else {
1397                 "argument never used"
1398             };
1399             (cx.args[i].expr.span, msg)
1400         })
1401         .collect::<Vec<_>>();
1402
1403     let errs_len = errs.len();
1404     if !errs.is_empty() {
1405         let args_used = cx.arg_types.len() - errs_len;
1406         let args_unused = errs_len;
1407
1408         let mut diag = {
1409             if let [(sp, msg)] = &errs[..] {
1410                 let mut diag = cx.ecx.struct_span_err(*sp, *msg);
1411                 diag.span_label(*sp, *msg);
1412                 diag
1413             } else {
1414                 let mut diag = cx.ecx.struct_span_err(
1415                     errs.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
1416                     "multiple unused formatting arguments",
1417                 );
1418                 diag.span_label(cx.fmtsp, "multiple missing formatting specifiers");
1419                 for (sp, msg) in errs {
1420                     diag.span_label(sp, msg);
1421                 }
1422                 diag
1423             }
1424         };
1425
1426         // Used to ensure we only report translations for *one* kind of foreign format.
1427         let mut found_foreign = false;
1428         // Decide if we want to look for foreign formatting directives.
1429         if args_used < args_unused {
1430             use super::format_foreign as foreign;
1431
1432             // The set of foreign substitutions we've explained.  This prevents spamming the user
1433             // with `%d should be written as {}` over and over again.
1434             let mut explained = FxHashSet::default();
1435
1436             macro_rules! check_foreign {
1437                 ($kind:ident) => {{
1438                     let mut show_doc_note = false;
1439
1440                     let mut suggestions = vec![];
1441                     // account for `"` and account for raw strings `r#`
1442                     let padding = str_style.map(|i| i + 2).unwrap_or(1);
1443                     for sub in foreign::$kind::iter_subs(fmt_str, padding) {
1444                         let (trn, success) = match sub.translate() {
1445                             Ok(trn) => (trn, true),
1446                             Err(Some(msg)) => (msg, false),
1447
1448                             // If it has no translation, don't call it out specifically.
1449                             _ => continue,
1450                         };
1451
1452                         let pos = sub.position();
1453                         let sub = String::from(sub.as_str());
1454                         if explained.contains(&sub) {
1455                             continue;
1456                         }
1457                         explained.insert(sub.clone());
1458
1459                         if !found_foreign {
1460                             found_foreign = true;
1461                             show_doc_note = true;
1462                         }
1463
1464                         if let Some(inner_sp) = pos {
1465                             let sp = fmt_sp.from_inner(inner_sp);
1466
1467                             if success {
1468                                 suggestions.push((sp, trn));
1469                             } else {
1470                                 diag.span_note(
1471                                     sp,
1472                                     &format!("format specifiers use curly braces, and {}", trn),
1473                                 );
1474                             }
1475                         } else {
1476                             if success {
1477                                 diag.help(&format!("`{}` should be written as `{}`", sub, trn));
1478                             } else {
1479                                 diag.note(&format!(
1480                                     "`{}` should use curly braces, and {}",
1481                                     sub, trn
1482                                 ));
1483                             }
1484                         }
1485                     }
1486
1487                     if show_doc_note {
1488                         diag.note(concat!(
1489                             stringify!($kind),
1490                             " formatting not supported; see the documentation for `std::fmt`",
1491                         ));
1492                     }
1493                     if suggestions.len() > 0 {
1494                         diag.multipart_suggestion(
1495                             "format specifiers use curly braces",
1496                             suggestions,
1497                             Applicability::MachineApplicable,
1498                         );
1499                     }
1500                 }};
1501             }
1502
1503             check_foreign!(printf);
1504             if !found_foreign {
1505                 check_foreign!(shell);
1506             }
1507         }
1508         if !found_foreign && errs_len == 1 {
1509             diag.span_label(cx.fmtsp, "formatting specifier missing");
1510         }
1511
1512         diag.emit();
1513     } else if cx.invalid_refs.is_empty() && cx.ecx.sess.err_count() == 0 {
1514         // Only check for unused named argument names if there are no other errors to avoid causing
1515         // too much noise in output errors, such as when a named argument is entirely unused.
1516         create_lints_for_named_arguments_used_positionally(&mut cx);
1517     }
1518
1519     cx.into_expr()
1520 }
1521
1522 fn may_contain_yield_point(e: &ast::Expr) -> bool {
1523     struct MayContainYieldPoint(bool);
1524
1525     impl Visitor<'_> for MayContainYieldPoint {
1526         fn visit_expr(&mut self, e: &ast::Expr) {
1527             if let ast::ExprKind::Await(_) | ast::ExprKind::Yield(_) = e.kind {
1528                 self.0 = true;
1529             } else {
1530                 visit::walk_expr(self, e);
1531             }
1532         }
1533
1534         fn visit_mac_call(&mut self, _: &ast::MacCall) {
1535             self.0 = true;
1536         }
1537
1538         fn visit_attribute(&mut self, _: &ast::Attribute) {
1539             // Conservatively assume this may be a proc macro attribute in
1540             // expression position.
1541             self.0 = true;
1542         }
1543
1544         fn visit_item(&mut self, _: &ast::Item) {
1545             // Do not recurse into nested items.
1546         }
1547     }
1548
1549     let mut visitor = MayContainYieldPoint(false);
1550     visitor.visit_expr(e);
1551     visitor.0
1552 }