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