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<Symbol, 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<Symbol, usize>), DiagnosticBuilder<'a>> {
131 let mut args = Vec::<P<ast::Expr>>::new();
132 let mut names = FxHashMap::<Symbol, 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.token.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 name = if let token::Ident(name, _) = p.token.kind {
156 return Err(ecx.struct_span_err(
158 "expected ident, positional arguments cannot follow named arguments",
162 p.expect(&token::Eq)?;
163 let e = p.parse_expr()?;
164 if let Some(prev) = names.get(&name) {
165 ecx.struct_span_err(e.span, &format!("duplicate argument named `{}`", name))
166 .span_note(args[*prev].span, "previously here")
171 // Resolve names into slots early.
172 // Since all the positional args are already seen at this point
173 // if the input is valid, we can simply append to the positional
174 // args. And remember the names.
175 let slot = args.len();
176 names.insert(name, slot);
179 let e = p.parse_expr()?;
183 Ok((fmtstr, args, names))
186 impl<'a, 'b> Context<'a, 'b> {
187 fn resolve_name_inplace(&self, p: &mut parse::Piece<'_>) {
188 // NOTE: the `unwrap_or` branch is needed in case of invalid format
189 // arguments, e.g., `format_args!("{foo}")`.
190 let lookup = |s: Symbol| *self.names.get(&s).unwrap_or(&0);
193 parse::String(_) => {}
194 parse::NextArgument(ref mut arg) => {
195 if let parse::ArgumentNamed(s) = arg.position {
196 arg.position = parse::ArgumentIs(lookup(s));
198 if let parse::CountIsName(s) = arg.format.width {
199 arg.format.width = parse::CountIsParam(lookup(s));
201 if let parse::CountIsName(s) = arg.format.precision {
202 arg.format.precision = parse::CountIsParam(lookup(s));
208 /// Verifies one piece of a parse string, and remembers it if valid.
209 /// All errors are not emitted as fatal so we can continue giving errors
210 /// about this and possibly other format strings.
211 fn verify_piece(&mut self, p: &parse::Piece<'_>) {
213 parse::String(..) => {}
214 parse::NextArgument(ref arg) => {
215 // width/precision first, if they have implicit positional
216 // parameters it makes more sense to consume them first.
217 self.verify_count(arg.format.width);
218 self.verify_count(arg.format.precision);
220 // argument second, if it's an implicit positional parameter
221 // it's written second, so it should come after width/precision.
222 let pos = match arg.position {
223 parse::ArgumentIs(i) | parse::ArgumentImplicitlyIs(i) => Exact(i),
224 parse::ArgumentNamed(s) => Named(s),
227 let ty = Placeholder(arg.format.ty.to_string());
228 self.verify_arg_type(pos, ty);
234 fn verify_count(&mut self, c: parse::Count) {
236 parse::CountImplied |
237 parse::CountIs(..) => {}
238 parse::CountIsParam(i) => {
239 self.verify_arg_type(Exact(i), Count);
241 parse::CountIsName(s) => {
242 self.verify_arg_type(Named(s), Count);
247 fn describe_num_args(&self) -> Cow<'_, str> {
248 match self.args.len() {
249 0 => "no arguments were given".into(),
250 1 => "there is 1 argument".into(),
251 x => format!("there are {} arguments", x).into(),
255 /// Handle invalid references to positional arguments. Output different
256 /// errors for the case where all arguments are positional and for when
257 /// there are named arguments or numbered positional arguments in the
259 fn report_invalid_references(&self, numbered_position_args: bool) {
261 let sp = if self.is_literal {
262 MultiSpan::from_spans(self.arg_spans.clone())
264 MultiSpan::from_span(self.fmtsp)
266 let refs_len = self.invalid_refs.len();
270 .map(|(r, pos)| (r.to_string(), self.arg_spans.get(*pos)));
272 if self.names.is_empty() && !numbered_position_args {
273 e = self.ecx.mut_span_err(
276 "{} positional argument{} in format string, but {}",
278 if self.pieces.len() > 1 { "s" } else { "" },
279 self.describe_num_args()
283 let (arg_list, mut sp) = if refs_len == 1 {
284 let (reg, pos) = refs.next().unwrap();
286 format!("argument {}", reg),
287 MultiSpan::from_span(*pos.unwrap_or(&self.fmtsp)),
290 let (mut refs, spans): (Vec<_>, Vec<_>) = refs.unzip();
291 let pos = MultiSpan::from_spans(spans.into_iter().map(|s| *s.unwrap()).collect());
292 let reg = refs.pop().unwrap();
295 "arguments {head} and {tail}",
296 head = refs.join(", "),
302 if !self.is_literal {
303 sp = MultiSpan::from_span(self.fmtsp);
306 e = self.ecx.mut_span_err(sp,
307 &format!("invalid reference to positional {} ({})",
309 self.describe_num_args()));
310 e.note("positional arguments are zero-based");
316 /// Actually verifies and tracks a given format placeholder
317 /// (a.k.a. argument).
318 fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
321 if self.args.len() <= arg {
322 self.invalid_refs.push((arg, self.curpiece));
327 // record every (position, type) combination only once
328 let ref mut seen_ty = self.arg_unique_types[arg];
329 let i = seen_ty.iter().position(|x| *x == ty).unwrap_or_else(|| {
330 let i = seen_ty.len();
334 self.arg_types[arg].push(i);
337 if let Entry::Vacant(e) = self.count_positions.entry(arg) {
338 let i = self.count_positions_count;
340 self.count_args.push(Exact(arg));
341 self.count_positions_count += 1;
348 match self.names.get(&name) {
350 // Treat as positional arg.
351 self.verify_arg_type(Exact(idx), ty)
354 let msg = format!("there is no argument named `{}`", name);
355 let sp = if self.is_literal {
356 *self.arg_spans.get(self.curpiece).unwrap_or(&self.fmtsp)
360 let mut err = self.ecx.struct_span_err(sp, &msg[..]);
368 /// Builds the mapping between format placeholders and argument objects.
369 fn build_index_map(&mut self) {
370 // NOTE: Keep the ordering the same as `into_expr`'s expansion would do!
371 let args_len = self.args.len();
372 self.arg_index_map.reserve(args_len);
374 let mut sofar = 0usize;
377 for i in 0..args_len {
378 let ref arg_types = self.arg_types[i];
379 let arg_offsets = arg_types.iter().map(|offset| sofar + *offset).collect::<Vec<_>>();
380 self.arg_index_map.push(arg_offsets);
381 sofar += self.arg_unique_types[i].len();
384 // Record starting index for counts, which appear just after arguments
385 self.count_args_index_offset = sofar;
388 fn rtpath(ecx: &ExtCtxt<'_>, s: &str) -> Vec<ast::Ident> {
389 ecx.std_path(&[sym::fmt, sym::rt, sym::v1, Symbol::intern(s)])
392 fn build_count(&self, c: parse::Count) -> P<ast::Expr> {
394 let count = |c, arg| {
395 let mut path = Context::rtpath(self.ecx, "Count");
396 path.push(self.ecx.ident_of(c));
398 Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]),
399 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
403 parse::CountIs(i) => count("Is", Some(self.ecx.expr_usize(sp, i))),
404 parse::CountIsParam(i) => {
405 // This needs mapping too, as `i` is referring to a macro
406 // argument. If `i` is not found in `count_positions` then
407 // the error had already been emitted elsewhere.
408 let i = self.count_positions.get(&i).cloned().unwrap_or(0)
409 + self.count_args_index_offset;
410 count("Param", Some(self.ecx.expr_usize(sp, i)))
412 parse::CountImplied => count("Implied", None),
413 // should never be the case, names are already resolved
414 parse::CountIsName(_) => panic!("should never happen"),
418 /// Build a literal expression from the accumulated string literals
419 fn build_literal_string(&mut self) -> P<ast::Expr> {
421 let s = Symbol::intern(&self.literal);
422 self.literal.clear();
423 self.ecx.expr_str(sp, s)
426 /// Builds a static `rt::Argument` from a `parse::Piece` or append
427 /// to the `literal` string.
428 fn build_piece(&mut self,
429 piece: &parse::Piece<'_>,
430 arg_index_consumed: &mut Vec<usize>)
431 -> Option<P<ast::Expr>> {
434 parse::String(s) => {
435 self.literal.push_str(s);
438 parse::NextArgument(ref arg) => {
439 // Build the position
442 let mut path = Context::rtpath(self.ecx, "Position");
443 path.push(self.ecx.ident_of(c));
446 let arg = self.ecx.expr_usize(sp, i);
447 self.ecx.expr_call_global(sp, path, vec![arg])
449 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
454 | parse::ArgumentImplicitlyIs(i) => {
455 // Map to index in final generated argument array
456 // in case of multiple types specified
457 let arg_idx = match arg_index_consumed.get_mut(i) {
458 None => 0, // error already emitted elsewhere
460 let ref idx_map = self.arg_index_map[i];
461 // unwrap_or branch: error already emitted elsewhere
462 let arg_idx = *idx_map.get(*offset).unwrap_or(&0);
467 pos("At", Some(arg_idx))
470 // should never be the case, because names are already
472 parse::ArgumentNamed(_) => panic!("should never happen"),
476 let simple_arg = parse::Argument {
478 // We don't have ArgumentNext any more, so we have to
479 // track the current argument ourselves.
484 format: parse::FormatSpec {
485 fill: arg.format.fill,
486 align: parse::AlignUnknown,
488 precision: parse::CountImplied,
489 width: parse::CountImplied,
494 let fill = arg.format.fill.unwrap_or(' ');
497 arg.position.index() == simple_arg.position.index();
499 if !pos_simple || arg.format != simple_arg.format || fill != ' ' {
500 self.all_pieces_simple = false;
504 let fill = self.ecx.expr_lit(sp, ast::LitKind::Char(fill));
506 let mut p = Context::rtpath(self.ecx, "Alignment");
507 p.push(self.ecx.ident_of(name));
508 self.ecx.path_global(sp, p)
510 let align = match arg.format.align {
511 parse::AlignLeft => align("Left"),
512 parse::AlignRight => align("Right"),
513 parse::AlignCenter => align("Center"),
514 parse::AlignUnknown => align("Unknown"),
516 let align = self.ecx.expr_path(align);
517 let flags = self.ecx.expr_u32(sp, arg.format.flags);
518 let prec = self.build_count(arg.format.precision);
519 let width = self.build_count(arg.format.width);
520 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "FormatSpec"));
521 let fmt = self.ecx.expr_struct(
525 self.ecx.field_imm(sp, self.ecx.ident_of("fill"), fill),
526 self.ecx.field_imm(sp, self.ecx.ident_of("align"), align),
527 self.ecx.field_imm(sp, self.ecx.ident_of("flags"), flags),
528 self.ecx.field_imm(sp, self.ecx.ident_of("precision"), prec),
529 self.ecx.field_imm(sp, self.ecx.ident_of("width"), width),
533 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "Argument"));
534 Some(self.ecx.expr_struct(
538 self.ecx.field_imm(sp, self.ecx.ident_of("position"), pos),
539 self.ecx.field_imm(sp, self.ecx.ident_of("format"), fmt),
546 /// Actually builds the expression which the format_args! block will be
548 fn into_expr(self) -> P<ast::Expr> {
549 let mut locals = Vec::with_capacity(
550 (0..self.args.len()).map(|i| self.arg_unique_types[i].len()).sum()
552 let mut counts = Vec::with_capacity(self.count_args.len());
553 let mut pats = Vec::with_capacity(self.args.len());
554 let mut heads = Vec::with_capacity(self.args.len());
556 let names_pos: Vec<_> = (0..self.args.len())
557 .map(|i| self.ecx.ident_of(&format!("arg{}", i)).gensym())
560 // First, build up the static array which will become our precompiled
562 let pieces = self.ecx.expr_vec_slice(self.fmtsp, self.str_pieces);
564 // Before consuming the expressions, we have to remember spans for
565 // count arguments as they are now generated separate from other
566 // arguments, hence have no access to the `P<ast::Expr>`'s.
567 let spans_pos: Vec<_> = self.args.iter().map(|e| e.span.clone()).collect();
569 // Right now there is a bug such that for the expression:
571 // the lifetime of `1` doesn't outlast the call to `bar`, so it's not
572 // valid for the call to `foo`. To work around this all arguments to the
573 // format! string are shoved into locals. Furthermore, we shove the address
574 // of each variable because we don't want to move out of the arguments
575 // passed to this function.
576 for (i, e) in self.args.into_iter().enumerate() {
577 let name = names_pos[i];
579 DUMMY_SP.with_ctxt(e.span.ctxt().apply_mark(self.ecx.current_expansion.mark));
580 pats.push(self.ecx.pat_ident(span, name));
581 for ref arg_ty in self.arg_unique_types[i].iter() {
582 locals.push(Context::format_arg(self.ecx, self.macsp, e.span, arg_ty, name));
584 heads.push(self.ecx.expr_addr_of(e.span, e));
586 for pos in self.count_args {
587 let index = match pos {
589 _ => panic!("should never happen"),
591 let name = names_pos[index];
592 let span = spans_pos[index];
593 counts.push(Context::format_arg(self.ecx, self.macsp, span, &Count, name));
596 // Now create a vector containing all the arguments
597 let args = locals.into_iter().chain(counts.into_iter());
599 let args_array = self.ecx.expr_vec(self.fmtsp, args.collect());
601 // Constructs an AST equivalent to:
603 // match (&arg0, &arg1) {
604 // (tmp0, tmp1) => args_array
613 // Because of #11585 the new temporary lifetime rule, the enclosing
614 // statements for these temporaries become the let's themselves.
615 // If one or more of them are RefCell's, RefCell borrow() will also
616 // end there; they don't last long enough for args_array to use them.
617 // The match expression solves the scope problem.
619 // Note, it may also very well be transformed to:
624 // ref tmp1 => args_array } } }
626 // But the nested match expression is proved to perform not as well
627 // as series of let's; the first approach does.
628 let pat = self.ecx.pat_tuple(self.fmtsp, pats);
629 let arm = self.ecx.arm(self.fmtsp, vec![pat], args_array);
630 let head = self.ecx.expr(self.fmtsp, ast::ExprKind::Tup(heads));
631 let result = self.ecx.expr_match(self.fmtsp, head, vec![arm]);
633 let args_slice = self.ecx.expr_addr_of(self.fmtsp, result);
635 // Now create the fmt::Arguments struct with all our locals we created.
636 let (fn_name, fn_args) = if self.all_pieces_simple {
637 ("new_v1", vec![pieces, args_slice])
639 // Build up the static array which will store our precompiled
640 // nonstandard placeholders, if there are any.
641 let fmt = self.ecx.expr_vec_slice(self.macsp, self.pieces);
643 ("new_v1_formatted", vec![pieces, args_slice, fmt])
646 let path = self.ecx.std_path(&[sym::fmt, sym::Arguments, Symbol::intern(fn_name)]);
647 self.ecx.expr_call_global(self.macsp, path, fn_args)
650 fn format_arg(ecx: &ExtCtxt<'_>,
656 sp = sp.apply_mark(ecx.current_expansion.mark);
657 let arg = ecx.expr_ident(sp, arg);
658 let trait_ = match *ty {
659 Placeholder(ref tyname) => {
671 ecx.span_err(sp, &format!("unknown format trait `{}`", *tyname));
672 return DummyResult::raw_expr(sp, true);
677 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, sym::from_usize]);
678 return ecx.expr_call_global(macsp, path, vec![arg]);
682 let path = ecx.std_path(&[sym::fmt, Symbol::intern(trait_), sym::fmt]);
683 let format_fn = ecx.path_global(sp, path);
684 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, sym::new]);
685 ecx.expr_call_global(macsp, path, vec![arg, ecx.expr_path(format_fn)])
689 pub fn expand_format_args<'cx>(ecx: &'cx mut ExtCtxt<'_>,
691 tts: &[tokenstream::TokenTree])
692 -> Box<dyn base::MacResult + 'cx> {
693 sp = sp.apply_mark(ecx.current_expansion.mark);
694 match parse_args(ecx, sp, tts) {
695 Ok((efmt, args, names)) => {
696 MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt, args, names, false))
700 DummyResult::expr(sp)
705 pub fn expand_format_args_nl<'cx>(
706 ecx: &'cx mut ExtCtxt<'_>,
708 tts: &[tokenstream::TokenTree],
709 ) -> Box<dyn base::MacResult + 'cx> {
710 //if !ecx.ecfg.enable_allow_internal_unstable() {
712 // For some reason, the only one that actually works for `println` is the first check
713 if !sp.allows_unstable(sym::format_args_nl) // the span is marked `#[allow_insternal_unsable]`
714 && !ecx.ecfg.enable_allow_internal_unstable() // NOTE: when is this enabled?
715 && !ecx.ecfg.enable_format_args_nl() // enabled using `#[feature(format_args_nl]`
717 feature_gate::emit_feature_err(&ecx.parse_sess,
720 feature_gate::GateIssue::Language,
721 feature_gate::EXPLAIN_FORMAT_ARGS_NL);
723 sp = sp.apply_mark(ecx.current_expansion.mark);
724 match parse_args(ecx, sp, tts) {
725 Ok((efmt, args, names)) => {
726 MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt, args, names, true))
730 DummyResult::expr(sp)
735 /// Take the various parts of `format_args!(efmt, args..., name=names...)`
736 /// and construct the appropriate formatting expression.
737 pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt<'_>,
740 args: Vec<P<ast::Expr>>,
741 names: FxHashMap<Symbol, usize>,
742 append_newline: bool)
744 // NOTE: this verbose way of initializing `Vec<Vec<ArgumentType>>` is because
745 // `ArgumentType` does not derive `Clone`.
746 let arg_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
747 let arg_unique_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
749 let mut macsp = ecx.call_site();
750 macsp = macsp.apply_mark(ecx.current_expansion.mark);
752 let msg = "format argument must be a string literal";
753 let fmt_sp = efmt.span;
754 let fmt = match expr_to_spanned_string(ecx, efmt, msg) {
755 Ok(mut fmt) if append_newline => {
756 fmt.node.0 = Symbol::intern(&format!("{}\n", fmt.node.0));
761 if let Some(mut err) = err {
762 let sugg_fmt = match args.len() {
763 0 => "{}".to_string(),
764 _ => format!("{}{{}}", "{} ".repeat(args.len())),
767 fmt_sp.shrink_to_lo(),
768 "you might be missing a string literal to format with",
769 format!("\"{}\", ", sugg_fmt),
770 Applicability::MaybeIncorrect,
774 return DummyResult::raw_expr(sp, true);
778 let (is_literal, fmt_snippet) = match ecx.source_map().span_to_snippet(fmt_sp) {
779 Ok(s) => (s.starts_with("\"") || s.starts_with("r#"), Some(s)),
783 let str_style = match fmt.node.1 {
784 ast::StrStyle::Cooked => None,
785 ast::StrStyle::Raw(raw) => {
790 /// Finds the indices of all characters that have been processed and differ between the actual
791 /// written code (code snippet) and the `InternedString` that get's processed in the `Parser`
792 /// in order to properly synthethise the intra-string `Span`s for error diagnostics.
793 fn find_skips(snippet: &str, is_raw: bool) -> Vec<usize> {
794 let mut eat_ws = false;
795 let mut s = snippet.chars().enumerate().peekable();
796 let mut skips = vec![];
797 while let Some((pos, c)) = s.next() {
798 match (c, s.peek()) {
799 // skip whitespace and empty lines ending in '\\'
800 ('\\', Some((next_pos, '\n'))) if !is_raw => {
803 skips.push(*next_pos);
806 ('\\', Some((next_pos, '\n'))) |
807 ('\\', Some((next_pos, 'n'))) |
808 ('\\', Some((next_pos, 't'))) if eat_ws => {
810 skips.push(*next_pos);
815 ('\t', _) if eat_ws => {
818 ('\\', Some((next_pos, 'n'))) |
819 ('\\', Some((next_pos, 't'))) |
820 ('\\', Some((next_pos, '0'))) |
821 ('\\', Some((next_pos, '\\'))) |
822 ('\\', Some((next_pos, '\''))) |
823 ('\\', Some((next_pos, '\"'))) => {
824 skips.push(*next_pos);
827 ('\\', Some((_, 'x'))) if !is_raw => {
828 for _ in 0..3 { // consume `\xAB` literal
829 if let Some((pos, _)) = s.next() {
836 ('\\', Some((_, 'u'))) if !is_raw => {
837 if let Some((pos, _)) = s.next() {
840 if let Some((next_pos, next_c)) = s.next() {
842 skips.push(next_pos);
843 let mut i = 0; // consume up to 6 hexanumeric chars + closing `}`
844 while let (Some((next_pos, c)), true) = (s.next(), i < 7) {
846 skips.push(next_pos);
848 skips.push(next_pos);
855 } else if next_c.is_digit(16) {
856 skips.push(next_pos);
857 // We suggest adding `{` and `}` when appropriate, accept it here as if
859 let mut i = 0; // consume up to 6 hexanumeric chars
860 while let (Some((next_pos, c)), _) = (s.next(), i < 6) {
862 skips.push(next_pos);
871 _ if eat_ws => { // `take_while(|c| c.is_whitespace())`
880 let skips = if let (true, Some(ref snippet)) = (is_literal, fmt_snippet.as_ref()) {
881 let r_start = str_style.map(|r| r + 1).unwrap_or(0);
882 let r_end = str_style.map(|r| r).unwrap_or(0);
883 let s = &snippet[r_start + 1..snippet.len() - r_end - 1];
884 find_skips(s, str_style.is_some())
889 let fmt_str = &*fmt.node.0.as_str(); // for the suggestions below
890 let mut parser = parse::Parser::new(fmt_str, str_style, skips.clone(), append_newline);
892 let mut unverified_pieces = Vec::new();
893 while let Some(piece) = parser.next() {
894 if !parser.errors.is_empty() {
897 unverified_pieces.push(piece);
901 if !parser.errors.is_empty() {
902 let err = parser.errors.remove(0);
903 let sp = fmt.span.from_inner(err.span);
904 let mut e = ecx.struct_span_err(sp, &format!("invalid format string: {}",
906 e.span_label(sp, err.label + " in format string");
907 if let Some(note) = err.note {
910 if let Some((label, span)) = err.secondary_label {
911 let sp = fmt.span.from_inner(span);
912 e.span_label(sp, label);
915 return DummyResult::raw_expr(sp, true);
918 let arg_spans = parser.arg_places.iter()
919 .map(|span| fmt.span.from_inner(*span))
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 num_pos_args = cx.args.len() - cx.names.len();
989 let errs = cx.arg_types
992 .filter(|(i, ty)| ty.is_empty() && !cx.count_positions.contains_key(&i))
994 let msg = if i >= num_pos_args {
996 "named argument never used"
998 // positional argument
999 "argument never used"
1001 (cx.args[i].span, msg)
1003 .collect::<Vec<_>>();
1005 let errs_len = errs.len();
1006 if !errs.is_empty() {
1007 let args_used = cx.arg_types.len() - errs_len;
1008 let args_unused = errs_len;
1012 let (sp, msg) = errs.into_iter().next().unwrap();
1013 let mut diag = cx.ecx.struct_span_err(sp, msg);
1014 diag.span_label(sp, msg);
1017 let mut diag = cx.ecx.struct_span_err(
1018 errs.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
1019 "multiple unused formatting arguments",
1021 diag.span_label(cx.fmtsp, "multiple missing formatting specifiers");
1022 for (sp, msg) in errs {
1023 diag.span_label(sp, msg);
1029 // Used to ensure we only report translations for *one* kind of foreign format.
1030 let mut found_foreign = false;
1031 // Decide if we want to look for foreign formatting directives.
1032 if args_used < args_unused {
1033 use super::format_foreign as foreign;
1035 // The set of foreign substitutions we've explained. This prevents spamming the user
1036 // with `%d should be written as {}` over and over again.
1037 let mut explained = FxHashSet::default();
1039 macro_rules! check_foreign {
1041 let mut show_doc_note = false;
1043 let mut suggestions = vec![];
1044 // account for `"` and account for raw strings `r#`
1045 let padding = str_style.map(|i| i + 2).unwrap_or(1);
1046 for sub in foreign::$kind::iter_subs(fmt_str, padding) {
1047 let trn = match sub.translate() {
1050 // If it has no translation, don't call it out specifically.
1054 let pos = sub.position();
1055 let sub = String::from(sub.as_str());
1056 if explained.contains(&sub) {
1059 explained.insert(sub.clone());
1062 found_foreign = true;
1063 show_doc_note = true;
1066 if let Some(inner_sp) = pos {
1067 let sp = fmt_sp.from_inner(inner_sp);
1068 suggestions.push((sp, trn));
1070 diag.help(&format!("`{}` should be written as `{}`", sub, trn));
1077 " formatting not supported; see the documentation for `std::fmt`",
1080 if suggestions.len() > 0 {
1081 diag.multipart_suggestion(
1082 "format specifiers use curly braces",
1084 Applicability::MachineApplicable,
1090 check_foreign!(printf);
1092 check_foreign!(shell);
1095 if !found_foreign && errs_len == 1 {
1096 diag.span_label(cx.fmtsp, "formatting specifier missing");