4 use fmt_macros as parse;
6 use errors::DiagnosticBuilder;
7 use errors::Applicability;
10 use syntax::ext::base::{self, *};
11 use syntax::ext::build::AstBuilder;
12 use syntax::feature_gate;
13 use syntax::parse::token;
15 use syntax::symbol::{Symbol, sym};
16 use syntax::tokenstream;
17 use syntax_pos::{MultiSpan, Span, DUMMY_SP};
19 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
21 use std::collections::hash_map::Entry;
34 struct Context<'a, 'b: 'a> {
35 ecx: &'a mut ExtCtxt<'b>,
36 /// The macro's call site. References to unstable formatting internals must
37 /// use this span to pass the stability checker.
39 /// The span of the format string literal.
42 /// List of parsed argument expressions.
43 /// Named expressions are resolved early, and are appended to the end of
44 /// argument expressions.
46 /// Example showing the various data structures in motion:
48 /// * Original: `"{foo:o} {:o} {foo:x} {0:x} {1:o} {:x} {1:x} {0:o}"`
49 /// * Implicit argument resolution: `"{foo:o} {0:o} {foo:x} {0:x} {1:o} {1:x} {1:x} {0:o}"`
50 /// * Name resolution: `"{2:o} {0:o} {2:x} {0:x} {1:o} {1:x} {1:x} {0:o}"`
51 /// * `arg_types` (in JSON): `[[0, 1, 0], [0, 1, 1], [0, 1]]`
52 /// * `arg_unique_types` (in simplified JSON): `[["o", "x"], ["o", "x"], ["o", "x"]]`
53 /// * `names` (in JSON): `{"foo": 2}`
54 args: Vec<P<ast::Expr>>,
55 /// Placeholder slot numbers indexed by argument.
56 arg_types: Vec<Vec<usize>>,
57 /// Unique format specs seen for each argument.
58 arg_unique_types: Vec<Vec<ArgumentType>>,
59 /// Map from named arguments to their resolved indices.
60 names: FxHashMap<String, usize>,
62 /// The latest consecutive literal strings, or empty if there weren't any.
65 /// Collection of the compiled `rt::Argument` structures
66 pieces: Vec<P<ast::Expr>>,
67 /// Collection of string literals
68 str_pieces: Vec<P<ast::Expr>>,
69 /// Stays `true` if all formatting parameters are default (as in "{}{}").
70 all_pieces_simple: bool,
72 /// Mapping between positional argument references and indices into the
73 /// final generated static argument array. We record the starting indices
74 /// corresponding to each positional argument, and number of references
75 /// consumed so far for each argument, to facilitate correct `Position`
76 /// mapping in `build_piece`. In effect this can be seen as a "flattened"
77 /// version of `arg_unique_types`.
79 /// Again with the example described above in docstring for `args`:
81 /// * `arg_index_map` (in JSON): `[[0, 1, 0], [2, 3, 3], [4, 5]]`
82 arg_index_map: Vec<Vec<usize>>,
84 /// Starting offset of count argument slots.
85 count_args_index_offset: usize,
87 /// Count argument slots and tracking data structures.
88 /// Count arguments are separately tracked for de-duplication in case
89 /// multiple references are made to one argument. For example, in this
92 /// * Original: `"{:.*} {:.foo$} {1:.*} {:.0$}"`
93 /// * Implicit argument resolution: `"{1:.0$} {2:.foo$} {1:.3$} {4:.0$}"`
94 /// * Name resolution: `"{1:.0$} {2:.5$} {1:.3$} {4:.0$}"`
95 /// * `count_positions` (in JSON): `{0: 0, 5: 1, 3: 2}`
96 /// * `count_args`: `vec![Exact(0), Exact(5), Exact(3)]`
97 count_args: Vec<Position>,
98 /// Relative slot numbers for count arguments.
99 count_positions: FxHashMap<usize, usize>,
100 /// Number of count slots assigned.
101 count_positions_count: usize,
103 /// Current position of the implicit positional arg pointer, as if it
104 /// still existed in this phase of processing.
105 /// Used only for `all_pieces_simple` tracking in `build_piece`.
107 /// Current piece being evaluated, used for error reporting.
109 /// Keep track of invalid references to positional arguments.
110 invalid_refs: Vec<(usize, usize)>,
111 /// Spans of all the formatting arguments, in order.
112 arg_spans: Vec<Span>,
113 /// Whether this formatting string is a literal or it comes from a macro.
117 /// Parses the arguments from the given list of tokens, returning the diagnostic
118 /// if there's a parse error so we can continue parsing other format!
121 /// If parsing succeeds, the return value is:
124 /// Some((fmtstr, parsed arguments, index map for named arguments))
127 ecx: &mut ExtCtxt<'a>,
129 tts: &[tokenstream::TokenTree]
130 ) -> Result<(P<ast::Expr>, Vec<P<ast::Expr>>, FxHashMap<String, usize>), DiagnosticBuilder<'a>> {
131 let mut args = Vec::<P<ast::Expr>>::new();
132 let mut names = FxHashMap::<String, usize>::default();
134 let mut p = ecx.new_parser_from_tts(tts);
136 if p.token == token::Eof {
137 return Err(ecx.struct_span_err(sp, "requires at least a format string argument"));
140 let fmtstr = p.parse_expr()?;
141 let mut named = false;
143 while p.token != token::Eof {
144 if !p.eat(&token::Comma) {
145 return Err(ecx.struct_span_err(p.span, "expected token: `,`"));
147 if p.token == token::Eof {
149 } // accept trailing commas
150 if named || (p.token.is_ident() && p.look_ahead(1, |t| *t == token::Eq)) {
152 let ident = if let token::Ident(i, _) = p.token {
156 return Err(ecx.struct_span_err(
158 "expected ident, positional arguments cannot follow named arguments",
161 let name: &str = &ident.as_str();
163 p.expect(&token::Eq)?;
164 let e = p.parse_expr()?;
165 if let Some(prev) = names.get(name) {
166 ecx.struct_span_err(e.span, &format!("duplicate argument named `{}`", name))
167 .span_note(args[*prev].span, "previously here")
172 // Resolve names into slots early.
173 // Since all the positional args are already seen at this point
174 // if the input is valid, we can simply append to the positional
175 // args. And remember the names.
176 let slot = args.len();
177 names.insert(name.to_string(), slot);
180 let e = p.parse_expr()?;
184 Ok((fmtstr, args, names))
187 impl<'a, 'b> Context<'a, 'b> {
188 fn resolve_name_inplace(&self, p: &mut parse::Piece<'_>) {
189 // NOTE: the `unwrap_or` branch is needed in case of invalid format
190 // arguments, e.g., `format_args!("{foo}")`.
191 let lookup = |s| *self.names.get(s).unwrap_or(&0);
194 parse::String(_) => {}
195 parse::NextArgument(ref mut arg) => {
196 if let parse::ArgumentNamed(s) = arg.position {
197 arg.position = parse::ArgumentIs(lookup(s));
199 if let parse::CountIsName(s) = arg.format.width {
200 arg.format.width = parse::CountIsParam(lookup(s));
202 if let parse::CountIsName(s) = arg.format.precision {
203 arg.format.precision = parse::CountIsParam(lookup(s));
209 /// Verifies one piece of a parse string, and remembers it if valid.
210 /// All errors are not emitted as fatal so we can continue giving errors
211 /// about this and possibly other format strings.
212 fn verify_piece(&mut self, p: &parse::Piece<'_>) {
214 parse::String(..) => {}
215 parse::NextArgument(ref arg) => {
216 // width/precision first, if they have implicit positional
217 // parameters it makes more sense to consume them first.
218 self.verify_count(arg.format.width);
219 self.verify_count(arg.format.precision);
221 // argument second, if it's an implicit positional parameter
222 // it's written second, so it should come after width/precision.
223 let pos = match arg.position {
224 parse::ArgumentIs(i) | parse::ArgumentImplicitlyIs(i) => Exact(i),
225 parse::ArgumentNamed(s) => Named(s.to_string()),
228 let ty = Placeholder(arg.format.ty.to_string());
229 self.verify_arg_type(pos, ty);
235 fn verify_count(&mut self, c: parse::Count<'_>) {
237 parse::CountImplied |
238 parse::CountIs(..) => {}
239 parse::CountIsParam(i) => {
240 self.verify_arg_type(Exact(i), Count);
242 parse::CountIsName(s) => {
243 self.verify_arg_type(Named(s.to_string()), Count);
248 fn describe_num_args(&self) -> Cow<'_, str> {
249 match self.args.len() {
250 0 => "no arguments were given".into(),
251 1 => "there is 1 argument".into(),
252 x => format!("there are {} arguments", x).into(),
256 /// Handle invalid references to positional arguments. Output different
257 /// errors for the case where all arguments are positional and for when
258 /// there are named arguments or numbered positional arguments in the
260 fn report_invalid_references(&self, numbered_position_args: bool) {
262 let sp = if self.is_literal {
263 MultiSpan::from_spans(self.arg_spans.clone())
265 MultiSpan::from_span(self.fmtsp)
267 let refs_len = self.invalid_refs.len();
271 .map(|(r, pos)| (r.to_string(), self.arg_spans.get(*pos)));
273 if self.names.is_empty() && !numbered_position_args {
274 e = self.ecx.mut_span_err(
277 "{} positional argument{} in format string, but {}",
279 if self.pieces.len() > 1 { "s" } else { "" },
280 self.describe_num_args()
284 let (arg_list, mut sp) = if refs_len == 1 {
285 let (reg, pos) = refs.next().unwrap();
287 format!("argument {}", reg),
288 MultiSpan::from_span(*pos.unwrap_or(&self.fmtsp)),
291 let (mut refs, spans): (Vec<_>, Vec<_>) = refs.unzip();
292 let pos = MultiSpan::from_spans(spans.into_iter().map(|s| *s.unwrap()).collect());
293 let reg = refs.pop().unwrap();
296 "arguments {head} and {tail}",
297 head = refs.join(", "),
303 if !self.is_literal {
304 sp = MultiSpan::from_span(self.fmtsp);
307 e = self.ecx.mut_span_err(sp,
308 &format!("invalid reference to positional {} ({})",
310 self.describe_num_args()));
311 e.note("positional arguments are zero-based");
317 /// Actually verifies and tracks a given format placeholder
318 /// (a.k.a. argument).
319 fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
322 if self.args.len() <= arg {
323 self.invalid_refs.push((arg, self.curpiece));
328 // record every (position, type) combination only once
329 let ref mut seen_ty = self.arg_unique_types[arg];
330 let i = seen_ty.iter().position(|x| *x == ty).unwrap_or_else(|| {
331 let i = seen_ty.len();
335 self.arg_types[arg].push(i);
338 if let Entry::Vacant(e) = self.count_positions.entry(arg) {
339 let i = self.count_positions_count;
341 self.count_args.push(Exact(arg));
342 self.count_positions_count += 1;
349 match self.names.get(&name) {
351 // Treat as positional arg.
352 self.verify_arg_type(Exact(idx), ty)
355 let msg = format!("there is no argument named `{}`", name);
356 let sp = if self.is_literal {
357 *self.arg_spans.get(self.curpiece).unwrap_or(&self.fmtsp)
361 let mut err = self.ecx.struct_span_err(sp, &msg[..]);
369 /// Builds the mapping between format placeholders and argument objects.
370 fn build_index_map(&mut self) {
371 // NOTE: Keep the ordering the same as `into_expr`'s expansion would do!
372 let args_len = self.args.len();
373 self.arg_index_map.reserve(args_len);
375 let mut sofar = 0usize;
378 for i in 0..args_len {
379 let ref arg_types = self.arg_types[i];
380 let arg_offsets = arg_types.iter().map(|offset| sofar + *offset).collect::<Vec<_>>();
381 self.arg_index_map.push(arg_offsets);
382 sofar += self.arg_unique_types[i].len();
385 // Record starting index for counts, which appear just after arguments
386 self.count_args_index_offset = sofar;
389 fn rtpath(ecx: &ExtCtxt<'_>, s: &str) -> Vec<ast::Ident> {
390 ecx.std_path(&[sym::fmt, sym::rt, sym::v1, Symbol::intern(s)])
393 fn build_count(&self, c: parse::Count<'_>) -> P<ast::Expr> {
395 let count = |c, arg| {
396 let mut path = Context::rtpath(self.ecx, "Count");
397 path.push(self.ecx.ident_of(c));
399 Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]),
400 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
404 parse::CountIs(i) => count("Is", Some(self.ecx.expr_usize(sp, i))),
405 parse::CountIsParam(i) => {
406 // This needs mapping too, as `i` is referring to a macro
407 // argument. If `i` is not found in `count_positions` then
408 // the error had already been emitted elsewhere.
409 let i = self.count_positions.get(&i).cloned().unwrap_or(0)
410 + self.count_args_index_offset;
411 count("Param", Some(self.ecx.expr_usize(sp, i)))
413 parse::CountImplied => count("Implied", None),
414 // should never be the case, names are already resolved
415 parse::CountIsName(_) => panic!("should never happen"),
419 /// Build a literal expression from the accumulated string literals
420 fn build_literal_string(&mut self) -> P<ast::Expr> {
422 let s = Symbol::intern(&self.literal);
423 self.literal.clear();
424 self.ecx.expr_str(sp, s)
427 /// Builds a static `rt::Argument` from a `parse::Piece` or append
428 /// to the `literal` string.
429 fn build_piece(&mut self,
430 piece: &parse::Piece<'_>,
431 arg_index_consumed: &mut Vec<usize>)
432 -> Option<P<ast::Expr>> {
435 parse::String(s) => {
436 self.literal.push_str(s);
439 parse::NextArgument(ref arg) => {
440 // Build the position
443 let mut path = Context::rtpath(self.ecx, "Position");
444 path.push(self.ecx.ident_of(c));
447 let arg = self.ecx.expr_usize(sp, i);
448 self.ecx.expr_call_global(sp, path, vec![arg])
450 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
455 | parse::ArgumentImplicitlyIs(i) => {
456 // Map to index in final generated argument array
457 // in case of multiple types specified
458 let arg_idx = match arg_index_consumed.get_mut(i) {
459 None => 0, // error already emitted elsewhere
461 let ref idx_map = self.arg_index_map[i];
462 // unwrap_or branch: error already emitted elsewhere
463 let arg_idx = *idx_map.get(*offset).unwrap_or(&0);
468 pos("At", Some(arg_idx))
471 // should never be the case, because names are already
473 parse::ArgumentNamed(_) => panic!("should never happen"),
477 let simple_arg = parse::Argument {
479 // We don't have ArgumentNext any more, so we have to
480 // track the current argument ourselves.
485 format: parse::FormatSpec {
486 fill: arg.format.fill,
487 align: parse::AlignUnknown,
489 precision: parse::CountImplied,
490 width: parse::CountImplied,
495 let fill = arg.format.fill.unwrap_or(' ');
498 arg.position.index() == simple_arg.position.index();
500 if !pos_simple || arg.format != simple_arg.format || fill != ' ' {
501 self.all_pieces_simple = false;
505 let fill = self.ecx.expr_lit(sp, ast::LitKind::Char(fill));
507 let mut p = Context::rtpath(self.ecx, "Alignment");
508 p.push(self.ecx.ident_of(name));
509 self.ecx.path_global(sp, p)
511 let align = match arg.format.align {
512 parse::AlignLeft => align("Left"),
513 parse::AlignRight => align("Right"),
514 parse::AlignCenter => align("Center"),
515 parse::AlignUnknown => align("Unknown"),
517 let align = self.ecx.expr_path(align);
518 let flags = self.ecx.expr_u32(sp, arg.format.flags);
519 let prec = self.build_count(arg.format.precision);
520 let width = self.build_count(arg.format.width);
521 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "FormatSpec"));
522 let fmt = self.ecx.expr_struct(
526 self.ecx.field_imm(sp, self.ecx.ident_of("fill"), fill),
527 self.ecx.field_imm(sp, self.ecx.ident_of("align"), align),
528 self.ecx.field_imm(sp, self.ecx.ident_of("flags"), flags),
529 self.ecx.field_imm(sp, self.ecx.ident_of("precision"), prec),
530 self.ecx.field_imm(sp, self.ecx.ident_of("width"), width),
534 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "Argument"));
535 Some(self.ecx.expr_struct(
539 self.ecx.field_imm(sp, self.ecx.ident_of("position"), pos),
540 self.ecx.field_imm(sp, self.ecx.ident_of("format"), fmt),
547 /// Actually builds the expression which the format_args! block will be
549 fn into_expr(self) -> P<ast::Expr> {
550 let mut locals = Vec::with_capacity(
551 (0..self.args.len()).map(|i| self.arg_unique_types[i].len()).sum()
553 let mut counts = Vec::with_capacity(self.count_args.len());
554 let mut pats = Vec::with_capacity(self.args.len());
555 let mut heads = Vec::with_capacity(self.args.len());
557 let names_pos: Vec<_> = (0..self.args.len())
558 .map(|i| self.ecx.ident_of(&format!("arg{}", i)).gensym())
561 // First, build up the static array which will become our precompiled
563 let pieces = self.ecx.expr_vec_slice(self.fmtsp, self.str_pieces);
565 // Before consuming the expressions, we have to remember spans for
566 // count arguments as they are now generated separate from other
567 // arguments, hence have no access to the `P<ast::Expr>`'s.
568 let spans_pos: Vec<_> = self.args.iter().map(|e| e.span.clone()).collect();
570 // Right now there is a bug such that for the expression:
572 // the lifetime of `1` doesn't outlast the call to `bar`, so it's not
573 // valid for the call to `foo`. To work around this all arguments to the
574 // format! string are shoved into locals. Furthermore, we shove the address
575 // of each variable because we don't want to move out of the arguments
576 // passed to this function.
577 for (i, e) in self.args.into_iter().enumerate() {
578 let name = names_pos[i];
580 DUMMY_SP.with_ctxt(e.span.ctxt().apply_mark(self.ecx.current_expansion.mark));
581 pats.push(self.ecx.pat_ident(span, name));
582 for ref arg_ty in self.arg_unique_types[i].iter() {
583 locals.push(Context::format_arg(self.ecx, self.macsp, e.span, arg_ty, name));
585 heads.push(self.ecx.expr_addr_of(e.span, e));
587 for pos in self.count_args {
588 let index = match pos {
590 _ => panic!("should never happen"),
592 let name = names_pos[index];
593 let span = spans_pos[index];
594 counts.push(Context::format_arg(self.ecx, self.macsp, span, &Count, name));
597 // Now create a vector containing all the arguments
598 let args = locals.into_iter().chain(counts.into_iter());
600 let args_array = self.ecx.expr_vec(self.fmtsp, args.collect());
602 // Constructs an AST equivalent to:
604 // match (&arg0, &arg1) {
605 // (tmp0, tmp1) => args_array
614 // Because of #11585 the new temporary lifetime rule, the enclosing
615 // statements for these temporaries become the let's themselves.
616 // If one or more of them are RefCell's, RefCell borrow() will also
617 // end there; they don't last long enough for args_array to use them.
618 // The match expression solves the scope problem.
620 // Note, it may also very well be transformed to:
625 // ref tmp1 => args_array } } }
627 // But the nested match expression is proved to perform not as well
628 // as series of let's; the first approach does.
629 let pat = self.ecx.pat_tuple(self.fmtsp, pats);
630 let arm = self.ecx.arm(self.fmtsp, vec![pat], args_array);
631 let head = self.ecx.expr(self.fmtsp, ast::ExprKind::Tup(heads));
632 let result = self.ecx.expr_match(self.fmtsp, head, vec![arm]);
634 let args_slice = self.ecx.expr_addr_of(self.fmtsp, result);
636 // Now create the fmt::Arguments struct with all our locals we created.
637 let (fn_name, fn_args) = if self.all_pieces_simple {
638 ("new_v1", vec![pieces, args_slice])
640 // Build up the static array which will store our precompiled
641 // nonstandard placeholders, if there are any.
642 let fmt = self.ecx.expr_vec_slice(self.macsp, self.pieces);
644 ("new_v1_formatted", vec![pieces, args_slice, fmt])
647 let path = self.ecx.std_path(&[sym::fmt, sym::Arguments, Symbol::intern(fn_name)]);
648 self.ecx.expr_call_global(self.macsp, path, fn_args)
651 fn format_arg(ecx: &ExtCtxt<'_>,
657 sp = sp.apply_mark(ecx.current_expansion.mark);
658 let arg = ecx.expr_ident(sp, arg);
659 let trait_ = match *ty {
660 Placeholder(ref tyname) => {
672 ecx.span_err(sp, &format!("unknown format trait `{}`", *tyname));
673 return DummyResult::raw_expr(sp, true);
678 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, sym::from_usize]);
679 return ecx.expr_call_global(macsp, path, vec![arg]);
683 let path = ecx.std_path(&[sym::fmt, Symbol::intern(trait_), sym::fmt]);
684 let format_fn = ecx.path_global(sp, path);
685 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, sym::new]);
686 ecx.expr_call_global(macsp, path, vec![arg, ecx.expr_path(format_fn)])
690 pub fn expand_format_args<'cx>(ecx: &'cx mut ExtCtxt<'_>,
692 tts: &[tokenstream::TokenTree])
693 -> Box<dyn base::MacResult + 'cx> {
694 sp = sp.apply_mark(ecx.current_expansion.mark);
695 match parse_args(ecx, sp, tts) {
696 Ok((efmt, args, names)) => {
697 MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt, args, names, false))
701 DummyResult::expr(sp)
706 pub fn expand_format_args_nl<'cx>(
707 ecx: &'cx mut ExtCtxt<'_>,
709 tts: &[tokenstream::TokenTree],
710 ) -> Box<dyn base::MacResult + 'cx> {
711 //if !ecx.ecfg.enable_allow_internal_unstable() {
713 // For some reason, the only one that actually works for `println` is the first check
714 if !sp.allows_unstable(sym::format_args_nl) // the span is marked `#[allow_insternal_unsable]`
715 && !ecx.ecfg.enable_allow_internal_unstable() // NOTE: when is this enabled?
716 && !ecx.ecfg.enable_format_args_nl() // enabled using `#[feature(format_args_nl]`
718 feature_gate::emit_feature_err(&ecx.parse_sess,
721 feature_gate::GateIssue::Language,
722 feature_gate::EXPLAIN_FORMAT_ARGS_NL);
724 sp = sp.apply_mark(ecx.current_expansion.mark);
725 match parse_args(ecx, sp, tts) {
726 Ok((efmt, args, names)) => {
727 MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt, args, names, true))
731 DummyResult::expr(sp)
736 /// Take the various parts of `format_args!(efmt, args..., name=names...)`
737 /// and construct the appropriate formatting expression.
738 pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt<'_>,
741 args: Vec<P<ast::Expr>>,
742 names: FxHashMap<String, usize>,
743 append_newline: bool)
745 // NOTE: this verbose way of initializing `Vec<Vec<ArgumentType>>` is because
746 // `ArgumentType` does not derive `Clone`.
747 let arg_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
748 let arg_unique_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
750 let mut macsp = ecx.call_site();
751 macsp = macsp.apply_mark(ecx.current_expansion.mark);
753 let msg = "format argument must be a string literal";
754 let fmt_sp = efmt.span;
755 let fmt = match expr_to_spanned_string(ecx, efmt, msg) {
756 Ok(mut fmt) if append_newline => {
757 fmt.node.0 = Symbol::intern(&format!("{}\n", fmt.node.0));
762 if let Some(mut err) = err {
763 let sugg_fmt = match args.len() {
764 0 => "{}".to_string(),
765 _ => format!("{}{{}}", "{} ".repeat(args.len())),
768 fmt_sp.shrink_to_lo(),
769 "you might be missing a string literal to format with",
770 format!("\"{}\", ", sugg_fmt),
771 Applicability::MaybeIncorrect,
775 return DummyResult::raw_expr(sp, true);
779 let (is_literal, fmt_snippet) = match ecx.source_map().span_to_snippet(fmt_sp) {
780 Ok(s) => (s.starts_with("\"") || s.starts_with("r#"), Some(s)),
784 let str_style = match fmt.node.1 {
785 ast::StrStyle::Cooked => None,
786 ast::StrStyle::Raw(raw) => {
791 /// Finds the indices of all characters that have been processed and differ between the actual
792 /// written code (code snippet) and the `InternedString` that get's processed in the `Parser`
793 /// in order to properly synthethise the intra-string `Span`s for error diagnostics.
794 fn find_skips(snippet: &str, is_raw: bool) -> Vec<usize> {
795 let mut eat_ws = false;
796 let mut s = snippet.chars().enumerate().peekable();
797 let mut skips = vec![];
798 while let Some((pos, c)) = s.next() {
799 match (c, s.peek()) {
800 // skip whitespace and empty lines ending in '\\'
801 ('\\', Some((next_pos, '\n'))) if !is_raw => {
804 skips.push(*next_pos);
807 ('\\', Some((next_pos, '\n'))) |
808 ('\\', Some((next_pos, 'n'))) |
809 ('\\', Some((next_pos, 't'))) if eat_ws => {
811 skips.push(*next_pos);
816 ('\t', _) if eat_ws => {
819 ('\\', Some((next_pos, 'n'))) |
820 ('\\', Some((next_pos, 't'))) |
821 ('\\', Some((next_pos, '0'))) |
822 ('\\', Some((next_pos, '\\'))) |
823 ('\\', Some((next_pos, '\''))) |
824 ('\\', Some((next_pos, '\"'))) => {
825 skips.push(*next_pos);
828 ('\\', Some((_, 'x'))) if !is_raw => {
829 for _ in 0..3 { // consume `\xAB` literal
830 if let Some((pos, _)) = s.next() {
837 ('\\', Some((_, 'u'))) if !is_raw => {
838 if let Some((pos, _)) = s.next() {
841 if let Some((next_pos, next_c)) = s.next() {
843 skips.push(next_pos);
844 let mut i = 0; // consume up to 6 hexanumeric chars + closing `}`
845 while let (Some((next_pos, c)), true) = (s.next(), i < 7) {
847 skips.push(next_pos);
849 skips.push(next_pos);
856 } else if next_c.is_digit(16) {
857 skips.push(next_pos);
858 // We suggest adding `{` and `}` when appropriate, accept it here as if
860 let mut i = 0; // consume up to 6 hexanumeric chars
861 while let (Some((next_pos, c)), _) = (s.next(), i < 6) {
863 skips.push(next_pos);
872 _ if eat_ws => { // `take_while(|c| c.is_whitespace())`
881 let skips = if let (true, Some(ref snippet)) = (is_literal, fmt_snippet.as_ref()) {
882 let r_start = str_style.map(|r| r + 1).unwrap_or(0);
883 let r_end = str_style.map(|r| r).unwrap_or(0);
884 let s = &snippet[r_start + 1..snippet.len() - r_end - 1];
885 find_skips(s, str_style.is_some())
890 let fmt_str = &*fmt.node.0.as_str(); // for the suggestions below
891 let mut parser = parse::Parser::new(fmt_str, str_style, skips.clone(), append_newline);
893 let mut unverified_pieces = Vec::new();
894 while let Some(piece) = parser.next() {
895 if !parser.errors.is_empty() {
898 unverified_pieces.push(piece);
902 if !parser.errors.is_empty() {
903 let err = parser.errors.remove(0);
904 let sp = fmt.span.from_inner_byte_pos(err.start.unwrap(), err.end.unwrap());
905 let mut e = ecx.struct_span_err(sp, &format!("invalid format string: {}",
907 e.span_label(sp, err.label + " in format string");
908 if let Some(note) = err.note {
911 if let Some((label, start, end)) = err.secondary_label {
912 let sp = fmt.span.from_inner_byte_pos(start.unwrap(), end.unwrap());
913 e.span_label(sp, label);
916 return DummyResult::raw_expr(sp, true);
919 let arg_spans = parser.arg_places.iter()
920 .map(|&(parse::SpanIndex(start), parse::SpanIndex(end))| {
921 fmt.span.from_inner_byte_pos(start, end)
925 let mut cx = Context {
933 arg_index_map: Vec::new(),
934 count_args: Vec::new(),
935 count_positions: FxHashMap::default(),
936 count_positions_count: 0,
937 count_args_index_offset: 0,
938 literal: String::new(),
939 pieces: Vec::with_capacity(unverified_pieces.len()),
940 str_pieces: Vec::with_capacity(unverified_pieces.len()),
941 all_pieces_simple: true,
944 invalid_refs: Vec::new(),
949 // This needs to happen *after* the Parser has consumed all pieces to create all the spans
950 let pieces = unverified_pieces.into_iter().map(|mut piece| {
951 cx.verify_piece(&piece);
952 cx.resolve_name_inplace(&mut piece);
954 }).collect::<Vec<_>>();
956 let numbered_position_args = pieces.iter().any(|arg: &parse::Piece<'_>| {
958 parse::String(_) => false,
959 parse::NextArgument(arg) => {
961 parse::Position::ArgumentIs(_) => true,
968 cx.build_index_map();
970 let mut arg_index_consumed = vec![0usize; cx.arg_index_map.len()];
972 for piece in pieces {
973 if let Some(piece) = cx.build_piece(&piece, &mut arg_index_consumed) {
974 let s = cx.build_literal_string();
975 cx.str_pieces.push(s);
976 cx.pieces.push(piece);
980 if !cx.literal.is_empty() {
981 let s = cx.build_literal_string();
982 cx.str_pieces.push(s);
985 if cx.invalid_refs.len() >= 1 {
986 cx.report_invalid_references(numbered_position_args);
989 // Make sure that all arguments were used and all arguments have types.
990 let num_pos_args = cx.args.len() - cx.names.len();
992 let errs = cx.arg_types
995 .filter(|(i, ty)| ty.is_empty() && !cx.count_positions.contains_key(&i))
997 let msg = if i >= num_pos_args {
999 "named argument never used"
1001 // positional argument
1002 "argument never used"
1004 (cx.args[i].span, msg)
1006 .collect::<Vec<_>>();
1008 let errs_len = errs.len();
1009 if !errs.is_empty() {
1010 let args_used = cx.arg_types.len() - errs_len;
1011 let args_unused = errs_len;
1015 let (sp, msg) = errs.into_iter().next().unwrap();
1016 let mut diag = cx.ecx.struct_span_err(sp, msg);
1017 diag.span_label(sp, msg);
1020 let mut diag = cx.ecx.struct_span_err(
1021 errs.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
1022 "multiple unused formatting arguments",
1024 diag.span_label(cx.fmtsp, "multiple missing formatting specifiers");
1025 for (sp, msg) in errs {
1026 diag.span_label(sp, msg);
1032 // Used to ensure we only report translations for *one* kind of foreign format.
1033 let mut found_foreign = false;
1034 // Decide if we want to look for foreign formatting directives.
1035 if args_used < args_unused {
1036 use super::format_foreign as foreign;
1038 // The set of foreign substitutions we've explained. This prevents spamming the user
1039 // with `%d should be written as {}` over and over again.
1040 let mut explained = FxHashSet::default();
1042 macro_rules! check_foreign {
1044 let mut show_doc_note = false;
1046 let mut suggestions = vec![];
1047 for sub in foreign::$kind::iter_subs(fmt_str) {
1048 let trn = match sub.translate() {
1051 // If it has no translation, don't call it out specifically.
1055 let pos = sub.position();
1056 let sub = String::from(sub.as_str());
1057 if explained.contains(&sub) {
1060 explained.insert(sub.clone());
1063 found_foreign = true;
1064 show_doc_note = true;
1067 if let Some((start, end)) = pos {
1068 // account for `"` and account for raw strings `r#`
1069 let padding = str_style.map(|i| i + 2).unwrap_or(1);
1070 let sp = fmt_sp.from_inner_byte_pos(start + padding, end + padding);
1071 suggestions.push((sp, trn));
1073 diag.help(&format!("`{}` should be written as `{}`", sub, trn));
1080 " formatting not supported; see the documentation for `std::fmt`",
1083 if suggestions.len() > 0 {
1084 diag.multipart_suggestion(
1085 "format specifiers use curly braces",
1087 Applicability::MachineApplicable,
1093 check_foreign!(printf);
1095 check_foreign!(shell);
1098 if !found_foreign && errs_len == 1 {
1099 diag.span_label(cx.fmtsp, "formatting specifier missing");