]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/format.rs
Rollup merge of #57920 - euclio:source-date-epoch, r=Mark-Simulacrum
[rust.git] / src / libsyntax_ext / format.rs
1 use self::ArgumentType::*;
2 use self::Position::*;
3
4 use fmt_macros as parse;
5
6 use errors::DiagnosticBuilder;
7 use syntax::ast;
8 use syntax::ext::base::{self, *};
9 use syntax::ext::build::AstBuilder;
10 use syntax::feature_gate;
11 use syntax::parse::token;
12 use syntax::ptr::P;
13 use syntax::symbol::Symbol;
14 use syntax::tokenstream;
15 use syntax_pos::{MultiSpan, Span, DUMMY_SP};
16 use errors::Applicability;
17
18 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
19 use std::borrow::Cow;
20 use std::collections::hash_map::Entry;
21
22 #[derive(PartialEq)]
23 enum ArgumentType {
24     Placeholder(String),
25     Count,
26 }
27
28 enum Position {
29     Exact(usize),
30     Named(String),
31 }
32
33 struct Context<'a, 'b: 'a> {
34     ecx: &'a mut ExtCtxt<'b>,
35     /// The macro's call site. References to unstable formatting internals must
36     /// use this span to pass the stability checker.
37     macsp: Span,
38     /// The span of the format string literal.
39     fmtsp: Span,
40
41     /// List of parsed argument expressions.
42     /// Named expressions are resolved early, and are appended to the end of
43     /// argument expressions.
44     ///
45     /// Example showing the various data structures in motion:
46     ///
47     /// * Original: `"{foo:o} {:o} {foo:x} {0:x} {1:o} {:x} {1:x} {0:o}"`
48     /// * Implicit argument resolution: `"{foo:o} {0:o} {foo:x} {0:x} {1:o} {1:x} {1:x} {0:o}"`
49     /// * Name resolution: `"{2:o} {0:o} {2:x} {0:x} {1:o} {1:x} {1:x} {0:o}"`
50     /// * `arg_types` (in JSON): `[[0, 1, 0], [0, 1, 1], [0, 1]]`
51     /// * `arg_unique_types` (in simplified JSON): `[["o", "x"], ["o", "x"], ["o", "x"]]`
52     /// * `names` (in JSON): `{"foo": 2}`
53     args: Vec<P<ast::Expr>>,
54     /// Placeholder slot numbers indexed by argument.
55     arg_types: Vec<Vec<usize>>,
56     /// Unique format specs seen for each argument.
57     arg_unique_types: Vec<Vec<ArgumentType>>,
58     /// Map from named arguments to their resolved indices.
59     names: FxHashMap<String, usize>,
60
61     /// The latest consecutive literal strings, or empty if there weren't any.
62     literal: String,
63
64     /// Collection of the compiled `rt::Argument` structures
65     pieces: Vec<P<ast::Expr>>,
66     /// Collection of string literals
67     str_pieces: Vec<P<ast::Expr>>,
68     /// Stays `true` if all formatting parameters are default (as in "{}{}").
69     all_pieces_simple: bool,
70
71     /// Mapping between positional argument references and indices into the
72     /// final generated static argument array. We record the starting indices
73     /// corresponding to each positional argument, and number of references
74     /// consumed so far for each argument, to facilitate correct `Position`
75     /// mapping in `build_piece`. In effect this can be seen as a "flattened"
76     /// version of `arg_unique_types`.
77     ///
78     /// Again with the example described above in docstring for `args`:
79     ///
80     /// * `arg_index_map` (in JSON): `[[0, 1, 0], [2, 3, 3], [4, 5]]`
81     arg_index_map: Vec<Vec<usize>>,
82
83     /// Starting offset of count argument slots.
84     count_args_index_offset: usize,
85
86     /// Count argument slots and tracking data structures.
87     /// Count arguments are separately tracked for de-duplication in case
88     /// multiple references are made to one argument. For example, in this
89     /// format string:
90     ///
91     /// * Original: `"{:.*} {:.foo$} {1:.*} {:.0$}"`
92     /// * Implicit argument resolution: `"{1:.0$} {2:.foo$} {1:.3$} {4:.0$}"`
93     /// * Name resolution: `"{1:.0$} {2:.5$} {1:.3$} {4:.0$}"`
94     /// * `count_positions` (in JSON): `{0: 0, 5: 1, 3: 2}`
95     /// * `count_args`: `vec![Exact(0), Exact(5), Exact(3)]`
96     count_args: Vec<Position>,
97     /// Relative slot numbers for count arguments.
98     count_positions: FxHashMap<usize, usize>,
99     /// Number of count slots assigned.
100     count_positions_count: usize,
101
102     /// Current position of the implicit positional arg pointer, as if it
103     /// still existed in this phase of processing.
104     /// Used only for `all_pieces_simple` tracking in `build_piece`.
105     curarg: usize,
106     /// Current piece being evaluated, used for error reporting.
107     curpiece: usize,
108     /// Keep track of invalid references to positional arguments.
109     invalid_refs: Vec<(usize, usize)>,
110     /// Spans of all the formatting arguments, in order.
111     arg_spans: Vec<Span>,
112     /// Whether this formatting string is a literal or it comes from a macro.
113     is_literal: bool,
114 }
115
116 /// Parses the arguments from the given list of tokens, returning the diagnostic
117 /// if there's a parse error so we can continue parsing other format!
118 /// expressions.
119 ///
120 /// If parsing succeeds, the return value is:
121 ///
122 /// ```text
123 /// Some((fmtstr, parsed arguments, index map for named arguments))
124 /// ```
125 fn parse_args<'a>(
126     ecx: &mut ExtCtxt<'a>,
127     sp: Span,
128     tts: &[tokenstream::TokenTree]
129 ) -> Result<(P<ast::Expr>, Vec<P<ast::Expr>>, FxHashMap<String, usize>), DiagnosticBuilder<'a>> {
130     let mut args = Vec::<P<ast::Expr>>::new();
131     let mut names = FxHashMap::<String, usize>::default();
132
133     let mut p = ecx.new_parser_from_tts(tts);
134
135     if p.token == token::Eof {
136         return Err(ecx.struct_span_err(sp, "requires at least a format string argument"));
137     }
138
139     let fmtstr = p.parse_expr()?;
140     let mut named = false;
141
142     while p.token != token::Eof {
143         if !p.eat(&token::Comma) {
144             return Err(ecx.struct_span_err(p.span, "expected token: `,`"));
145         }
146         if p.token == token::Eof {
147             break;
148         } // accept trailing commas
149         if named || (p.token.is_ident() && p.look_ahead(1, |t| *t == token::Eq)) {
150             named = true;
151             let ident = if let token::Ident(i, _) = p.token {
152                 p.bump();
153                 i
154             } else {
155                 return Err(ecx.struct_span_err(
156                     p.span,
157                     "expected ident, positional arguments cannot follow named arguments",
158                 ));
159             };
160             let name: &str = &ident.as_str();
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.to_string(), 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| *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.to_string()),
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.to_string()), 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(&["fmt", "rt", "v1", 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     /// Build 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(&["fmt", "Arguments", 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(&["fmt", "ArgumentV1", "from_usize"]);
678                 return ecx.expr_call_global(macsp, path, vec![arg]);
679             }
680         };
681
682         let path = ecx.std_path(&["fmt", trait_, "fmt"]);
683         let format_fn = ecx.path_global(sp, path);
684         let path = ecx.std_path(&["fmt", "ArgumentV1", "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()   // the enclosing span is marked as `#[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                                        "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<String, 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     /// Find 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_byte_pos(err.start.unwrap(), err.end.unwrap());
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, start, end)) = err.secondary_label {
911             let sp = fmt.span.from_inner_byte_pos(start.unwrap(), end.unwrap());
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(|&(parse::SpanIndex(start), parse::SpanIndex(end))| {
920             fmt.span.from_inner_byte_pos(start, end)
921         })
922         .collect();
923
924     let mut cx = Context {
925         ecx,
926         args,
927         arg_types,
928         arg_unique_types,
929         names,
930         curarg: 0,
931         curpiece: 0,
932         arg_index_map: Vec::new(),
933         count_args: Vec::new(),
934         count_positions: FxHashMap::default(),
935         count_positions_count: 0,
936         count_args_index_offset: 0,
937         literal: String::new(),
938         pieces: Vec::with_capacity(unverified_pieces.len()),
939         str_pieces: Vec::with_capacity(unverified_pieces.len()),
940         all_pieces_simple: true,
941         macsp,
942         fmtsp: fmt.span,
943         invalid_refs: Vec::new(),
944         arg_spans,
945         is_literal,
946     };
947
948     // This needs to happen *after* the Parser has consumed all pieces to create all the spans
949     let pieces = unverified_pieces.into_iter().map(|mut piece| {
950         cx.verify_piece(&piece);
951         cx.resolve_name_inplace(&mut piece);
952         piece
953     }).collect::<Vec<_>>();
954
955     let numbered_position_args = pieces.iter().any(|arg: &parse::Piece| {
956         match *arg {
957             parse::String(_) => false,
958             parse::NextArgument(arg) => {
959                 match arg.position {
960                     parse::Position::ArgumentIs(_) => true,
961                     _ => false,
962                 }
963             }
964         }
965     });
966
967     cx.build_index_map();
968
969     let mut arg_index_consumed = vec![0usize; cx.arg_index_map.len()];
970
971     for piece in pieces {
972         if let Some(piece) = cx.build_piece(&piece, &mut arg_index_consumed) {
973             let s = cx.build_literal_string();
974             cx.str_pieces.push(s);
975             cx.pieces.push(piece);
976         }
977     }
978
979     if !cx.literal.is_empty() {
980         let s = cx.build_literal_string();
981         cx.str_pieces.push(s);
982     }
983
984     if cx.invalid_refs.len() >= 1 {
985         cx.report_invalid_references(numbered_position_args);
986     }
987
988     // Make sure that all arguments were used and all arguments have types.
989     let num_pos_args = cx.args.len() - cx.names.len();
990
991     let errs = cx.arg_types
992                  .iter()
993                  .enumerate()
994                  .filter(|(i, ty)| ty.is_empty() && !cx.count_positions.contains_key(&i))
995                  .map(|(i, _)| {
996                     let msg = if i >= num_pos_args {
997                         // named argument
998                         "named argument never used"
999                     } else {
1000                         // positional argument
1001                         "argument never used"
1002                     };
1003                     (cx.args[i].span, msg)
1004                  })
1005                  .collect::<Vec<_>>();
1006
1007     let errs_len = errs.len();
1008     if !errs.is_empty() {
1009         let args_used = cx.arg_types.len() - errs_len;
1010         let args_unused = errs_len;
1011
1012         let mut diag = {
1013             if errs_len == 1 {
1014                 let (sp, msg) = errs.into_iter().next().unwrap();
1015                 let mut diag = cx.ecx.struct_span_err(sp, msg);
1016                 diag.span_label(sp, msg);
1017                 diag
1018             } else {
1019                 let mut diag = cx.ecx.struct_span_err(
1020                     errs.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
1021                     "multiple unused formatting arguments",
1022                 );
1023                 diag.span_label(cx.fmtsp, "multiple missing formatting specifiers");
1024                 for (sp, msg) in errs {
1025                     diag.span_label(sp, msg);
1026                 }
1027                 diag
1028             }
1029         };
1030
1031         // Used to ensure we only report translations for *one* kind of foreign format.
1032         let mut found_foreign = false;
1033         // Decide if we want to look for foreign formatting directives.
1034         if args_used < args_unused {
1035             use super::format_foreign as foreign;
1036
1037             // The set of foreign substitutions we've explained.  This prevents spamming the user
1038             // with `%d should be written as {}` over and over again.
1039             let mut explained = FxHashSet::default();
1040
1041             macro_rules! check_foreign {
1042                 ($kind:ident) => {{
1043                     let mut show_doc_note = false;
1044
1045                     let mut suggestions = vec![];
1046                     for sub in foreign::$kind::iter_subs(fmt_str) {
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((start, end)) = pos {
1067                             // account for `"` and account for raw strings `r#`
1068                             let padding = str_style.map(|i| i + 2).unwrap_or(1);
1069                             let sp = fmt_sp.from_inner_byte_pos(start + padding, end + padding);
1070                             suggestions.push((sp, trn));
1071                         } else {
1072                             diag.help(&format!("`{}` should be written as `{}`", sub, trn));
1073                         }
1074                     }
1075
1076                     if show_doc_note {
1077                         diag.note(concat!(
1078                             stringify!($kind),
1079                             " formatting not supported; see the documentation for `std::fmt`",
1080                         ));
1081                     }
1082                     if suggestions.len() > 0 {
1083                         diag.multipart_suggestion(
1084                             "format specifiers use curly braces",
1085                             suggestions,
1086                             Applicability::MachineApplicable,
1087                         );
1088                     }
1089                 }};
1090             }
1091
1092             check_foreign!(printf);
1093             if !found_foreign {
1094                 check_foreign!(shell);
1095             }
1096         }
1097         if !found_foreign && errs_len == 1 {
1098             diag.span_label(cx.fmtsp, "formatting specifier missing");
1099         }
1100
1101         diag.emit();
1102     }
1103
1104     cx.into_expr()
1105 }