1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use self::ArgumentType::*;
12 use self::Position::*;
14 use fmt_macros as parse;
17 use syntax::ext::base::{self, *};
18 use syntax::ext::build::AstBuilder;
19 use syntax::feature_gate;
20 use syntax::parse::token;
22 use syntax::symbol::Symbol;
23 use syntax::tokenstream;
24 use syntax_pos::{MultiSpan, Span, DUMMY_SP};
25 use errors::Applicability;
27 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
29 use std::collections::hash_map::Entry;
42 struct Context<'a, 'b: 'a> {
43 ecx: &'a mut ExtCtxt<'b>,
44 /// The macro's call site. References to unstable formatting internals must
45 /// use this span to pass the stability checker.
47 /// The span of the format string literal.
50 /// List of parsed argument expressions.
51 /// Named expressions are resolved early, and are appended to the end of
52 /// argument expressions.
54 /// Example showing the various data structures in motion:
56 /// * Original: `"{foo:o} {:o} {foo:x} {0:x} {1:o} {:x} {1:x} {0:o}"`
57 /// * Implicit argument resolution: `"{foo:o} {0:o} {foo:x} {0:x} {1:o} {1:x} {1:x} {0:o}"`
58 /// * Name resolution: `"{2:o} {0:o} {2:x} {0:x} {1:o} {1:x} {1:x} {0:o}"`
59 /// * `arg_types` (in JSON): `[[0, 1, 0], [0, 1, 1], [0, 1]]`
60 /// * `arg_unique_types` (in simplified JSON): `[["o", "x"], ["o", "x"], ["o", "x"]]`
61 /// * `names` (in JSON): `{"foo": 2}`
62 args: Vec<P<ast::Expr>>,
63 /// Placeholder slot numbers indexed by argument.
64 arg_types: Vec<Vec<usize>>,
65 /// Unique format specs seen for each argument.
66 arg_unique_types: Vec<Vec<ArgumentType>>,
67 /// Map from named arguments to their resolved indices.
68 names: FxHashMap<String, usize>,
70 /// The latest consecutive literal strings, or empty if there weren't any.
73 /// Collection of the compiled `rt::Argument` structures
74 pieces: Vec<P<ast::Expr>>,
75 /// Collection of string literals
76 str_pieces: Vec<P<ast::Expr>>,
77 /// Stays `true` if all formatting parameters are default (as in "{}{}").
78 all_pieces_simple: bool,
80 /// Mapping between positional argument references and indices into the
81 /// final generated static argument array. We record the starting indices
82 /// corresponding to each positional argument, and number of references
83 /// consumed so far for each argument, to facilitate correct `Position`
84 /// mapping in `build_piece`. In effect this can be seen as a "flattened"
85 /// version of `arg_unique_types`.
87 /// Again with the example described above in docstring for `args`:
89 /// * `arg_index_map` (in JSON): `[[0, 1, 0], [2, 3, 3], [4, 5]]`
90 arg_index_map: Vec<Vec<usize>>,
92 /// Starting offset of count argument slots.
93 count_args_index_offset: usize,
95 /// Count argument slots and tracking data structures.
96 /// Count arguments are separately tracked for de-duplication in case
97 /// multiple references are made to one argument. For example, in this
100 /// * Original: `"{:.*} {:.foo$} {1:.*} {:.0$}"`
101 /// * Implicit argument resolution: `"{1:.0$} {2:.foo$} {1:.3$} {4:.0$}"`
102 /// * Name resolution: `"{1:.0$} {2:.5$} {1:.3$} {4:.0$}"`
103 /// * `count_positions` (in JSON): `{0: 0, 5: 1, 3: 2}`
104 /// * `count_args`: `vec![Exact(0), Exact(5), Exact(3)]`
105 count_args: Vec<Position>,
106 /// Relative slot numbers for count arguments.
107 count_positions: FxHashMap<usize, usize>,
108 /// Number of count slots assigned.
109 count_positions_count: usize,
111 /// Current position of the implicit positional arg pointer, as if it
112 /// still existed in this phase of processing.
113 /// Used only for `all_pieces_simple` tracking in `build_piece`.
115 /// Current piece being evaluated, used for error reporting.
117 /// Keep track of invalid references to positional arguments.
118 invalid_refs: Vec<(usize, usize)>,
119 /// Spans of all the formatting arguments, in order.
120 arg_spans: Vec<Span>,
121 /// Whether this formatting string is a literal or it comes from a macro.
125 /// Parses the arguments from the given list of tokens, returning None
126 /// if there's a parse error so we can continue parsing other format!
129 /// If parsing succeeds, the return value is:
132 /// Some((fmtstr, parsed arguments, index map for named arguments))
134 fn parse_args(ecx: &mut ExtCtxt,
136 tts: &[tokenstream::TokenTree])
137 -> Option<(P<ast::Expr>, Vec<P<ast::Expr>>, FxHashMap<String, usize>)> {
138 let mut args = Vec::<P<ast::Expr>>::new();
139 let mut names = FxHashMap::<String, usize>::default();
141 let mut p = ecx.new_parser_from_tts(tts);
143 if p.token == token::Eof {
144 ecx.span_err(sp, "requires at least a format string argument");
148 let fmtstr = panictry!(p.parse_expr());
149 let mut named = false;
151 while p.token != token::Eof {
152 if !p.eat(&token::Comma) {
153 ecx.span_err(p.span, "expected token: `,`");
156 if p.token == token::Eof {
158 } // accept trailing commas
159 if named || (p.token.is_ident() && p.look_ahead(1, |t| *t == token::Eq)) {
161 let ident = match p.token {
162 token::Ident(i, _) => {
169 "expected ident, positional arguments cannot follow named arguments",
177 "expected ident for named argument, found `{}`",
178 p.this_token_to_string()
184 let name: &str = &ident.as_str();
186 panictry!(p.expect(&token::Eq));
187 let e = panictry!(p.parse_expr());
188 if let Some(prev) = names.get(name) {
189 ecx.struct_span_err(e.span, &format!("duplicate argument named `{}`", name))
190 .span_note(args[*prev].span, "previously here")
195 // Resolve names into slots early.
196 // Since all the positional args are already seen at this point
197 // if the input is valid, we can simply append to the positional
198 // args. And remember the names.
199 let slot = args.len();
200 names.insert(name.to_string(), slot);
203 args.push(panictry!(p.parse_expr()));
206 Some((fmtstr, args, names))
209 impl<'a, 'b> Context<'a, 'b> {
210 fn resolve_name_inplace(&self, p: &mut parse::Piece) {
211 // NOTE: the `unwrap_or` branch is needed in case of invalid format
212 // arguments, e.g. `format_args!("{foo}")`.
213 let lookup = |s| *self.names.get(s).unwrap_or(&0);
216 parse::String(_) => {}
217 parse::NextArgument(ref mut arg) => {
218 if let parse::ArgumentNamed(s) = arg.position {
219 arg.position = parse::ArgumentIs(lookup(s));
221 if let parse::CountIsName(s) = arg.format.width {
222 arg.format.width = parse::CountIsParam(lookup(s));
224 if let parse::CountIsName(s) = arg.format.precision {
225 arg.format.precision = parse::CountIsParam(lookup(s));
231 /// Verifies one piece of a parse string, and remembers it if valid.
232 /// All errors are not emitted as fatal so we can continue giving errors
233 /// about this and possibly other format strings.
234 fn verify_piece(&mut self, p: &parse::Piece) {
236 parse::String(..) => {}
237 parse::NextArgument(ref arg) => {
238 // width/precision first, if they have implicit positional
239 // parameters it makes more sense to consume them first.
240 self.verify_count(arg.format.width);
241 self.verify_count(arg.format.precision);
243 // argument second, if it's an implicit positional parameter
244 // it's written second, so it should come after width/precision.
245 let pos = match arg.position {
246 parse::ArgumentIs(i) | parse::ArgumentImplicitlyIs(i) => Exact(i),
247 parse::ArgumentNamed(s) => Named(s.to_string()),
250 let ty = Placeholder(arg.format.ty.to_string());
251 self.verify_arg_type(pos, ty);
257 fn verify_count(&mut self, c: parse::Count) {
259 parse::CountImplied |
260 parse::CountIs(..) => {}
261 parse::CountIsParam(i) => {
262 self.verify_arg_type(Exact(i), Count);
264 parse::CountIsName(s) => {
265 self.verify_arg_type(Named(s.to_string()), Count);
270 fn describe_num_args(&self) -> Cow<str> {
271 match self.args.len() {
272 0 => "no arguments were given".into(),
273 1 => "there is 1 argument".into(),
274 x => format!("there are {} arguments", x).into(),
278 /// Handle invalid references to positional arguments. Output different
279 /// errors for the case where all arguments are positional and for when
280 /// there are named arguments or numbered positional arguments in the
282 fn report_invalid_references(&self, numbered_position_args: bool) {
284 let sp = if self.is_literal {
285 MultiSpan::from_spans(self.arg_spans.clone())
287 MultiSpan::from_span(self.fmtsp)
289 let mut refs: Vec<_> = self
292 .map(|(r, pos)| (r.to_string(), self.arg_spans.get(*pos)))
295 if self.names.is_empty() && !numbered_position_args {
296 e = self.ecx.mut_span_err(
299 "{} positional argument{} in format string, but {}",
301 if self.pieces.len() > 1 { "s" } else { "" },
302 self.describe_num_args()
306 let (arg_list, mut sp) = match refs.len() {
308 let (reg, pos) = refs.pop().unwrap();
310 format!("argument {}", reg),
311 MultiSpan::from_span(*pos.unwrap_or(&self.fmtsp)),
316 MultiSpan::from_spans(refs.iter().map(|(_, p)| *p.unwrap()).collect());
317 let mut refs: Vec<String> = refs.iter().map(|(s, _)| s.to_owned()).collect();
318 let reg = refs.pop().unwrap();
321 "arguments {head} and {tail}",
323 head = refs.join(", ")
329 if !self.is_literal {
330 sp = MultiSpan::from_span(self.fmtsp);
333 e = self.ecx.mut_span_err(sp,
334 &format!("invalid reference to positional {} ({})",
336 self.describe_num_args()));
337 e.note("positional arguments are zero-based");
343 /// Actually verifies and tracks a given format placeholder
344 /// (a.k.a. argument).
345 fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
348 if self.args.len() <= arg {
349 self.invalid_refs.push((arg, self.curpiece));
354 // record every (position, type) combination only once
355 let ref mut seen_ty = self.arg_unique_types[arg];
356 let i = match seen_ty.iter().position(|x| *x == ty) {
359 let i = seen_ty.len();
364 self.arg_types[arg].push(i);
367 match self.count_positions.entry(arg) {
368 Entry::Vacant(e) => {
369 let i = self.count_positions_count;
371 self.count_args.push(Exact(arg));
372 self.count_positions_count += 1;
374 Entry::Occupied(_) => {}
381 let idx = match self.names.get(&name) {
384 let msg = format!("there is no argument named `{}`", name);
385 let sp = if self.is_literal {
386 *self.arg_spans.get(self.curpiece).unwrap_or(&self.fmtsp)
390 let mut err = self.ecx.struct_span_err(sp, &msg[..]);
395 // Treat as positional arg.
396 self.verify_arg_type(Exact(idx), ty)
401 /// Builds the mapping between format placeholders and argument objects.
402 fn build_index_map(&mut self) {
403 // NOTE: Keep the ordering the same as `into_expr`'s expansion would do!
404 let args_len = self.args.len();
405 self.arg_index_map.reserve(args_len);
407 let mut sofar = 0usize;
410 for i in 0..args_len {
411 let ref arg_types = self.arg_types[i];
412 let arg_offsets = arg_types.iter().map(|offset| sofar + *offset).collect::<Vec<_>>();
413 self.arg_index_map.push(arg_offsets);
414 sofar += self.arg_unique_types[i].len();
417 // Record starting index for counts, which appear just after arguments
418 self.count_args_index_offset = sofar;
421 fn rtpath(ecx: &ExtCtxt, s: &str) -> Vec<ast::Ident> {
422 ecx.std_path(&["fmt", "rt", "v1", s])
425 fn build_count(&self, c: parse::Count) -> P<ast::Expr> {
427 let count = |c, arg| {
428 let mut path = Context::rtpath(self.ecx, "Count");
429 path.push(self.ecx.ident_of(c));
431 Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]),
432 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
436 parse::CountIs(i) => count("Is", Some(self.ecx.expr_usize(sp, i))),
437 parse::CountIsParam(i) => {
438 // This needs mapping too, as `i` is referring to a macro
440 let i = match self.count_positions.get(&i) {
442 None => 0, // error already emitted elsewhere
444 let i = i + self.count_args_index_offset;
445 count("Param", Some(self.ecx.expr_usize(sp, i)))
447 parse::CountImplied => count("Implied", None),
448 // should never be the case, names are already resolved
449 parse::CountIsName(_) => panic!("should never happen"),
453 /// Build a literal expression from the accumulated string literals
454 fn build_literal_string(&mut self) -> P<ast::Expr> {
456 let s = Symbol::intern(&self.literal);
457 self.literal.clear();
458 self.ecx.expr_str(sp, s)
461 /// Build a static `rt::Argument` from a `parse::Piece` or append
462 /// to the `literal` string.
463 fn build_piece(&mut self,
464 piece: &parse::Piece,
465 arg_index_consumed: &mut Vec<usize>)
466 -> Option<P<ast::Expr>> {
469 parse::String(s) => {
470 self.literal.push_str(s);
473 parse::NextArgument(ref arg) => {
474 // Build the position
477 let mut path = Context::rtpath(self.ecx, "Position");
478 path.push(self.ecx.ident_of(c));
481 let arg = self.ecx.expr_usize(sp, i);
482 self.ecx.expr_call_global(sp, path, vec![arg])
484 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
489 | parse::ArgumentImplicitlyIs(i) => {
490 // Map to index in final generated argument array
491 // in case of multiple types specified
492 let arg_idx = match arg_index_consumed.get_mut(i) {
493 None => 0, // error already emitted elsewhere
495 let ref idx_map = self.arg_index_map[i];
496 // unwrap_or branch: error already emitted elsewhere
497 let arg_idx = *idx_map.get(*offset).unwrap_or(&0);
502 pos("At", Some(arg_idx))
505 // should never be the case, because names are already
507 parse::ArgumentNamed(_) => panic!("should never happen"),
511 let simple_arg = parse::Argument {
513 // We don't have ArgumentNext any more, so we have to
514 // track the current argument ourselves.
519 format: parse::FormatSpec {
520 fill: arg.format.fill,
521 align: parse::AlignUnknown,
523 precision: parse::CountImplied,
524 width: parse::CountImplied,
529 let fill = match arg.format.fill {
534 if *arg != simple_arg || fill != ' ' {
535 self.all_pieces_simple = false;
539 let fill = self.ecx.expr_lit(sp, ast::LitKind::Char(fill));
541 let mut p = Context::rtpath(self.ecx, "Alignment");
542 p.push(self.ecx.ident_of(name));
543 self.ecx.path_global(sp, p)
545 let align = match arg.format.align {
546 parse::AlignLeft => align("Left"),
547 parse::AlignRight => align("Right"),
548 parse::AlignCenter => align("Center"),
549 parse::AlignUnknown => align("Unknown"),
551 let align = self.ecx.expr_path(align);
552 let flags = self.ecx.expr_u32(sp, arg.format.flags);
553 let prec = self.build_count(arg.format.precision);
554 let width = self.build_count(arg.format.width);
555 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "FormatSpec"));
556 let fmt = self.ecx.expr_struct(
560 self.ecx.field_imm(sp, self.ecx.ident_of("fill"), fill),
561 self.ecx.field_imm(sp, self.ecx.ident_of("align"), align),
562 self.ecx.field_imm(sp, self.ecx.ident_of("flags"), flags),
563 self.ecx.field_imm(sp, self.ecx.ident_of("precision"), prec),
564 self.ecx.field_imm(sp, self.ecx.ident_of("width"), width),
568 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "Argument"));
569 Some(self.ecx.expr_struct(
573 self.ecx.field_imm(sp, self.ecx.ident_of("position"), pos),
574 self.ecx.field_imm(sp, self.ecx.ident_of("format"), fmt),
581 /// Actually builds the expression which the format_args! block will be
583 fn into_expr(self) -> P<ast::Expr> {
584 let mut locals = Vec::with_capacity(
585 (0..self.args.len()).map(|i| self.arg_unique_types[i].len()).sum()
587 let mut counts = Vec::with_capacity(self.count_args.len());
588 let mut pats = Vec::with_capacity(self.args.len());
589 let mut heads = Vec::with_capacity(self.args.len());
591 let names_pos: Vec<_> = (0..self.args.len())
592 .map(|i| self.ecx.ident_of(&format!("arg{}", i)).gensym())
595 // First, build up the static array which will become our precompiled
597 let pieces = self.ecx.expr_vec_slice(self.fmtsp, self.str_pieces);
599 // Before consuming the expressions, we have to remember spans for
600 // count arguments as they are now generated separate from other
601 // arguments, hence have no access to the `P<ast::Expr>`'s.
602 let spans_pos: Vec<_> = self.args.iter().map(|e| e.span.clone()).collect();
604 // Right now there is a bug such that for the expression:
606 // the lifetime of `1` doesn't outlast the call to `bar`, so it's not
607 // valid for the call to `foo`. To work around this all arguments to the
608 // format! string are shoved into locals. Furthermore, we shove the address
609 // of each variable because we don't want to move out of the arguments
610 // passed to this function.
611 for (i, e) in self.args.into_iter().enumerate() {
612 let name = names_pos[i];
614 DUMMY_SP.with_ctxt(e.span.ctxt().apply_mark(self.ecx.current_expansion.mark));
615 pats.push(self.ecx.pat_ident(span, name));
616 for ref arg_ty in self.arg_unique_types[i].iter() {
617 locals.push(Context::format_arg(self.ecx, self.macsp, e.span, arg_ty, name));
619 heads.push(self.ecx.expr_addr_of(e.span, e));
621 for pos in self.count_args {
622 let index = match pos {
624 _ => panic!("should never happen"),
626 let name = names_pos[index];
627 let span = spans_pos[index];
628 counts.push(Context::format_arg(self.ecx, self.macsp, span, &Count, name));
631 // Now create a vector containing all the arguments
632 let args = locals.into_iter().chain(counts.into_iter());
634 let args_array = self.ecx.expr_vec(self.fmtsp, args.collect());
636 // Constructs an AST equivalent to:
638 // match (&arg0, &arg1) {
639 // (tmp0, tmp1) => args_array
648 // Because of #11585 the new temporary lifetime rule, the enclosing
649 // statements for these temporaries become the let's themselves.
650 // If one or more of them are RefCell's, RefCell borrow() will also
651 // end there; they don't last long enough for args_array to use them.
652 // The match expression solves the scope problem.
654 // Note, it may also very well be transformed to:
659 // ref tmp1 => args_array } } }
661 // But the nested match expression is proved to perform not as well
662 // as series of let's; the first approach does.
663 let pat = self.ecx.pat_tuple(self.fmtsp, pats);
664 let arm = self.ecx.arm(self.fmtsp, vec![pat], args_array);
665 let head = self.ecx.expr(self.fmtsp, ast::ExprKind::Tup(heads));
666 let result = self.ecx.expr_match(self.fmtsp, head, vec![arm]);
668 let args_slice = self.ecx.expr_addr_of(self.fmtsp, result);
670 // Now create the fmt::Arguments struct with all our locals we created.
671 let (fn_name, fn_args) = if self.all_pieces_simple {
672 ("new_v1", vec![pieces, args_slice])
674 // Build up the static array which will store our precompiled
675 // nonstandard placeholders, if there are any.
676 let fmt = self.ecx.expr_vec_slice(self.macsp, self.pieces);
678 ("new_v1_formatted", vec![pieces, args_slice, fmt])
681 let path = self.ecx.std_path(&["fmt", "Arguments", fn_name]);
682 self.ecx.expr_call_global(self.macsp, path, fn_args)
685 fn format_arg(ecx: &ExtCtxt,
691 sp = sp.apply_mark(ecx.current_expansion.mark);
692 let arg = ecx.expr_ident(sp, arg);
693 let trait_ = match *ty {
694 Placeholder(ref tyname) => {
706 ecx.span_err(sp, &format!("unknown format trait `{}`", *tyname));
712 let path = ecx.std_path(&["fmt", "ArgumentV1", "from_usize"]);
713 return ecx.expr_call_global(macsp, path, vec![arg]);
717 let path = ecx.std_path(&["fmt", trait_, "fmt"]);
718 let format_fn = ecx.path_global(sp, path);
719 let path = ecx.std_path(&["fmt", "ArgumentV1", "new"]);
720 ecx.expr_call_global(macsp, path, vec![arg, ecx.expr_path(format_fn)])
724 pub fn expand_format_args<'cx>(ecx: &'cx mut ExtCtxt,
726 tts: &[tokenstream::TokenTree])
727 -> Box<dyn base::MacResult + 'cx> {
728 sp = sp.apply_mark(ecx.current_expansion.mark);
729 match parse_args(ecx, sp, tts) {
730 Some((efmt, args, names)) => {
731 MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt, args, names, false))
733 None => DummyResult::expr(sp),
737 pub fn expand_format_args_nl<'cx>(
738 ecx: &'cx mut ExtCtxt,
740 tts: &[tokenstream::TokenTree],
741 ) -> Box<dyn base::MacResult + 'cx> {
742 //if !ecx.ecfg.enable_allow_internal_unstable() {
744 // For some reason, the only one that actually works for `println` is the first check
745 if !sp.allows_unstable() // the enclosing span is marked as `#[allow_insternal_unsable]`
746 && !ecx.ecfg.enable_allow_internal_unstable() // NOTE: when is this enabled?
747 && !ecx.ecfg.enable_format_args_nl() // enabled using `#[feature(format_args_nl]`
749 feature_gate::emit_feature_err(&ecx.parse_sess,
752 feature_gate::GateIssue::Language,
753 feature_gate::EXPLAIN_FORMAT_ARGS_NL);
754 return base::DummyResult::expr(sp);
756 sp = sp.apply_mark(ecx.current_expansion.mark);
757 match parse_args(ecx, sp, tts) {
758 Some((efmt, args, names)) => {
759 MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt, args, names, true))
761 None => DummyResult::expr(sp),
765 /// Take the various parts of `format_args!(efmt, args..., name=names...)`
766 /// and construct the appropriate formatting expression.
767 pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt,
770 args: Vec<P<ast::Expr>>,
771 names: FxHashMap<String, usize>,
772 append_newline: bool)
774 // NOTE: this verbose way of initializing `Vec<Vec<ArgumentType>>` is because
775 // `ArgumentType` does not derive `Clone`.
776 let arg_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
777 let arg_unique_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
779 let mut macsp = ecx.call_site();
780 macsp = macsp.apply_mark(ecx.current_expansion.mark);
782 let msg = "format argument must be a string literal";
783 let fmt_sp = efmt.span;
784 let fmt = match expr_to_spanned_string(ecx, efmt, msg) {
785 Ok(mut fmt) if append_newline => {
786 fmt.node.0 = Symbol::intern(&format!("{}\n", fmt.node.0));
791 let sugg_fmt = match args.len() {
792 0 => "{}".to_string(),
793 _ => format!("{}{{}}", "{} ".repeat(args.len())),
795 err.span_suggestion_with_applicability(
796 fmt_sp.shrink_to_lo(),
797 "you might be missing a string literal to format with",
798 format!("\"{}\", ", sugg_fmt),
799 Applicability::MaybeIncorrect,
802 return DummyResult::raw_expr(sp);
806 let is_literal = match ecx.source_map().span_to_snippet(fmt_sp) {
807 Ok(ref s) if s.starts_with("\"") || s.starts_with("r#") => true,
811 let fmt_str = &*fmt.node.0.as_str();
812 let str_style = match fmt.node.1 {
813 ast::StrStyle::Cooked => None,
814 ast::StrStyle::Raw(raw) => Some(raw as usize),
817 let mut parser = parse::Parser::new(fmt_str, str_style);
819 let mut unverified_pieces = Vec::new();
820 while let Some(piece) = parser.next() {
821 if !parser.errors.is_empty() {
824 unverified_pieces.push(piece);
828 if !parser.errors.is_empty() {
829 let err = parser.errors.remove(0);
830 let sp = fmt.span.from_inner_byte_pos(err.start, err.end);
831 let mut e = ecx.struct_span_err(sp, &format!("invalid format string: {}",
833 e.span_label(sp, err.label + " in format string");
834 if let Some(note) = err.note {
838 return DummyResult::raw_expr(sp);
841 let arg_spans = parser.arg_places.iter()
842 .map(|&(start, end)| fmt.span.from_inner_byte_pos(start, end))
845 let mut cx = Context {
853 arg_index_map: Vec::new(),
854 count_args: Vec::new(),
855 count_positions: FxHashMap::default(),
856 count_positions_count: 0,
857 count_args_index_offset: 0,
858 literal: String::new(),
859 pieces: Vec::with_capacity(unverified_pieces.len()),
860 str_pieces: Vec::with_capacity(unverified_pieces.len()),
861 all_pieces_simple: true,
864 invalid_refs: Vec::new(),
869 // This needs to happen *after* the Parser has consumed all pieces to create all the spans
870 let pieces = unverified_pieces.into_iter().map(|mut piece| {
871 cx.verify_piece(&piece);
872 cx.resolve_name_inplace(&mut piece);
874 }).collect::<Vec<_>>();
876 let numbered_position_args = pieces.iter().any(|arg: &parse::Piece| {
878 parse::String(_) => false,
879 parse::NextArgument(arg) => {
881 parse::Position::ArgumentIs(_) => true,
888 cx.build_index_map();
890 let mut arg_index_consumed = vec![0usize; cx.arg_index_map.len()];
892 for piece in pieces {
893 if let Some(piece) = cx.build_piece(&piece, &mut arg_index_consumed) {
894 let s = cx.build_literal_string();
895 cx.str_pieces.push(s);
896 cx.pieces.push(piece);
900 if !cx.literal.is_empty() {
901 let s = cx.build_literal_string();
902 cx.str_pieces.push(s);
905 if cx.invalid_refs.len() >= 1 {
906 cx.report_invalid_references(numbered_position_args);
909 // Make sure that all arguments were used and all arguments have types.
910 let num_pos_args = cx.args.len() - cx.names.len();
912 let errs = cx.arg_types
915 .filter(|(i, ty)| ty.is_empty() && !cx.count_positions.contains_key(&i))
917 let msg = if i >= num_pos_args {
919 "named argument never used"
921 // positional argument
922 "argument never used"
924 (cx.args[i].span, msg)
926 .collect::<Vec<_>>();
928 let errs_len = errs.len();
929 if !errs.is_empty() {
930 let args_used = cx.arg_types.len() - errs_len;
931 let args_unused = errs_len;
935 let (sp, msg) = errs.into_iter().next().unwrap();
936 cx.ecx.struct_span_err(sp, msg)
938 let mut diag = cx.ecx.struct_span_err(
939 errs.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
940 "multiple unused formatting arguments",
942 diag.span_label(cx.fmtsp, "multiple missing formatting specifiers");
947 // Used to ensure we only report translations for *one* kind of foreign format.
948 let mut found_foreign = false;
949 // Decide if we want to look for foreign formatting directives.
950 if args_used < args_unused {
951 use super::format_foreign as foreign;
953 // The set of foreign substitutions we've explained. This prevents spamming the user
954 // with `%d should be written as {}` over and over again.
955 let mut explained = FxHashSet::default();
957 macro_rules! check_foreign {
959 let mut show_doc_note = false;
961 let mut suggestions = vec![];
962 for sub in foreign::$kind::iter_subs(fmt_str) {
963 let trn = match sub.translate() {
966 // If it has no translation, don't call it out specifically.
970 let pos = sub.position();
971 let sub = String::from(sub.as_str());
972 if explained.contains(&sub) {
975 explained.insert(sub.clone());
978 found_foreign = true;
979 show_doc_note = true;
982 if let Some((start, end)) = pos {
983 // account for `"` and account for raw strings `r#`
984 let padding = str_style.map(|i| i + 2).unwrap_or(1);
985 let sp = fmt_sp.from_inner_byte_pos(start + padding, end + padding);
986 suggestions.push((sp, trn));
988 diag.help(&format!("`{}` should be written as `{}`", sub, trn));
995 " formatting not supported; see the documentation for `std::fmt`",
998 if suggestions.len() > 0 {
999 diag.multipart_suggestion_with_applicability(
1000 "format specifiers use curly braces",
1002 Applicability::MachineApplicable,
1008 check_foreign!(printf);
1010 check_foreign!(shell);
1013 if !found_foreign && errs_len == 1 {
1014 diag.span_label(cx.fmtsp, "formatting specifier missing");