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