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