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