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