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