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