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