4 use fmt_macros as parse;
6 use errors::DiagnosticBuilder;
7 use errors::Applicability;
11 use syntax::ext::base::{self, *};
12 use syntax::parse::token;
14 use syntax::symbol::{Symbol, sym};
15 use syntax::tokenstream::TokenStream;
16 use syntax_pos::{MultiSpan, Span};
18 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
20 use std::collections::hash_map::Entry;
33 struct Context<'a, 'b> {
34 ecx: &'a mut ExtCtxt<'b>,
35 /// The macro's call site. References to unstable formatting internals must
36 /// use this span to pass the stability checker.
38 /// The span of the format string literal.
41 /// List of parsed argument expressions.
42 /// Named expressions are resolved early, and are appended to the end of
43 /// argument expressions.
45 /// Example showing the various data structures in motion:
47 /// * Original: `"{foo:o} {:o} {foo:x} {0:x} {1:o} {:x} {1:x} {0:o}"`
48 /// * Implicit argument resolution: `"{foo:o} {0:o} {foo:x} {0:x} {1:o} {1:x} {1:x} {0:o}"`
49 /// * Name resolution: `"{2:o} {0:o} {2:x} {0:x} {1:o} {1:x} {1:x} {0:o}"`
50 /// * `arg_types` (in JSON): `[[0, 1, 0], [0, 1, 1], [0, 1]]`
51 /// * `arg_unique_types` (in simplified JSON): `[["o", "x"], ["o", "x"], ["o", "x"]]`
52 /// * `names` (in JSON): `{"foo": 2}`
53 args: Vec<P<ast::Expr>>,
54 /// Placeholder slot numbers indexed by argument.
55 arg_types: Vec<Vec<usize>>,
56 /// Unique format specs seen for each argument.
57 arg_unique_types: Vec<Vec<ArgumentType>>,
58 /// Map from named arguments to their resolved indices.
59 names: FxHashMap<Symbol, usize>,
61 /// The latest consecutive literal strings, or empty if there weren't any.
64 /// Collection of the compiled `rt::Argument` structures
65 pieces: Vec<P<ast::Expr>>,
66 /// Collection of string literals
67 str_pieces: Vec<P<ast::Expr>>,
68 /// Stays `true` if all formatting parameters are default (as in "{}{}").
69 all_pieces_simple: bool,
71 /// Mapping between positional argument references and indices into the
72 /// final generated static argument array. We record the starting indices
73 /// corresponding to each positional argument, and number of references
74 /// consumed so far for each argument, to facilitate correct `Position`
75 /// mapping in `build_piece`. In effect this can be seen as a "flattened"
76 /// version of `arg_unique_types`.
78 /// Again with the example described above in docstring for `args`:
80 /// * `arg_index_map` (in JSON): `[[0, 1, 0], [2, 3, 3], [4, 5]]`
81 arg_index_map: Vec<Vec<usize>>,
83 /// Starting offset of count argument slots.
84 count_args_index_offset: usize,
86 /// Count argument slots and tracking data structures.
87 /// Count arguments are separately tracked for de-duplication in case
88 /// multiple references are made to one argument. For example, in this
91 /// * Original: `"{:.*} {:.foo$} {1:.*} {:.0$}"`
92 /// * Implicit argument resolution: `"{1:.0$} {2:.foo$} {1:.3$} {4:.0$}"`
93 /// * Name resolution: `"{1:.0$} {2:.5$} {1:.3$} {4:.0$}"`
94 /// * `count_positions` (in JSON): `{0: 0, 5: 1, 3: 2}`
95 /// * `count_args`: `vec![Exact(0), Exact(5), Exact(3)]`
96 count_args: Vec<Position>,
97 /// Relative slot numbers for count arguments.
98 count_positions: FxHashMap<usize, usize>,
99 /// Number of count slots assigned.
100 count_positions_count: usize,
102 /// Current position of the implicit positional arg pointer, as if it
103 /// still existed in this phase of processing.
104 /// Used only for `all_pieces_simple` tracking in `build_piece`.
106 /// Current piece being evaluated, used for error reporting.
108 /// Keep track of invalid references to positional arguments.
109 invalid_refs: Vec<(usize, usize)>,
110 /// Spans of all the formatting arguments, in order.
111 arg_spans: Vec<Span>,
112 /// All the formatting arguments that have formatting flags set, in order for diagnostics.
113 arg_with_formatting: Vec<parse::FormatSpec<'a>>,
114 /// Whether this formatting string is a literal or it comes from a macro.
118 /// Parses the arguments from the given list of tokens, returning the diagnostic
119 /// if there's a parse error so we can continue parsing other format!
122 /// If parsing succeeds, the return value is:
125 /// Some((fmtstr, parsed arguments, index map for named arguments))
128 ecx: &mut ExtCtxt<'a>,
131 ) -> Result<(P<ast::Expr>, Vec<P<ast::Expr>>, FxHashMap<Symbol, usize>), DiagnosticBuilder<'a>> {
132 let mut args = Vec::<P<ast::Expr>>::new();
133 let mut names = FxHashMap::<Symbol, usize>::default();
135 let mut p = ecx.new_parser_from_tts(tts);
137 if p.token == token::Eof {
138 return Err(ecx.struct_span_err(sp, "requires at least a format string argument"));
141 let fmtstr = p.parse_expr()?;
142 let mut first = true;
143 let mut named = false;
145 while p.token != token::Eof {
146 if !p.eat(&token::Comma) {
148 // After `format!(""` we always expect *only* a comma...
149 let mut err = ecx.struct_span_err(p.token.span, "expected token: `,`");
150 err.span_label(p.token.span, "expected `,`");
151 p.maybe_annotate_with_ascription(&mut err, false);
154 // ...after that delegate to `expect` to also include the other expected tokens.
155 return Err(p.expect(&token::Comma).err().unwrap());
159 if p.token == token::Eof {
161 } // accept trailing commas
162 if p.token.is_ident() && p.look_ahead(1, |t| *t == token::Eq) {
164 let name = if let token::Ident(name, _) = p.token.kind {
171 p.expect(&token::Eq)?;
172 let e = p.parse_expr()?;
173 if let Some(prev) = names.get(&name) {
174 ecx.struct_span_err(e.span, &format!("duplicate argument named `{}`", name))
175 .span_note(args[*prev].span, "previously here")
180 // Resolve names into slots early.
181 // Since all the positional args are already seen at this point
182 // if the input is valid, we can simply append to the positional
183 // args. And remember the names.
184 let slot = args.len();
185 names.insert(name, slot);
188 let e = p.parse_expr()?;
190 let mut err = ecx.struct_span_err(
192 "positional arguments cannot follow named arguments",
194 err.span_label(e.span, "positional arguments must be before named arguments");
195 for (_, pos) in &names {
196 err.span_label(args[*pos].span, "named argument");
203 Ok((fmtstr, args, names))
206 impl<'a, 'b> Context<'a, 'b> {
207 fn resolve_name_inplace(&self, p: &mut parse::Piece<'_>) {
208 // NOTE: the `unwrap_or` branch is needed in case of invalid format
209 // arguments, e.g., `format_args!("{foo}")`.
210 let lookup = |s: Symbol| *self.names.get(&s).unwrap_or(&0);
213 parse::String(_) => {}
214 parse::NextArgument(ref mut arg) => {
215 if let parse::ArgumentNamed(s) = arg.position {
216 arg.position = parse::ArgumentIs(lookup(s));
218 if let parse::CountIsName(s) = arg.format.width {
219 arg.format.width = parse::CountIsParam(lookup(s));
221 if let parse::CountIsName(s) = arg.format.precision {
222 arg.format.precision = parse::CountIsParam(lookup(s));
228 /// Verifies one piece of a parse string, and remembers it if valid.
229 /// All errors are not emitted as fatal so we can continue giving errors
230 /// about this and possibly other format strings.
231 fn verify_piece(&mut self, p: &parse::Piece<'_>) {
233 parse::String(..) => {}
234 parse::NextArgument(ref arg) => {
235 // width/precision first, if they have implicit positional
236 // parameters it makes more sense to consume them first.
237 self.verify_count(arg.format.width);
238 self.verify_count(arg.format.precision);
240 // argument second, if it's an implicit positional parameter
241 // it's written second, so it should come after width/precision.
242 let pos = match arg.position {
243 parse::ArgumentIs(i) | parse::ArgumentImplicitlyIs(i) => Exact(i),
244 parse::ArgumentNamed(s) => Named(s),
247 let ty = Placeholder(arg.format.ty.to_string());
248 self.verify_arg_type(pos, ty);
254 fn verify_count(&mut self, c: parse::Count) {
256 parse::CountImplied |
257 parse::CountIs(..) => {}
258 parse::CountIsParam(i) => {
259 self.verify_arg_type(Exact(i), Count);
261 parse::CountIsName(s) => {
262 self.verify_arg_type(Named(s), Count);
267 fn describe_num_args(&self) -> Cow<'_, str> {
268 match self.args.len() {
269 0 => "no arguments were given".into(),
270 1 => "there is 1 argument".into(),
271 x => format!("there are {} arguments", x).into(),
275 /// Handle invalid references to positional arguments. Output different
276 /// errors for the case where all arguments are positional and for when
277 /// there are named arguments or numbered positional arguments in the
279 fn report_invalid_references(&self, numbered_position_args: bool) {
281 let sp = if self.is_literal {
282 MultiSpan::from_spans(self.arg_spans.clone())
284 MultiSpan::from_span(self.fmtsp)
289 .map(|(r, pos)| (r.to_string(), self.arg_spans.get(*pos)));
291 let mut zero_based_note = false;
293 let count = self.pieces.len() + self.arg_with_formatting
295 .filter(|fmt| fmt.precision_span.is_some())
297 if self.names.is_empty() && !numbered_position_args && count != self.args.len() {
298 e = self.ecx.struct_span_err(
301 "{} positional argument{} in format string, but {}",
304 self.describe_num_args(),
308 let (mut refs, spans): (Vec<_>, Vec<_>) = refs.unzip();
309 // Avoid `invalid reference to positional arguments 7 and 7 (there is 1 argument)`
310 // for `println!("{7:7$}", 1);`
313 let (arg_list, mut sp) = if refs.len() == 1 {
314 let spans: Vec<_> = spans.into_iter().filter_map(|sp| sp.map(|sp| *sp)).collect();
316 format!("argument {}", refs[0]),
317 if spans.is_empty() {
318 MultiSpan::from_span(self.fmtsp)
320 MultiSpan::from_spans(spans)
324 let pos = MultiSpan::from_spans(spans.into_iter().map(|s| *s.unwrap()).collect());
325 let reg = refs.pop().unwrap();
328 "arguments {head} and {tail}",
329 head = refs.join(", "),
335 if !self.is_literal {
336 sp = MultiSpan::from_span(self.fmtsp);
339 e = self.ecx.struct_span_err(sp,
340 &format!("invalid reference to positional {} ({})",
342 self.describe_num_args()));
343 zero_based_note = true;
346 for fmt in &self.arg_with_formatting {
347 if let Some(span) = fmt.precision_span {
348 let span = self.fmtsp.from_inner(span);
349 match fmt.precision {
350 parse::CountIsParam(pos) if pos > self.args.len() => {
351 e.span_label(span, &format!(
352 "this precision flag expects an `usize` argument at position {}, \
355 self.describe_num_args(),
357 zero_based_note = true;
359 parse::CountIsParam(pos) => {
360 let count = self.pieces.len() + self.arg_with_formatting
362 .filter(|fmt| fmt.precision_span.is_some())
364 e.span_label(span, &format!(
365 "this precision flag adds an extra required argument at position {}, \
366 which is why there {} expected",
369 "is 1 argument".to_string()
371 format!("are {} arguments", count)
376 "this parameter corresponds to the precision flag",
378 zero_based_note = true;
383 if let Some(span) = fmt.width_span {
384 let span = self.fmtsp.from_inner(span);
386 parse::CountIsParam(pos) if pos > self.args.len() => {
387 e.span_label(span, &format!(
388 "this width flag expects an `usize` argument at position {}, \
391 self.describe_num_args(),
393 zero_based_note = true;
400 e.note("positional arguments are zero-based");
402 if !self.arg_with_formatting.is_empty() {
403 e.note("for information about formatting flags, visit \
404 https://doc.rust-lang.org/std/fmt/index.html");
410 /// Actually verifies and tracks a given format placeholder
411 /// (a.k.a. argument).
412 fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
415 if self.args.len() <= arg {
416 self.invalid_refs.push((arg, self.curpiece));
421 // record every (position, type) combination only once
422 let ref mut seen_ty = self.arg_unique_types[arg];
423 let i = seen_ty.iter().position(|x| *x == ty).unwrap_or_else(|| {
424 let i = seen_ty.len();
428 self.arg_types[arg].push(i);
431 if let Entry::Vacant(e) = self.count_positions.entry(arg) {
432 let i = self.count_positions_count;
434 self.count_args.push(Exact(arg));
435 self.count_positions_count += 1;
442 match self.names.get(&name) {
444 // Treat as positional arg.
445 self.verify_arg_type(Exact(idx), ty)
448 let msg = format!("there is no argument named `{}`", name);
449 let sp = if self.is_literal {
450 *self.arg_spans.get(self.curpiece).unwrap_or(&self.fmtsp)
454 let mut err = self.ecx.struct_span_err(sp, &msg[..]);
462 /// Builds the mapping between format placeholders and argument objects.
463 fn build_index_map(&mut self) {
464 // NOTE: Keep the ordering the same as `into_expr`'s expansion would do!
465 let args_len = self.args.len();
466 self.arg_index_map.reserve(args_len);
468 let mut sofar = 0usize;
471 for i in 0..args_len {
472 let ref arg_types = self.arg_types[i];
473 let arg_offsets = arg_types.iter().map(|offset| sofar + *offset).collect::<Vec<_>>();
474 self.arg_index_map.push(arg_offsets);
475 sofar += self.arg_unique_types[i].len();
478 // Record starting index for counts, which appear just after arguments
479 self.count_args_index_offset = sofar;
482 fn rtpath(ecx: &ExtCtxt<'_>, s: &str) -> Vec<ast::Ident> {
483 ecx.std_path(&[sym::fmt, sym::rt, sym::v1, Symbol::intern(s)])
486 fn build_count(&self, c: parse::Count) -> P<ast::Expr> {
488 let count = |c, arg| {
489 let mut path = Context::rtpath(self.ecx, "Count");
490 path.push(self.ecx.ident_of(c, sp));
492 Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]),
493 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
497 parse::CountIs(i) => count("Is", Some(self.ecx.expr_usize(sp, i))),
498 parse::CountIsParam(i) => {
499 // This needs mapping too, as `i` is referring to a macro
500 // argument. If `i` is not found in `count_positions` then
501 // the error had already been emitted elsewhere.
502 let i = self.count_positions.get(&i).cloned().unwrap_or(0)
503 + self.count_args_index_offset;
504 count("Param", Some(self.ecx.expr_usize(sp, i)))
506 parse::CountImplied => count("Implied", None),
507 // should never be the case, names are already resolved
508 parse::CountIsName(_) => panic!("should never happen"),
512 /// Build a literal expression from the accumulated string literals
513 fn build_literal_string(&mut self) -> P<ast::Expr> {
515 let s = Symbol::intern(&self.literal);
516 self.literal.clear();
517 self.ecx.expr_str(sp, s)
520 /// Builds a static `rt::Argument` from a `parse::Piece` or append
521 /// to the `literal` string.
524 piece: &parse::Piece<'a>,
525 arg_index_consumed: &mut Vec<usize>,
526 ) -> Option<P<ast::Expr>> {
529 parse::String(s) => {
530 self.literal.push_str(s);
533 parse::NextArgument(ref arg) => {
534 // Build the position
537 let mut path = Context::rtpath(self.ecx, "Position");
538 path.push(self.ecx.ident_of(c, sp));
541 let arg = self.ecx.expr_usize(sp, i);
542 self.ecx.expr_call_global(sp, path, vec![arg])
544 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
549 | parse::ArgumentImplicitlyIs(i) => {
550 // Map to index in final generated argument array
551 // in case of multiple types specified
552 let arg_idx = match arg_index_consumed.get_mut(i) {
553 None => 0, // error already emitted elsewhere
555 let ref idx_map = self.arg_index_map[i];
556 // unwrap_or branch: error already emitted elsewhere
557 let arg_idx = *idx_map.get(*offset).unwrap_or(&0);
562 pos("At", Some(arg_idx))
565 // should never be the case, because names are already
567 parse::ArgumentNamed(_) => panic!("should never happen"),
571 let simple_arg = parse::Argument {
573 // We don't have ArgumentNext any more, so we have to
574 // track the current argument ourselves.
579 format: parse::FormatSpec {
580 fill: arg.format.fill,
581 align: parse::AlignUnknown,
583 precision: parse::CountImplied,
584 precision_span: None,
585 width: parse::CountImplied,
591 let fill = arg.format.fill.unwrap_or(' ');
594 arg.position.index() == simple_arg.position.index();
596 if arg.format.precision_span.is_some() || arg.format.width_span.is_some() {
597 self.arg_with_formatting.push(arg.format);
599 if !pos_simple || arg.format != simple_arg.format || fill != ' ' {
600 self.all_pieces_simple = false;
604 let fill = self.ecx.expr_lit(sp, ast::LitKind::Char(fill));
606 let mut p = Context::rtpath(self.ecx, "Alignment");
607 p.push(self.ecx.ident_of(name, sp));
608 self.ecx.path_global(sp, p)
610 let align = match arg.format.align {
611 parse::AlignLeft => align("Left"),
612 parse::AlignRight => align("Right"),
613 parse::AlignCenter => align("Center"),
614 parse::AlignUnknown => align("Unknown"),
616 let align = self.ecx.expr_path(align);
617 let flags = self.ecx.expr_u32(sp, arg.format.flags);
618 let prec = self.build_count(arg.format.precision);
619 let width = self.build_count(arg.format.width);
620 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "FormatSpec"));
621 let fmt = self.ecx.expr_struct(
625 self.ecx.field_imm(sp, self.ecx.ident_of("fill", sp), fill),
626 self.ecx.field_imm(sp, self.ecx.ident_of("align", sp), align),
627 self.ecx.field_imm(sp, self.ecx.ident_of("flags", sp), flags),
628 self.ecx.field_imm(sp, self.ecx.ident_of("precision", sp), prec),
629 self.ecx.field_imm(sp, self.ecx.ident_of("width", sp), width),
633 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "Argument"));
634 Some(self.ecx.expr_struct(
638 self.ecx.field_imm(sp, self.ecx.ident_of("position", sp), pos),
639 self.ecx.field_imm(sp, self.ecx.ident_of("format", sp), fmt),
646 /// Actually builds the expression which the format_args! block will be
648 fn into_expr(self) -> P<ast::Expr> {
649 let mut locals = Vec::with_capacity(
650 (0..self.args.len()).map(|i| self.arg_unique_types[i].len()).sum()
652 let mut counts = Vec::with_capacity(self.count_args.len());
653 let mut pats = Vec::with_capacity(self.args.len());
654 let mut heads = Vec::with_capacity(self.args.len());
656 let names_pos: Vec<_> = (0..self.args.len())
657 .map(|i| self.ecx.ident_of(&format!("arg{}", i), self.macsp))
660 // First, build up the static array which will become our precompiled
662 let pieces = self.ecx.expr_vec_slice(self.fmtsp, self.str_pieces);
664 // Before consuming the expressions, we have to remember spans for
665 // count arguments as they are now generated separate from other
666 // arguments, hence have no access to the `P<ast::Expr>`'s.
667 let spans_pos: Vec<_> = self.args.iter().map(|e| e.span.clone()).collect();
669 // Right now there is a bug such that for the expression:
671 // the lifetime of `1` doesn't outlast the call to `bar`, so it's not
672 // valid for the call to `foo`. To work around this all arguments to the
673 // format! string are shoved into locals. Furthermore, we shove the address
674 // of each variable because we don't want to move out of the arguments
675 // passed to this function.
676 for (i, e) in self.args.into_iter().enumerate() {
677 let name = names_pos[i];
678 let span = self.ecx.with_def_site_ctxt(e.span);
679 pats.push(self.ecx.pat_ident(span, name));
680 for ref arg_ty in self.arg_unique_types[i].iter() {
681 locals.push(Context::format_arg(self.ecx, self.macsp, e.span, arg_ty, name));
683 heads.push(self.ecx.expr_addr_of(e.span, e));
685 for pos in self.count_args {
686 let index = match pos {
688 _ => panic!("should never happen"),
690 let name = names_pos[index];
691 let span = spans_pos[index];
692 counts.push(Context::format_arg(self.ecx, self.macsp, span, &Count, name));
695 // Now create a vector containing all the arguments
696 let args = locals.into_iter().chain(counts.into_iter());
698 let args_array = self.ecx.expr_vec(self.macsp, args.collect());
700 // Constructs an AST equivalent to:
702 // match (&arg0, &arg1) {
703 // (tmp0, tmp1) => args_array
712 // Because of #11585 the new temporary lifetime rule, the enclosing
713 // statements for these temporaries become the let's themselves.
714 // If one or more of them are RefCell's, RefCell borrow() will also
715 // end there; they don't last long enough for args_array to use them.
716 // The match expression solves the scope problem.
718 // Note, it may also very well be transformed to:
723 // ref tmp1 => args_array } } }
725 // But the nested match expression is proved to perform not as well
726 // as series of let's; the first approach does.
727 let pat = self.ecx.pat_tuple(self.macsp, pats);
728 let arm = self.ecx.arm(self.macsp, pat, args_array);
729 let head = self.ecx.expr(self.macsp, ast::ExprKind::Tup(heads));
730 let result = self.ecx.expr_match(self.macsp, head, vec![arm]);
732 let args_slice = self.ecx.expr_addr_of(self.macsp, result);
734 // Now create the fmt::Arguments struct with all our locals we created.
735 let (fn_name, fn_args) = if self.all_pieces_simple {
736 ("new_v1", vec![pieces, args_slice])
738 // Build up the static array which will store our precompiled
739 // nonstandard placeholders, if there are any.
740 let fmt = self.ecx.expr_vec_slice(self.macsp, self.pieces);
742 ("new_v1_formatted", vec![pieces, args_slice, fmt])
745 let path = self.ecx.std_path(&[sym::fmt, sym::Arguments, Symbol::intern(fn_name)]);
746 self.ecx.expr_call_global(self.macsp, path, fn_args)
756 sp = ecx.with_def_site_ctxt(sp);
757 let arg = ecx.expr_ident(sp, arg);
758 let trait_ = match *ty {
759 Placeholder(ref tyname) => {
771 let mut err = ecx.struct_span_err(
773 &format!("unknown format trait `{}`", *tyname),
775 err.note("the only appropriate formatting traits are:\n\
776 - ``, which uses the `Display` trait\n\
777 - `?`, which uses the `Debug` trait\n\
778 - `e`, which uses the `LowerExp` trait\n\
779 - `E`, which uses the `UpperExp` trait\n\
780 - `o`, which uses the `Octal` trait\n\
781 - `p`, which uses the `Pointer` trait\n\
782 - `b`, which uses the `Binary` trait\n\
783 - `x`, which uses the `LowerHex` trait\n\
784 - `X`, which uses the `UpperHex` trait");
786 return DummyResult::raw_expr(sp, true);
791 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, sym::from_usize]);
792 return ecx.expr_call_global(macsp, path, vec![arg]);
796 let path = ecx.std_path(&[sym::fmt, Symbol::intern(trait_), sym::fmt]);
797 let format_fn = ecx.path_global(sp, path);
798 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, sym::new]);
799 ecx.expr_call_global(macsp, path, vec![arg, ecx.expr_path(format_fn)])
803 fn expand_format_args_impl<'cx>(
804 ecx: &'cx mut ExtCtxt<'_>,
808 ) -> Box<dyn base::MacResult + 'cx> {
809 sp = ecx.with_def_site_ctxt(sp);
810 match parse_args(ecx, sp, tts) {
811 Ok((efmt, args, names)) => {
812 MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt, args, names, nl))
821 pub fn expand_format_args<'cx>(
822 ecx: &'cx mut ExtCtxt<'_>,
825 ) -> Box<dyn base::MacResult + 'cx> {
826 expand_format_args_impl(ecx, sp, tts, false)
829 pub fn expand_format_args_nl<'cx>(
830 ecx: &'cx mut ExtCtxt<'_>,
833 ) -> Box<dyn base::MacResult + 'cx> {
834 expand_format_args_impl(ecx, sp, tts, true)
837 /// Take the various parts of `format_args!(efmt, args..., name=names...)`
838 /// and construct the appropriate formatting expression.
839 pub fn expand_preparsed_format_args(
840 ecx: &mut ExtCtxt<'_>,
843 args: Vec<P<ast::Expr>>,
844 names: FxHashMap<Symbol, usize>,
845 append_newline: bool,
847 // NOTE: this verbose way of initializing `Vec<Vec<ArgumentType>>` is because
848 // `ArgumentType` does not derive `Clone`.
849 let arg_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
850 let arg_unique_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
852 let mut macsp = ecx.call_site();
853 macsp = ecx.with_def_site_ctxt(macsp);
855 let msg = "format argument must be a string literal";
856 let fmt_sp = efmt.span;
857 let (fmt_str, fmt_style, fmt_span) = match expr_to_spanned_string(ecx, efmt, msg) {
858 Ok(mut fmt) if append_newline => {
859 fmt.0 = Symbol::intern(&format!("{}\n", fmt.0));
864 if let Some(mut err) = err {
865 let sugg_fmt = match args.len() {
866 0 => "{}".to_string(),
867 _ => format!("{}{{}}", "{} ".repeat(args.len())),
870 fmt_sp.shrink_to_lo(),
871 "you might be missing a string literal to format with",
872 format!("\"{}\", ", sugg_fmt),
873 Applicability::MaybeIncorrect,
877 return DummyResult::raw_expr(sp, true);
881 let (is_literal, fmt_snippet) = match ecx.source_map().span_to_snippet(fmt_sp) {
882 Ok(s) => (s.starts_with("\"") || s.starts_with("r#"), Some(s)),
886 let str_style = match fmt_style {
887 ast::StrStyle::Cooked => None,
888 ast::StrStyle::Raw(raw) => {
893 /// Finds the indices of all characters that have been processed and differ between the actual
894 /// written code (code snippet) and the `InternedString` that get's processed in the `Parser`
895 /// in order to properly synthethise the intra-string `Span`s for error diagnostics.
896 fn find_skips(snippet: &str, is_raw: bool) -> Vec<usize> {
897 let mut eat_ws = false;
898 let mut s = snippet.chars().enumerate().peekable();
899 let mut skips = vec![];
900 while let Some((pos, c)) = s.next() {
901 match (c, s.peek()) {
902 // skip whitespace and empty lines ending in '\\'
903 ('\\', Some((next_pos, '\n'))) if !is_raw => {
906 skips.push(*next_pos);
909 ('\\', Some((next_pos, '\n'))) |
910 ('\\', Some((next_pos, 'n'))) |
911 ('\\', Some((next_pos, 't'))) if eat_ws => {
913 skips.push(*next_pos);
918 ('\t', _) if eat_ws => {
921 ('\\', Some((next_pos, 'n'))) |
922 ('\\', Some((next_pos, 't'))) |
923 ('\\', Some((next_pos, '0'))) |
924 ('\\', Some((next_pos, '\\'))) |
925 ('\\', Some((next_pos, '\''))) |
926 ('\\', Some((next_pos, '\"'))) => {
927 skips.push(*next_pos);
930 ('\\', Some((_, 'x'))) if !is_raw => {
931 for _ in 0..3 { // consume `\xAB` literal
932 if let Some((pos, _)) = s.next() {
939 ('\\', Some((_, 'u'))) if !is_raw => {
940 if let Some((pos, _)) = s.next() {
943 if let Some((next_pos, next_c)) = s.next() {
945 skips.push(next_pos);
946 let mut i = 0; // consume up to 6 hexanumeric chars + closing `}`
947 while let (Some((next_pos, c)), true) = (s.next(), i < 7) {
949 skips.push(next_pos);
951 skips.push(next_pos);
958 } else if next_c.is_digit(16) {
959 skips.push(next_pos);
960 // We suggest adding `{` and `}` when appropriate, accept it here as if
962 let mut i = 0; // consume up to 6 hexanumeric chars
963 while let (Some((next_pos, c)), _) = (s.next(), i < 6) {
965 skips.push(next_pos);
974 _ if eat_ws => { // `take_while(|c| c.is_whitespace())`
983 let skips = if let (true, Some(ref snippet)) = (is_literal, fmt_snippet.as_ref()) {
984 let r_start = str_style.map(|r| r + 1).unwrap_or(0);
985 let r_end = str_style.map(|r| r).unwrap_or(0);
986 let s = &snippet[r_start + 1..snippet.len() - r_end - 1];
987 find_skips(s, str_style.is_some())
992 let fmt_str = &*fmt_str.as_str(); // for the suggestions below
993 let mut parser = parse::Parser::new(fmt_str, str_style, skips, append_newline);
995 let mut unverified_pieces = Vec::new();
996 while let Some(piece) = parser.next() {
997 if !parser.errors.is_empty() {
1000 unverified_pieces.push(piece);
1004 if !parser.errors.is_empty() {
1005 let err = parser.errors.remove(0);
1006 let sp = fmt_span.from_inner(err.span);
1007 let mut e = ecx.struct_span_err(sp, &format!("invalid format string: {}",
1009 e.span_label(sp, err.label + " in format string");
1010 if let Some(note) = err.note {
1013 if let Some((label, span)) = err.secondary_label {
1014 let sp = fmt_span.from_inner(span);
1015 e.span_label(sp, label);
1018 return DummyResult::raw_expr(sp, true);
1021 let arg_spans = parser.arg_places.iter()
1022 .map(|span| fmt_span.from_inner(*span))
1025 let named_pos: FxHashSet<usize> = names.values().cloned().collect();
1027 let mut cx = Context {
1035 arg_index_map: Vec::new(),
1036 count_args: Vec::new(),
1037 count_positions: FxHashMap::default(),
1038 count_positions_count: 0,
1039 count_args_index_offset: 0,
1040 literal: String::new(),
1041 pieces: Vec::with_capacity(unverified_pieces.len()),
1042 str_pieces: Vec::with_capacity(unverified_pieces.len()),
1043 all_pieces_simple: true,
1046 invalid_refs: Vec::new(),
1048 arg_with_formatting: Vec::new(),
1052 // This needs to happen *after* the Parser has consumed all pieces to create all the spans
1053 let pieces = unverified_pieces.into_iter().map(|mut piece| {
1054 cx.verify_piece(&piece);
1055 cx.resolve_name_inplace(&mut piece);
1057 }).collect::<Vec<_>>();
1059 let numbered_position_args = pieces.iter().any(|arg: &parse::Piece<'_>| {
1061 parse::String(_) => false,
1062 parse::NextArgument(arg) => {
1063 match arg.position {
1064 parse::Position::ArgumentIs(_) => true,
1071 cx.build_index_map();
1073 let mut arg_index_consumed = vec![0usize; cx.arg_index_map.len()];
1075 for piece in pieces {
1076 if let Some(piece) = cx.build_piece(&piece, &mut arg_index_consumed) {
1077 let s = cx.build_literal_string();
1078 cx.str_pieces.push(s);
1079 cx.pieces.push(piece);
1083 if !cx.literal.is_empty() {
1084 let s = cx.build_literal_string();
1085 cx.str_pieces.push(s);
1088 if cx.invalid_refs.len() >= 1 {
1089 cx.report_invalid_references(numbered_position_args);
1092 // Make sure that all arguments were used and all arguments have types.
1093 let errs = cx.arg_types
1096 .filter(|(i, ty)| ty.is_empty() && !cx.count_positions.contains_key(&i))
1098 let msg = if named_pos.contains(&i) {
1100 "named argument never used"
1102 // positional argument
1103 "argument never used"
1105 (cx.args[i].span, msg)
1107 .collect::<Vec<_>>();
1109 let errs_len = errs.len();
1110 if !errs.is_empty() {
1111 let args_used = cx.arg_types.len() - errs_len;
1112 let args_unused = errs_len;
1116 let (sp, msg) = errs.into_iter().next().unwrap();
1117 let mut diag = cx.ecx.struct_span_err(sp, msg);
1118 diag.span_label(sp, msg);
1121 let mut diag = cx.ecx.struct_span_err(
1122 errs.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
1123 "multiple unused formatting arguments",
1125 diag.span_label(cx.fmtsp, "multiple missing formatting specifiers");
1126 for (sp, msg) in errs {
1127 diag.span_label(sp, msg);
1133 // Used to ensure we only report translations for *one* kind of foreign format.
1134 let mut found_foreign = false;
1135 // Decide if we want to look for foreign formatting directives.
1136 if args_used < args_unused {
1137 use super::format_foreign as foreign;
1139 // The set of foreign substitutions we've explained. This prevents spamming the user
1140 // with `%d should be written as {}` over and over again.
1141 let mut explained = FxHashSet::default();
1143 macro_rules! check_foreign {
1145 let mut show_doc_note = false;
1147 let mut suggestions = vec![];
1148 // account for `"` and account for raw strings `r#`
1149 let padding = str_style.map(|i| i + 2).unwrap_or(1);
1150 for sub in foreign::$kind::iter_subs(fmt_str, padding) {
1151 let trn = match sub.translate() {
1154 // If it has no translation, don't call it out specifically.
1158 let pos = sub.position();
1159 let sub = String::from(sub.as_str());
1160 if explained.contains(&sub) {
1163 explained.insert(sub.clone());
1166 found_foreign = true;
1167 show_doc_note = true;
1170 if let Some(inner_sp) = pos {
1171 let sp = fmt_sp.from_inner(inner_sp);
1172 suggestions.push((sp, trn));
1174 diag.help(&format!("`{}` should be written as `{}`", sub, trn));
1181 " formatting not supported; see the documentation for `std::fmt`",
1184 if suggestions.len() > 0 {
1185 diag.multipart_suggestion(
1186 "format specifiers use curly braces",
1188 Applicability::MachineApplicable,
1194 check_foreign!(printf);
1196 check_foreign!(shell);
1199 if !found_foreign && errs_len == 1 {
1200 diag.span_label(cx.fmtsp, "formatting specifier missing");