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