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