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