4 use fmt_macros as parse;
6 use errors::DiagnosticBuilder;
7 use errors::Applicability;
10 use syntax::ext::base::{self, *};
11 use syntax::parse::token;
13 use syntax::symbol::{Symbol, sym};
14 use syntax::tokenstream;
15 use syntax_pos::{MultiSpan, Span, DUMMY_SP};
17 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
19 use std::collections::hash_map::Entry;
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.
37 /// The span of the format string literal.
40 /// List of parsed argument expressions.
41 /// Named expressions are resolved early, and are appended to the end of
42 /// argument expressions.
44 /// Example showing the various data structures in motion:
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>,
60 /// The latest consecutive literal strings, or empty if there weren't any.
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,
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`.
77 /// Again with the example described above in docstring for `args`:
79 /// * `arg_index_map` (in JSON): `[[0, 1, 0], [2, 3, 3], [4, 5]]`
80 arg_index_map: Vec<Vec<usize>>,
82 /// Starting offset of count argument slots.
83 count_args_index_offset: usize,
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
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,
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`.
105 /// Current piece being evaluated, used for error reporting.
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.
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!
119 /// If parsing succeeds, the return value is:
122 /// Some((fmtstr, parsed arguments, index map for named arguments))
125 ecx: &mut ExtCtxt<'a>,
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();
132 let mut p = ecx.new_parser_from_tts(tts);
134 if p.token == token::Eof {
135 return Err(ecx.struct_span_err(sp, "requires at least a format string argument"));
138 let fmtstr = p.parse_expr()?;
139 let mut named = false;
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);
148 if p.token == token::Eof {
150 } // accept trailing commas
151 if p.token.is_ident() && p.look_ahead(1, |t| *t == token::Eq) {
153 let name = if let token::Ident(name, _) = p.token.kind {
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")
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);
177 let e = p.parse_expr()?;
179 let mut err = ecx.struct_span_err(
181 "positional arguments cannot follow named arguments",
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");
192 Ok((fmtstr, args, names))
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);
202 parse::String(_) => {}
203 parse::NextArgument(ref mut arg) => {
204 if let parse::ArgumentNamed(s) = arg.position {
205 arg.position = parse::ArgumentIs(lookup(s));
207 if let parse::CountIsName(s) = arg.format.width {
208 arg.format.width = parse::CountIsParam(lookup(s));
210 if let parse::CountIsName(s) = arg.format.precision {
211 arg.format.precision = parse::CountIsParam(lookup(s));
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<'_>) {
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);
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),
236 let ty = Placeholder(arg.format.ty.to_string());
237 self.verify_arg_type(pos, ty);
243 fn verify_count(&mut self, c: parse::Count) {
245 parse::CountImplied |
246 parse::CountIs(..) => {}
247 parse::CountIsParam(i) => {
248 self.verify_arg_type(Exact(i), Count);
250 parse::CountIsName(s) => {
251 self.verify_arg_type(Named(s), Count);
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(),
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
268 fn report_invalid_references(&self, numbered_position_args: bool) {
270 let sp = if self.is_literal {
271 MultiSpan::from_spans(self.arg_spans.clone())
273 MultiSpan::from_span(self.fmtsp)
275 let refs_len = self.invalid_refs.len();
279 .map(|(r, pos)| (r.to_string(), self.arg_spans.get(*pos)));
281 if self.names.is_empty() && !numbered_position_args {
282 e = self.ecx.mut_span_err(
285 "{} positional argument{} in format string, but {}",
287 if self.pieces.len() > 1 { "s" } else { "" },
288 self.describe_num_args()
292 let (arg_list, mut sp) = if refs_len == 1 {
293 let (reg, pos) = refs.next().unwrap();
295 format!("argument {}", reg),
296 MultiSpan::from_span(*pos.unwrap_or(&self.fmtsp)),
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();
304 "arguments {head} and {tail}",
305 head = refs.join(", "),
311 if !self.is_literal {
312 sp = MultiSpan::from_span(self.fmtsp);
315 e = self.ecx.mut_span_err(sp,
316 &format!("invalid reference to positional {} ({})",
318 self.describe_num_args()));
319 e.note("positional arguments are zero-based");
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) {
330 if self.args.len() <= arg {
331 self.invalid_refs.push((arg, self.curpiece));
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();
343 self.arg_types[arg].push(i);
346 if let Entry::Vacant(e) = self.count_positions.entry(arg) {
347 let i = self.count_positions_count;
349 self.count_args.push(Exact(arg));
350 self.count_positions_count += 1;
357 match self.names.get(&name) {
359 // Treat as positional arg.
360 self.verify_arg_type(Exact(idx), ty)
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)
369 let mut err = self.ecx.struct_span_err(sp, &msg[..]);
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);
383 let mut sofar = 0usize;
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();
393 // Record starting index for counts, which appear just after arguments
394 self.count_args_index_offset = sofar;
397 fn rtpath(ecx: &ExtCtxt<'_>, s: &str) -> Vec<ast::Ident> {
398 ecx.std_path(&[sym::fmt, sym::rt, sym::v1, Symbol::intern(s)])
401 fn build_count(&self, c: parse::Count) -> P<ast::Expr> {
403 let count = |c, arg| {
404 let mut path = Context::rtpath(self.ecx, "Count");
405 path.push(self.ecx.ident_of(c));
407 Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]),
408 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
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)))
421 parse::CountImplied => count("Implied", None),
422 // should never be the case, names are already resolved
423 parse::CountIsName(_) => panic!("should never happen"),
427 /// Build a literal expression from the accumulated string literals
428 fn build_literal_string(&mut self) -> P<ast::Expr> {
430 let s = Symbol::intern(&self.literal);
431 self.literal.clear();
432 self.ecx.expr_str(sp, s)
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>> {
443 parse::String(s) => {
444 self.literal.push_str(s);
447 parse::NextArgument(ref arg) => {
448 // Build the position
451 let mut path = Context::rtpath(self.ecx, "Position");
452 path.push(self.ecx.ident_of(c));
455 let arg = self.ecx.expr_usize(sp, i);
456 self.ecx.expr_call_global(sp, path, vec![arg])
458 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
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
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);
476 pos("At", Some(arg_idx))
479 // should never be the case, because names are already
481 parse::ArgumentNamed(_) => panic!("should never happen"),
485 let simple_arg = parse::Argument {
487 // We don't have ArgumentNext any more, so we have to
488 // track the current argument ourselves.
493 format: parse::FormatSpec {
494 fill: arg.format.fill,
495 align: parse::AlignUnknown,
497 precision: parse::CountImplied,
498 width: parse::CountImplied,
503 let fill = arg.format.fill.unwrap_or(' ');
506 arg.position.index() == simple_arg.position.index();
508 if !pos_simple || arg.format != simple_arg.format || fill != ' ' {
509 self.all_pieces_simple = false;
513 let fill = self.ecx.expr_lit(sp, ast::LitKind::Char(fill));
515 let mut p = Context::rtpath(self.ecx, "Alignment");
516 p.push(self.ecx.ident_of(name));
517 self.ecx.path_global(sp, p)
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"),
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(
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),
542 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "Argument"));
543 Some(self.ecx.expr_struct(
547 self.ecx.field_imm(sp, self.ecx.ident_of("position"), pos),
548 self.ecx.field_imm(sp, self.ecx.ident_of("format"), fmt),
555 /// Actually builds the expression which the format_args! block will be
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()
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());
565 let names_pos: Vec<_> = (0..self.args.len())
566 .map(|i| self.ecx.ident_of(&format!("arg{}", i)).gensym())
569 // First, build up the static array which will become our precompiled
571 let pieces = self.ecx.expr_vec_slice(self.fmtsp, self.str_pieces);
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();
578 // Right now there is a bug such that for the expression:
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];
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));
593 heads.push(self.ecx.expr_addr_of(e.span, e));
595 for pos in self.count_args {
596 let index = match pos {
598 _ => panic!("should never happen"),
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));
605 // Now create a vector containing all the arguments
606 let args = locals.into_iter().chain(counts.into_iter());
608 let args_array = self.ecx.expr_vec(self.fmtsp, args.collect());
610 // Constructs an AST equivalent to:
612 // match (&arg0, &arg1) {
613 // (tmp0, tmp1) => args_array
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.
628 // Note, it may also very well be transformed to:
633 // ref tmp1 => args_array } } }
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]);
642 let args_slice = self.ecx.expr_addr_of(self.fmtsp, result);
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])
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);
652 ("new_v1_formatted", vec![pieces, args_slice, fmt])
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)
659 fn format_arg(ecx: &ExtCtxt<'_>,
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) => {
680 ecx.span_err(sp, &format!("unknown format trait `{}`", *tyname));
681 return DummyResult::raw_expr(sp, true);
686 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, sym::from_usize]);
687 return ecx.expr_call_global(macsp, path, vec![arg]);
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)])
698 fn expand_format_args_impl<'cx>(
699 ecx: &'cx mut ExtCtxt<'_>,
701 tts: &[tokenstream::TokenTree],
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))
711 DummyResult::expr(sp)
716 pub fn expand_format_args<'cx>(
717 ecx: &'cx mut ExtCtxt<'_>,
719 tts: &[tokenstream::TokenTree],
720 ) -> Box<dyn base::MacResult + 'cx> {
721 expand_format_args_impl(ecx, sp, tts, false)
724 pub fn expand_format_args_nl<'cx>(
725 ecx: &'cx mut ExtCtxt<'_>,
727 tts: &[tokenstream::TokenTree],
728 ) -> Box<dyn base::MacResult + 'cx> {
729 expand_format_args_impl(ecx, sp, tts, true)
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<'_>,
738 args: Vec<P<ast::Expr>>,
739 names: FxHashMap<Symbol, usize>,
740 append_newline: bool,
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();
747 let mut macsp = ecx.call_site();
748 macsp = macsp.apply_mark(ecx.current_expansion.id);
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));
759 if let Some(mut err) = err {
760 let sugg_fmt = match args.len() {
761 0 => "{}".to_string(),
762 _ => format!("{}{{}}", "{} ".repeat(args.len())),
765 fmt_sp.shrink_to_lo(),
766 "you might be missing a string literal to format with",
767 format!("\"{}\", ", sugg_fmt),
768 Applicability::MaybeIncorrect,
772 return DummyResult::raw_expr(sp, true);
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)),
781 let str_style = match fmt.node.1 {
782 ast::StrStyle::Cooked => None,
783 ast::StrStyle::Raw(raw) => {
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 => {
801 skips.push(*next_pos);
804 ('\\', Some((next_pos, '\n'))) |
805 ('\\', Some((next_pos, 'n'))) |
806 ('\\', Some((next_pos, 't'))) if eat_ws => {
808 skips.push(*next_pos);
813 ('\t', _) if eat_ws => {
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);
825 ('\\', Some((_, 'x'))) if !is_raw => {
826 for _ in 0..3 { // consume `\xAB` literal
827 if let Some((pos, _)) = s.next() {
834 ('\\', Some((_, 'u'))) if !is_raw => {
835 if let Some((pos, _)) = s.next() {
838 if let Some((next_pos, next_c)) = s.next() {
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) {
844 skips.push(next_pos);
846 skips.push(next_pos);
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
857 let mut i = 0; // consume up to 6 hexanumeric chars
858 while let (Some((next_pos, c)), _) = (s.next(), i < 6) {
860 skips.push(next_pos);
869 _ if eat_ws => { // `take_while(|c| c.is_whitespace())`
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())
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);
890 let mut unverified_pieces = Vec::new();
891 while let Some(piece) = parser.next() {
892 if !parser.errors.is_empty() {
895 unverified_pieces.push(piece);
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: {}",
904 e.span_label(sp, err.label + " in format string");
905 if let Some(note) = err.note {
908 if let Some((label, span)) = err.secondary_label {
909 let sp = fmt.span.from_inner(span);
910 e.span_label(sp, label);
913 return DummyResult::raw_expr(sp, true);
916 let arg_spans = parser.arg_places.iter()
917 .map(|span| fmt.span.from_inner(*span))
920 let named_pos: FxHashSet<usize> = names.values().cloned().collect();
922 let mut cx = Context {
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,
941 invalid_refs: Vec::new(),
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);
951 }).collect::<Vec<_>>();
953 let numbered_position_args = pieces.iter().any(|arg: &parse::Piece<'_>| {
955 parse::String(_) => false,
956 parse::NextArgument(arg) => {
958 parse::Position::ArgumentIs(_) => true,
965 cx.build_index_map();
967 let mut arg_index_consumed = vec![0usize; cx.arg_index_map.len()];
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);
977 if !cx.literal.is_empty() {
978 let s = cx.build_literal_string();
979 cx.str_pieces.push(s);
982 if cx.invalid_refs.len() >= 1 {
983 cx.report_invalid_references(numbered_position_args);
986 // Make sure that all arguments were used and all arguments have types.
987 let errs = cx.arg_types
990 .filter(|(i, ty)| ty.is_empty() && !cx.count_positions.contains_key(&i))
992 let msg = if named_pos.contains(&i) {
994 "named argument never used"
996 // positional argument
997 "argument never used"
999 (cx.args[i].span, msg)
1001 .collect::<Vec<_>>();
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;
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);
1015 let mut diag = cx.ecx.struct_span_err(
1016 errs.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
1017 "multiple unused formatting arguments",
1019 diag.span_label(cx.fmtsp, "multiple missing formatting specifiers");
1020 for (sp, msg) in errs {
1021 diag.span_label(sp, msg);
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;
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();
1037 macro_rules! check_foreign {
1039 let mut show_doc_note = false;
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() {
1048 // If it has no translation, don't call it out specifically.
1052 let pos = sub.position();
1053 let sub = String::from(sub.as_str());
1054 if explained.contains(&sub) {
1057 explained.insert(sub.clone());
1060 found_foreign = true;
1061 show_doc_note = true;
1064 if let Some(inner_sp) = pos {
1065 let sp = fmt_sp.from_inner(inner_sp);
1066 suggestions.push((sp, trn));
1068 diag.help(&format!("`{}` should be written as `{}`", sub, trn));
1075 " formatting not supported; see the documentation for `std::fmt`",
1078 if suggestions.len() > 0 {
1079 diag.multipart_suggestion(
1080 "format specifiers use curly braces",
1082 Applicability::MachineApplicable,
1088 check_foreign!(printf);
1090 check_foreign!(shell);
1093 if !found_foreign && errs_len == 1 {
1094 diag.span_label(cx.fmtsp, "formatting specifier missing");