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