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