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