]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_builtin_macros/src/format.rs
Rollup merge of #91524 - rukai:fix_extend_from_slice_docs, r=dtolnay
[rust.git] / compiler / rustc_builtin_macros / src / format.rs
1 use ArgumentType::*;
2 use Position::*;
3
4 use rustc_ast as ast;
5 use rustc_ast::ptr::P;
6 use rustc_ast::tokenstream::TokenStream;
7 use rustc_ast::{token, BlockCheckMode, UnsafeSource};
8 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9 use rustc_errors::{pluralize, Applicability, DiagnosticBuilder};
10 use rustc_expand::base::{self, *};
11 use rustc_parse_format as parse;
12 use rustc_span::symbol::{sym, Ident, Symbol};
13 use rustc_span::{MultiSpan, Span};
14
15 use std::borrow::Cow;
16 use std::collections::hash_map::Entry;
17
18 #[derive(PartialEq)]
19 enum ArgumentType {
20     Placeholder(&'static str),
21     Count,
22 }
23
24 enum Position {
25     Exact(usize),
26     Named(Symbol),
27 }
28
29 struct Context<'a, 'b> {
30     ecx: &'a mut ExtCtxt<'b>,
31     /// The macro's call site. References to unstable formatting internals must
32     /// use this span to pass the stability checker.
33     macsp: Span,
34     /// The span of the format string literal.
35     fmtsp: Span,
36
37     /// List of parsed argument expressions.
38     /// Named expressions are resolved early, and are appended to the end of
39     /// argument expressions.
40     ///
41     /// Example showing the various data structures in motion:
42     ///
43     /// * Original: `"{foo:o} {:o} {foo:x} {0:x} {1:o} {:x} {1:x} {0:o}"`
44     /// * Implicit argument resolution: `"{foo:o} {0:o} {foo:x} {0:x} {1:o} {1:x} {1:x} {0:o}"`
45     /// * Name resolution: `"{2:o} {0:o} {2:x} {0:x} {1:o} {1:x} {1:x} {0:o}"`
46     /// * `arg_types` (in JSON): `[[0, 1, 0], [0, 1, 1], [0, 1]]`
47     /// * `arg_unique_types` (in simplified JSON): `[["o", "x"], ["o", "x"], ["o", "x"]]`
48     /// * `names` (in JSON): `{"foo": 2}`
49     args: Vec<P<ast::Expr>>,
50     /// Placeholder slot numbers indexed by argument.
51     arg_types: Vec<Vec<usize>>,
52     /// Unique format specs seen for each argument.
53     arg_unique_types: Vec<Vec<ArgumentType>>,
54     /// Map from named arguments to their resolved indices.
55     names: FxHashMap<Symbol, usize>,
56
57     /// The latest consecutive literal strings, or empty if there weren't any.
58     literal: String,
59
60     /// Collection of the compiled `rt::Argument` structures
61     pieces: Vec<P<ast::Expr>>,
62     /// Collection of string literals
63     str_pieces: Vec<P<ast::Expr>>,
64     /// Stays `true` if all formatting parameters are default (as in "{}{}").
65     all_pieces_simple: bool,
66
67     /// Mapping between positional argument references and indices into the
68     /// final generated static argument array. We record the starting indices
69     /// corresponding to each positional argument, and number of references
70     /// consumed so far for each argument, to facilitate correct `Position`
71     /// mapping in `build_piece`. In effect this can be seen as a "flattened"
72     /// version of `arg_unique_types`.
73     ///
74     /// Again with the example described above in docstring for `args`:
75     ///
76     /// * `arg_index_map` (in JSON): `[[0, 1, 0], [2, 3, 3], [4, 5]]`
77     arg_index_map: Vec<Vec<usize>>,
78
79     /// Starting offset of count argument slots.
80     count_args_index_offset: usize,
81
82     /// Count argument slots and tracking data structures.
83     /// Count arguments are separately tracked for de-duplication in case
84     /// multiple references are made to one argument. For example, in this
85     /// format string:
86     ///
87     /// * Original: `"{:.*} {:.foo$} {1:.*} {:.0$}"`
88     /// * Implicit argument resolution: `"{1:.0$} {2:.foo$} {1:.3$} {4:.0$}"`
89     /// * Name resolution: `"{1:.0$} {2:.5$} {1:.3$} {4:.0$}"`
90     /// * `count_positions` (in JSON): `{0: 0, 5: 1, 3: 2}`
91     /// * `count_args`: `vec![0, 5, 3]`
92     count_args: Vec<usize>,
93     /// Relative slot numbers for count arguments.
94     count_positions: FxHashMap<usize, usize>,
95     /// Number of count slots assigned.
96     count_positions_count: usize,
97
98     /// Current position of the implicit positional arg pointer, as if it
99     /// still existed in this phase of processing.
100     /// Used only for `all_pieces_simple` tracking in `build_piece`.
101     curarg: usize,
102     /// Current piece being evaluated, used for error reporting.
103     curpiece: usize,
104     /// Keep track of invalid references to positional arguments.
105     invalid_refs: Vec<(usize, usize)>,
106     /// Spans of all the formatting arguments, in order.
107     arg_spans: Vec<Span>,
108     /// All the formatting arguments that have formatting flags set, in order for diagnostics.
109     arg_with_formatting: Vec<parse::FormatSpec<'a>>,
110
111     /// Whether this format string came from a string literal, as opposed to a macro.
112     is_literal: bool,
113 }
114
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!
117 /// expressions.
118 ///
119 /// If parsing succeeds, the return value is:
120 ///
121 /// ```text
122 /// Some((fmtstr, parsed arguments, index map for named arguments))
123 /// ```
124 fn parse_args<'a>(
125     ecx: &mut ExtCtxt<'a>,
126     sp: Span,
127     tts: TokenStream,
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();
131
132     let mut p = ecx.new_parser_from_tts(tts);
133
134     if p.token == token::Eof {
135         return Err(ecx.struct_span_err(sp, "requires at least a format string argument"));
136     }
137
138     let first_token = &p.token;
139     let fmtstr = match first_token.kind {
140         token::TokenKind::Literal(token::Lit {
141             kind: token::LitKind::Str | token::LitKind::StrRaw(_),
142             ..
143         }) => {
144             // If the first token is a string literal, then a format expression
145             // is constructed from it.
146             //
147             // This allows us to properly handle cases when the first comma
148             // after the format string is mistakenly replaced with any operator,
149             // which cause the expression parser to eat too much tokens.
150             p.parse_literal_maybe_minus()?
151         }
152         _ => {
153             // Otherwise, we fall back to the expression parser.
154             p.parse_expr()?
155         }
156     };
157
158     let mut first = true;
159     let mut named = false;
160
161     while p.token != token::Eof {
162         if !p.eat(&token::Comma) {
163             if first {
164                 p.clear_expected_tokens();
165             }
166
167             match p.expect(&token::Comma) {
168                 Err(mut err) => {
169                     match token::TokenKind::Comma.similar_tokens() {
170                         Some(tks) if tks.contains(&p.token.kind) => {
171                             // If a similar token is found, then it may be a typo. We
172                             // consider it as a comma, and continue parsing.
173                             err.emit();
174                             p.bump();
175                         }
176                         // Otherwise stop the parsing and return the error.
177                         _ => return Err(err),
178                     }
179                 }
180                 Ok(recovered) => {
181                     assert!(recovered);
182                 }
183             }
184         }
185         first = false;
186         if p.token == token::Eof {
187             break;
188         } // accept trailing commas
189         match p.token.ident() {
190             Some((ident, _)) if p.look_ahead(1, |t| *t == token::Eq) => {
191                 named = true;
192                 p.bump();
193                 p.expect(&token::Eq)?;
194                 let e = p.parse_expr()?;
195                 if let Some(prev) = names.get(&ident.name) {
196                     ecx.struct_span_err(e.span, &format!("duplicate argument named `{}`", ident))
197                         .span_label(args[*prev].span, "previously here")
198                         .span_label(e.span, "duplicate argument")
199                         .emit();
200                     continue;
201                 }
202
203                 // Resolve names into slots early.
204                 // Since all the positional args are already seen at this point
205                 // if the input is valid, we can simply append to the positional
206                 // args. And remember the names.
207                 let slot = args.len();
208                 names.insert(ident.name, slot);
209                 args.push(e);
210             }
211             _ => {
212                 let e = p.parse_expr()?;
213                 if named {
214                     let mut err = ecx.struct_span_err(
215                         e.span,
216                         "positional arguments cannot follow named arguments",
217                     );
218                     err.span_label(e.span, "positional arguments must be before named arguments");
219                     for pos in names.values() {
220                         err.span_label(args[*pos].span, "named argument");
221                     }
222                     err.emit();
223                 }
224                 args.push(e);
225             }
226         }
227     }
228     Ok((fmtstr, args, names))
229 }
230
231 impl<'a, 'b> Context<'a, 'b> {
232     fn resolve_name_inplace(&self, p: &mut parse::Piece<'_>) {
233         // NOTE: the `unwrap_or` branch is needed in case of invalid format
234         // arguments, e.g., `format_args!("{foo}")`.
235         let lookup = |s: Symbol| *self.names.get(&s).unwrap_or(&0);
236
237         match *p {
238             parse::String(_) => {}
239             parse::NextArgument(ref mut arg) => {
240                 if let parse::ArgumentNamed(s) = arg.position {
241                     arg.position = parse::ArgumentIs(lookup(s));
242                 }
243                 if let parse::CountIsName(s) = arg.format.width {
244                     arg.format.width = parse::CountIsParam(lookup(s));
245                 }
246                 if let parse::CountIsName(s) = arg.format.precision {
247                     arg.format.precision = parse::CountIsParam(lookup(s));
248                 }
249             }
250         }
251     }
252
253     /// Verifies one piece of a parse string, and remembers it if valid.
254     /// All errors are not emitted as fatal so we can continue giving errors
255     /// about this and possibly other format strings.
256     fn verify_piece(&mut self, p: &parse::Piece<'_>) {
257         match *p {
258             parse::String(..) => {}
259             parse::NextArgument(ref arg) => {
260                 // width/precision first, if they have implicit positional
261                 // parameters it makes more sense to consume them first.
262                 self.verify_count(arg.format.width);
263                 self.verify_count(arg.format.precision);
264
265                 // argument second, if it's an implicit positional parameter
266                 // it's written second, so it should come after width/precision.
267                 let pos = match arg.position {
268                     parse::ArgumentIs(i) | parse::ArgumentImplicitlyIs(i) => Exact(i),
269                     parse::ArgumentNamed(s) => Named(s),
270                 };
271
272                 let ty = Placeholder(match arg.format.ty {
273                     "" => "Display",
274                     "?" => "Debug",
275                     "e" => "LowerExp",
276                     "E" => "UpperExp",
277                     "o" => "Octal",
278                     "p" => "Pointer",
279                     "b" => "Binary",
280                     "x" => "LowerHex",
281                     "X" => "UpperHex",
282                     _ => {
283                         let fmtsp = self.fmtsp;
284                         let sp = arg.format.ty_span.map(|sp| fmtsp.from_inner(sp));
285                         let mut err = self.ecx.struct_span_err(
286                             sp.unwrap_or(fmtsp),
287                             &format!("unknown format trait `{}`", arg.format.ty),
288                         );
289                         err.note(
290                             "the only appropriate formatting traits are:\n\
291                                 - ``, which uses the `Display` trait\n\
292                                 - `?`, which uses the `Debug` trait\n\
293                                 - `e`, which uses the `LowerExp` trait\n\
294                                 - `E`, which uses the `UpperExp` trait\n\
295                                 - `o`, which uses the `Octal` trait\n\
296                                 - `p`, which uses the `Pointer` trait\n\
297                                 - `b`, which uses the `Binary` trait\n\
298                                 - `x`, which uses the `LowerHex` trait\n\
299                                 - `X`, which uses the `UpperHex` trait",
300                         );
301                         if let Some(sp) = sp {
302                             for (fmt, name) in &[
303                                 ("", "Display"),
304                                 ("?", "Debug"),
305                                 ("e", "LowerExp"),
306                                 ("E", "UpperExp"),
307                                 ("o", "Octal"),
308                                 ("p", "Pointer"),
309                                 ("b", "Binary"),
310                                 ("x", "LowerHex"),
311                                 ("X", "UpperHex"),
312                             ] {
313                                 // FIXME: rustfix (`run-rustfix`) fails to apply suggestions.
314                                 // > "Cannot replace slice of data that was already replaced"
315                                 err.tool_only_span_suggestion(
316                                     sp,
317                                     &format!("use the `{}` trait", name),
318                                     (*fmt).to_string(),
319                                     Applicability::MaybeIncorrect,
320                                 );
321                             }
322                         }
323                         err.emit();
324                         "<invalid>"
325                     }
326                 });
327                 self.verify_arg_type(pos, ty);
328                 self.curpiece += 1;
329             }
330         }
331     }
332
333     fn verify_count(&mut self, c: parse::Count) {
334         match c {
335             parse::CountImplied | parse::CountIs(..) => {}
336             parse::CountIsParam(i) => {
337                 self.verify_arg_type(Exact(i), Count);
338             }
339             parse::CountIsName(s) => {
340                 self.verify_arg_type(Named(s), Count);
341             }
342         }
343     }
344
345     fn describe_num_args(&self) -> Cow<'_, str> {
346         match self.args.len() {
347             0 => "no arguments were given".into(),
348             1 => "there is 1 argument".into(),
349             x => format!("there are {} arguments", x).into(),
350         }
351     }
352
353     /// Handle invalid references to positional arguments. Output different
354     /// errors for the case where all arguments are positional and for when
355     /// there are named arguments or numbered positional arguments in the
356     /// format string.
357     fn report_invalid_references(&self, numbered_position_args: bool) {
358         let mut e;
359         let sp = if !self.arg_spans.is_empty() {
360             // Point at the formatting arguments.
361             MultiSpan::from_spans(self.arg_spans.clone())
362         } else {
363             MultiSpan::from_span(self.fmtsp)
364         };
365         let refs =
366             self.invalid_refs.iter().map(|(r, pos)| (r.to_string(), self.arg_spans.get(*pos)));
367
368         let mut zero_based_note = false;
369
370         let count = self.pieces.len()
371             + self.arg_with_formatting.iter().filter(|fmt| fmt.precision_span.is_some()).count();
372         if self.names.is_empty() && !numbered_position_args && count != self.args.len() {
373             e = self.ecx.struct_span_err(
374                 sp,
375                 &format!(
376                     "{} positional argument{} in format string, but {}",
377                     count,
378                     pluralize!(count),
379                     self.describe_num_args(),
380                 ),
381             );
382             for arg in &self.args {
383                 // Point at the arguments that will be formatted.
384                 e.span_label(arg.span, "");
385             }
386         } else {
387             let (mut refs, spans): (Vec<_>, Vec<_>) = refs.unzip();
388             // Avoid `invalid reference to positional arguments 7 and 7 (there is 1 argument)`
389             // for `println!("{7:7$}", 1);`
390             refs.sort();
391             refs.dedup();
392             let spans: Vec<_> = spans.into_iter().filter_map(|sp| sp.copied()).collect();
393             let sp = if self.arg_spans.is_empty() || spans.is_empty() {
394                 MultiSpan::from_span(self.fmtsp)
395             } else {
396                 MultiSpan::from_spans(spans)
397             };
398             let arg_list = if refs.len() == 1 {
399                 format!("argument {}", refs[0])
400             } else {
401                 let reg = refs.pop().unwrap();
402                 format!("arguments {head} and {tail}", head = refs.join(", "), tail = reg)
403             };
404
405             e = self.ecx.struct_span_err(
406                 sp,
407                 &format!(
408                     "invalid reference to positional {} ({})",
409                     arg_list,
410                     self.describe_num_args()
411                 ),
412             );
413             zero_based_note = true;
414         };
415
416         for fmt in &self.arg_with_formatting {
417             if let Some(span) = fmt.precision_span {
418                 let span = self.fmtsp.from_inner(span);
419                 match fmt.precision {
420                     parse::CountIsParam(pos) if pos > self.args.len() => {
421                         e.span_label(
422                             span,
423                             &format!(
424                                 "this precision flag expects an `usize` argument at position {}, \
425                              but {}",
426                                 pos,
427                                 self.describe_num_args(),
428                             ),
429                         );
430                         zero_based_note = true;
431                     }
432                     parse::CountIsParam(pos) => {
433                         let count = self.pieces.len()
434                             + self
435                                 .arg_with_formatting
436                                 .iter()
437                                 .filter(|fmt| fmt.precision_span.is_some())
438                                 .count();
439                         e.span_label(span, &format!(
440                             "this precision flag adds an extra required argument at position {}, \
441                              which is why there {} expected",
442                             pos,
443                             if count == 1 {
444                                 "is 1 argument".to_string()
445                             } else {
446                                 format!("are {} arguments", count)
447                             },
448                         ));
449                         if let Some(arg) = self.args.get(pos) {
450                             e.span_label(
451                                 arg.span,
452                                 "this parameter corresponds to the precision flag",
453                             );
454                         }
455                         zero_based_note = true;
456                     }
457                     _ => {}
458                 }
459             }
460             if let Some(span) = fmt.width_span {
461                 let span = self.fmtsp.from_inner(span);
462                 match fmt.width {
463                     parse::CountIsParam(pos) if pos > self.args.len() => {
464                         e.span_label(
465                             span,
466                             &format!(
467                                 "this width flag expects an `usize` argument at position {}, \
468                              but {}",
469                                 pos,
470                                 self.describe_num_args(),
471                             ),
472                         );
473                         zero_based_note = true;
474                     }
475                     _ => {}
476                 }
477             }
478         }
479         if zero_based_note {
480             e.note("positional arguments are zero-based");
481         }
482         if !self.arg_with_formatting.is_empty() {
483             e.note(
484                 "for information about formatting flags, visit \
485                     https://doc.rust-lang.org/std/fmt/index.html",
486             );
487         }
488
489         e.emit();
490     }
491
492     /// Actually verifies and tracks a given format placeholder
493     /// (a.k.a. argument).
494     fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
495         match arg {
496             Exact(arg) => {
497                 if self.args.len() <= arg {
498                     self.invalid_refs.push((arg, self.curpiece));
499                     return;
500                 }
501                 match ty {
502                     Placeholder(_) => {
503                         // record every (position, type) combination only once
504                         let seen_ty = &mut self.arg_unique_types[arg];
505                         let i = seen_ty.iter().position(|x| *x == ty).unwrap_or_else(|| {
506                             let i = seen_ty.len();
507                             seen_ty.push(ty);
508                             i
509                         });
510                         self.arg_types[arg].push(i);
511                     }
512                     Count => {
513                         if let Entry::Vacant(e) = self.count_positions.entry(arg) {
514                             let i = self.count_positions_count;
515                             e.insert(i);
516                             self.count_args.push(arg);
517                             self.count_positions_count += 1;
518                         }
519                     }
520                 }
521             }
522
523             Named(name) => {
524                 match self.names.get(&name) {
525                     Some(&idx) => {
526                         // Treat as positional arg.
527                         self.verify_arg_type(Exact(idx), ty)
528                     }
529                     None => {
530                         // For the moment capturing variables from format strings expanded from macros is
531                         // disabled (see RFC #2795)
532                         if self.is_literal {
533                             // Treat this name as a variable to capture from the surrounding scope
534                             let idx = self.args.len();
535                             self.arg_types.push(Vec::new());
536                             self.arg_unique_types.push(Vec::new());
537                             let span = if self.is_literal {
538                                 *self.arg_spans.get(self.curpiece).unwrap_or(&self.fmtsp)
539                             } else {
540                                 self.fmtsp
541                             };
542                             self.args.push(self.ecx.expr_ident(span, Ident::new(name, span)));
543                             self.names.insert(name, idx);
544                             self.verify_arg_type(Exact(idx), ty)
545                         } else {
546                             let msg = format!("there is no argument named `{}`", name);
547                             let sp = if self.is_literal {
548                                 *self.arg_spans.get(self.curpiece).unwrap_or(&self.fmtsp)
549                             } else {
550                                 self.fmtsp
551                             };
552                             let mut err = self.ecx.struct_span_err(sp, &msg[..]);
553
554                             err.note(&format!(
555                                 "did you intend to capture a variable `{}` from \
556                                  the surrounding scope?",
557                                 name
558                             ));
559                             err.note(
560                                 "to avoid ambiguity, `format_args!` cannot capture variables \
561                                  when the format string is expanded from a macro",
562                             );
563
564                             err.emit();
565                         }
566                     }
567                 }
568             }
569         }
570     }
571
572     /// Builds the mapping between format placeholders and argument objects.
573     fn build_index_map(&mut self) {
574         // NOTE: Keep the ordering the same as `into_expr`'s expansion would do!
575         let args_len = self.args.len();
576         self.arg_index_map.reserve(args_len);
577
578         let mut sofar = 0usize;
579
580         // Map the arguments
581         for i in 0..args_len {
582             let arg_types = &self.arg_types[i];
583             let arg_offsets = arg_types.iter().map(|offset| sofar + *offset).collect::<Vec<_>>();
584             self.arg_index_map.push(arg_offsets);
585             sofar += self.arg_unique_types[i].len();
586         }
587
588         // Record starting index for counts, which appear just after arguments
589         self.count_args_index_offset = sofar;
590     }
591
592     fn rtpath(ecx: &ExtCtxt<'_>, s: Symbol) -> Vec<Ident> {
593         ecx.std_path(&[sym::fmt, sym::rt, sym::v1, s])
594     }
595
596     fn build_count(&self, c: parse::Count) -> P<ast::Expr> {
597         let sp = self.macsp;
598         let count = |c, arg| {
599             let mut path = Context::rtpath(self.ecx, sym::Count);
600             path.push(Ident::new(c, sp));
601             match arg {
602                 Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]),
603                 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
604             }
605         };
606         match c {
607             parse::CountIs(i) => count(sym::Is, Some(self.ecx.expr_usize(sp, i))),
608             parse::CountIsParam(i) => {
609                 // This needs mapping too, as `i` is referring to a macro
610                 // argument. If `i` is not found in `count_positions` then
611                 // the error had already been emitted elsewhere.
612                 let i = self.count_positions.get(&i).cloned().unwrap_or(0)
613                     + self.count_args_index_offset;
614                 count(sym::Param, Some(self.ecx.expr_usize(sp, i)))
615             }
616             parse::CountImplied => count(sym::Implied, None),
617             // should never be the case, names are already resolved
618             parse::CountIsName(_) => panic!("should never happen"),
619         }
620     }
621
622     /// Build a literal expression from the accumulated string literals
623     fn build_literal_string(&mut self) -> P<ast::Expr> {
624         let sp = self.fmtsp;
625         let s = Symbol::intern(&self.literal);
626         self.literal.clear();
627         self.ecx.expr_str(sp, s)
628     }
629
630     /// Builds a static `rt::Argument` from a `parse::Piece` or append
631     /// to the `literal` string.
632     fn build_piece(
633         &mut self,
634         piece: &parse::Piece<'a>,
635         arg_index_consumed: &mut Vec<usize>,
636     ) -> Option<P<ast::Expr>> {
637         let sp = self.macsp;
638         match *piece {
639             parse::String(s) => {
640                 self.literal.push_str(s);
641                 None
642             }
643             parse::NextArgument(ref arg) => {
644                 // Build the position
645                 let pos = {
646                     match arg.position {
647                         parse::ArgumentIs(i) | parse::ArgumentImplicitlyIs(i) => {
648                             // Map to index in final generated argument array
649                             // in case of multiple types specified
650                             let arg_idx = match arg_index_consumed.get_mut(i) {
651                                 None => 0, // error already emitted elsewhere
652                                 Some(offset) => {
653                                     let idx_map = &self.arg_index_map[i];
654                                     // unwrap_or branch: error already emitted elsewhere
655                                     let arg_idx = *idx_map.get(*offset).unwrap_or(&0);
656                                     *offset += 1;
657                                     arg_idx
658                                 }
659                             };
660                             self.ecx.expr_usize(sp, arg_idx)
661                         }
662
663                         // should never be the case, because names are already
664                         // resolved.
665                         parse::ArgumentNamed(_) => panic!("should never happen"),
666                     }
667                 };
668
669                 let simple_arg = parse::Argument {
670                     position: {
671                         // We don't have ArgumentNext any more, so we have to
672                         // track the current argument ourselves.
673                         let i = self.curarg;
674                         self.curarg += 1;
675                         parse::ArgumentIs(i)
676                     },
677                     format: parse::FormatSpec {
678                         fill: arg.format.fill,
679                         align: parse::AlignUnknown,
680                         flags: 0,
681                         precision: parse::CountImplied,
682                         precision_span: None,
683                         width: parse::CountImplied,
684                         width_span: None,
685                         ty: arg.format.ty,
686                         ty_span: arg.format.ty_span,
687                     },
688                 };
689
690                 let fill = arg.format.fill.unwrap_or(' ');
691
692                 let pos_simple = arg.position.index() == simple_arg.position.index();
693
694                 if arg.format.precision_span.is_some() || arg.format.width_span.is_some() {
695                     self.arg_with_formatting.push(arg.format);
696                 }
697                 if !pos_simple || arg.format != simple_arg.format || fill != ' ' {
698                     self.all_pieces_simple = false;
699                 }
700
701                 // Build the format
702                 let fill = self.ecx.expr_lit(sp, ast::LitKind::Char(fill));
703                 let align = |name| {
704                     let mut p = Context::rtpath(self.ecx, sym::Alignment);
705                     p.push(Ident::new(name, sp));
706                     self.ecx.path_global(sp, p)
707                 };
708                 let align = match arg.format.align {
709                     parse::AlignLeft => align(sym::Left),
710                     parse::AlignRight => align(sym::Right),
711                     parse::AlignCenter => align(sym::Center),
712                     parse::AlignUnknown => align(sym::Unknown),
713                 };
714                 let align = self.ecx.expr_path(align);
715                 let flags = self.ecx.expr_u32(sp, arg.format.flags);
716                 let prec = self.build_count(arg.format.precision);
717                 let width = self.build_count(arg.format.width);
718                 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, sym::FormatSpec));
719                 let fmt = self.ecx.expr_struct(
720                     sp,
721                     path,
722                     vec![
723                         self.ecx.field_imm(sp, Ident::new(sym::fill, sp), fill),
724                         self.ecx.field_imm(sp, Ident::new(sym::align, sp), align),
725                         self.ecx.field_imm(sp, Ident::new(sym::flags, sp), flags),
726                         self.ecx.field_imm(sp, Ident::new(sym::precision, sp), prec),
727                         self.ecx.field_imm(sp, Ident::new(sym::width, sp), width),
728                     ],
729                 );
730
731                 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, sym::Argument));
732                 Some(self.ecx.expr_struct(
733                     sp,
734                     path,
735                     vec![
736                         self.ecx.field_imm(sp, Ident::new(sym::position, sp), pos),
737                         self.ecx.field_imm(sp, Ident::new(sym::format, sp), fmt),
738                     ],
739                 ))
740             }
741         }
742     }
743
744     /// Actually builds the expression which the format_args! block will be
745     /// expanded to.
746     fn into_expr(self) -> P<ast::Expr> {
747         let mut args = Vec::with_capacity(
748             self.arg_unique_types.iter().map(|v| v.len()).sum::<usize>() + self.count_args.len(),
749         );
750         let mut heads = Vec::with_capacity(self.args.len());
751
752         // First, build up the static array which will become our precompiled
753         // format "string"
754         let pieces = self.ecx.expr_vec_slice(self.fmtsp, self.str_pieces);
755
756         // Before consuming the expressions, we have to remember spans for
757         // count arguments as they are now generated separate from other
758         // arguments, hence have no access to the `P<ast::Expr>`'s.
759         let spans_pos: Vec<_> = self.args.iter().map(|e| e.span).collect();
760
761         // Right now there is a bug such that for the expression:
762         //      foo(bar(&1))
763         // the lifetime of `1` doesn't outlast the call to `bar`, so it's not
764         // valid for the call to `foo`. To work around this all arguments to the
765         // format! string are shoved into locals. Furthermore, we shove the address
766         // of each variable because we don't want to move out of the arguments
767         // passed to this function.
768         for (i, e) in self.args.into_iter().enumerate() {
769             for arg_ty in self.arg_unique_types[i].iter() {
770                 args.push(Context::format_arg(self.ecx, self.macsp, e.span, arg_ty, i));
771             }
772             // use the arg span for `&arg` so that borrowck errors
773             // point to the specific expression passed to the macro
774             // (the span is otherwise unavailable in MIR)
775             heads.push(self.ecx.expr_addr_of(e.span.with_ctxt(self.macsp.ctxt()), e));
776         }
777         for index in self.count_args {
778             let span = spans_pos[index];
779             args.push(Context::format_arg(self.ecx, self.macsp, span, &Count, index));
780         }
781
782         let args_array = self.ecx.expr_vec(self.macsp, args);
783
784         // Constructs an AST equivalent to:
785         //
786         //      match (&arg0, &arg1) {
787         //          (tmp0, tmp1) => args_array
788         //      }
789         //
790         // It was:
791         //
792         //      let tmp0 = &arg0;
793         //      let tmp1 = &arg1;
794         //      args_array
795         //
796         // Because of #11585 the new temporary lifetime rule, the enclosing
797         // statements for these temporaries become the let's themselves.
798         // If one or more of them are RefCell's, RefCell borrow() will also
799         // end there; they don't last long enough for args_array to use them.
800         // The match expression solves the scope problem.
801         //
802         // Note, it may also very well be transformed to:
803         //
804         //      match arg0 {
805         //          ref tmp0 => {
806         //              match arg1 => {
807         //                  ref tmp1 => args_array } } }
808         //
809         // But the nested match expression is proved to perform not as well
810         // as series of let's; the first approach does.
811         let args_match = {
812             let pat = self.ecx.pat_ident(self.macsp, Ident::new(sym::_args, self.macsp));
813             let arm = self.ecx.arm(self.macsp, pat, args_array);
814             let head = self.ecx.expr(self.macsp, ast::ExprKind::Tup(heads));
815             self.ecx.expr_match(self.macsp, head, vec![arm])
816         };
817
818         let args_slice = self.ecx.expr_addr_of(self.macsp, args_match);
819
820         // Now create the fmt::Arguments struct with all our locals we created.
821         let (fn_name, fn_args) = if self.all_pieces_simple {
822             ("new_v1", vec![pieces, args_slice])
823         } else {
824             // Build up the static array which will store our precompiled
825             // nonstandard placeholders, if there are any.
826             let fmt = self.ecx.expr_vec_slice(self.macsp, self.pieces);
827
828             let path = self.ecx.std_path(&[sym::fmt, sym::UnsafeArg, sym::new]);
829             let unsafe_arg = self.ecx.expr_call_global(self.macsp, path, Vec::new());
830             let unsafe_expr = self.ecx.expr_block(P(ast::Block {
831                 stmts: vec![self.ecx.stmt_expr(unsafe_arg)],
832                 id: ast::DUMMY_NODE_ID,
833                 rules: BlockCheckMode::Unsafe(UnsafeSource::CompilerGenerated),
834                 span: self.macsp,
835                 tokens: None,
836                 could_be_bare_literal: false,
837             }));
838
839             ("new_v1_formatted", vec![pieces, args_slice, fmt, unsafe_expr])
840         };
841
842         let path = self.ecx.std_path(&[sym::fmt, sym::Arguments, Symbol::intern(fn_name)]);
843         self.ecx.expr_call_global(self.macsp, path, fn_args)
844     }
845
846     fn format_arg(
847         ecx: &ExtCtxt<'_>,
848         macsp: Span,
849         mut sp: Span,
850         ty: &ArgumentType,
851         arg_index: usize,
852     ) -> P<ast::Expr> {
853         sp = ecx.with_def_site_ctxt(sp);
854         let arg = ecx.expr_ident(sp, Ident::new(sym::_args, sp));
855         let arg = ecx.expr(sp, ast::ExprKind::Field(arg, Ident::new(sym::integer(arg_index), sp)));
856         let trait_ = match *ty {
857             Placeholder(trait_) if trait_ == "<invalid>" => return DummyResult::raw_expr(sp, true),
858             Placeholder(trait_) => trait_,
859             Count => {
860                 let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, sym::from_usize]);
861                 return ecx.expr_call_global(macsp, path, vec![arg]);
862             }
863         };
864
865         let path = ecx.std_path(&[sym::fmt, Symbol::intern(trait_), sym::fmt]);
866         let format_fn = ecx.path_global(sp, path);
867         let path = ecx.std_path(&[sym::fmt, sym::ArgumentV1, sym::new]);
868         ecx.expr_call_global(macsp, path, vec![arg, ecx.expr_path(format_fn)])
869     }
870 }
871
872 fn expand_format_args_impl<'cx>(
873     ecx: &'cx mut ExtCtxt<'_>,
874     mut sp: Span,
875     tts: TokenStream,
876     nl: bool,
877 ) -> Box<dyn base::MacResult + 'cx> {
878     sp = ecx.with_def_site_ctxt(sp);
879     match parse_args(ecx, sp, tts) {
880         Ok((efmt, args, names)) => {
881             MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt, args, names, nl))
882         }
883         Err(mut err) => {
884             err.emit();
885             DummyResult::any(sp)
886         }
887     }
888 }
889
890 pub fn expand_format_args<'cx>(
891     ecx: &'cx mut ExtCtxt<'_>,
892     sp: Span,
893     tts: TokenStream,
894 ) -> Box<dyn base::MacResult + 'cx> {
895     expand_format_args_impl(ecx, sp, tts, false)
896 }
897
898 pub fn expand_format_args_nl<'cx>(
899     ecx: &'cx mut ExtCtxt<'_>,
900     sp: Span,
901     tts: TokenStream,
902 ) -> Box<dyn base::MacResult + 'cx> {
903     expand_format_args_impl(ecx, sp, tts, true)
904 }
905
906 /// Take the various parts of `format_args!(efmt, args..., name=names...)`
907 /// and construct the appropriate formatting expression.
908 pub fn expand_preparsed_format_args(
909     ecx: &mut ExtCtxt<'_>,
910     sp: Span,
911     efmt: P<ast::Expr>,
912     args: Vec<P<ast::Expr>>,
913     names: FxHashMap<Symbol, usize>,
914     append_newline: bool,
915 ) -> P<ast::Expr> {
916     // NOTE: this verbose way of initializing `Vec<Vec<ArgumentType>>` is because
917     // `ArgumentType` does not derive `Clone`.
918     let arg_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
919     let arg_unique_types: Vec<_> = (0..args.len()).map(|_| Vec::new()).collect();
920
921     let mut macsp = ecx.call_site();
922     macsp = ecx.with_def_site_ctxt(macsp);
923
924     let msg = "format argument must be a string literal";
925     let fmt_sp = efmt.span;
926     let efmt_kind_is_lit: bool = matches!(efmt.kind, ast::ExprKind::Lit(_));
927     let (fmt_str, fmt_style, fmt_span) = match expr_to_spanned_string(ecx, efmt, msg) {
928         Ok(mut fmt) if append_newline => {
929             fmt.0 = Symbol::intern(&format!("{}\n", fmt.0));
930             fmt
931         }
932         Ok(fmt) => fmt,
933         Err(err) => {
934             if let Some((mut err, suggested)) = err {
935                 let sugg_fmt = match args.len() {
936                     0 => "{}".to_string(),
937                     _ => format!("{}{{}}", "{} ".repeat(args.len())),
938                 };
939                 if !suggested {
940                     err.span_suggestion(
941                         fmt_sp.shrink_to_lo(),
942                         "you might be missing a string literal to format with",
943                         format!("\"{}\", ", sugg_fmt),
944                         Applicability::MaybeIncorrect,
945                     );
946                 }
947                 err.emit();
948             }
949             return DummyResult::raw_expr(sp, true);
950         }
951     };
952
953     let str_style = match fmt_style {
954         ast::StrStyle::Cooked => None,
955         ast::StrStyle::Raw(raw) => Some(raw as usize),
956     };
957
958     let fmt_str = &fmt_str.as_str(); // for the suggestions below
959     let fmt_snippet = ecx.source_map().span_to_snippet(fmt_sp).ok();
960     let mut parser = parse::Parser::new(
961         fmt_str,
962         str_style,
963         fmt_snippet,
964         append_newline,
965         parse::ParseMode::Format,
966     );
967
968     let mut unverified_pieces = Vec::new();
969     while let Some(piece) = parser.next() {
970         if !parser.errors.is_empty() {
971             break;
972         } else {
973             unverified_pieces.push(piece);
974         }
975     }
976
977     if !parser.errors.is_empty() {
978         let err = parser.errors.remove(0);
979         let sp = if efmt_kind_is_lit {
980             fmt_span.from_inner(err.span)
981         } else {
982             // The format string could be another macro invocation, e.g.:
983             //     format!(concat!("abc", "{}"), 4);
984             // However, `err.span` is an inner span relative to the *result* of
985             // the macro invocation, which is why we would get a nonsensical
986             // result calling `fmt_span.from_inner(err.span)` as above, and
987             // might even end up inside a multibyte character (issue #86085).
988             // Therefore, we conservatively report the error for the entire
989             // argument span here.
990             fmt_span
991         };
992         let mut e = ecx.struct_span_err(sp, &format!("invalid format string: {}", err.description));
993         e.span_label(sp, err.label + " in format string");
994         if let Some(note) = err.note {
995             e.note(&note);
996         }
997         if let Some((label, span)) = err.secondary_label {
998             let sp = fmt_span.from_inner(span);
999             e.span_label(sp, label);
1000         }
1001         e.emit();
1002         return DummyResult::raw_expr(sp, true);
1003     }
1004
1005     let arg_spans = parser.arg_places.iter().map(|span| fmt_span.from_inner(*span)).collect();
1006
1007     let named_pos: FxHashSet<usize> = names.values().cloned().collect();
1008
1009     let mut cx = Context {
1010         ecx,
1011         args,
1012         arg_types,
1013         arg_unique_types,
1014         names,
1015         curarg: 0,
1016         curpiece: 0,
1017         arg_index_map: Vec::new(),
1018         count_args: Vec::new(),
1019         count_positions: FxHashMap::default(),
1020         count_positions_count: 0,
1021         count_args_index_offset: 0,
1022         literal: String::new(),
1023         pieces: Vec::with_capacity(unverified_pieces.len()),
1024         str_pieces: Vec::with_capacity(unverified_pieces.len()),
1025         all_pieces_simple: true,
1026         macsp,
1027         fmtsp: fmt_span,
1028         invalid_refs: Vec::new(),
1029         arg_spans,
1030         arg_with_formatting: Vec::new(),
1031         is_literal: parser.is_literal,
1032     };
1033
1034     // This needs to happen *after* the Parser has consumed all pieces to create all the spans
1035     let pieces = unverified_pieces
1036         .into_iter()
1037         .map(|mut piece| {
1038             cx.verify_piece(&piece);
1039             cx.resolve_name_inplace(&mut piece);
1040             piece
1041         })
1042         .collect::<Vec<_>>();
1043
1044     let numbered_position_args = pieces.iter().any(|arg: &parse::Piece<'_>| match *arg {
1045         parse::String(_) => false,
1046         parse::NextArgument(arg) => matches!(arg.position, parse::Position::ArgumentIs(_)),
1047     });
1048
1049     cx.build_index_map();
1050
1051     let mut arg_index_consumed = vec![0usize; cx.arg_index_map.len()];
1052
1053     for piece in pieces {
1054         if let Some(piece) = cx.build_piece(&piece, &mut arg_index_consumed) {
1055             let s = cx.build_literal_string();
1056             cx.str_pieces.push(s);
1057             cx.pieces.push(piece);
1058         }
1059     }
1060
1061     if !cx.literal.is_empty() {
1062         let s = cx.build_literal_string();
1063         cx.str_pieces.push(s);
1064     }
1065
1066     if !cx.invalid_refs.is_empty() {
1067         cx.report_invalid_references(numbered_position_args);
1068     }
1069
1070     // Make sure that all arguments were used and all arguments have types.
1071     let errs = cx
1072         .arg_types
1073         .iter()
1074         .enumerate()
1075         .filter(|(i, ty)| ty.is_empty() && !cx.count_positions.contains_key(&i))
1076         .map(|(i, _)| {
1077             let msg = if named_pos.contains(&i) {
1078                 // named argument
1079                 "named argument never used"
1080             } else {
1081                 // positional argument
1082                 "argument never used"
1083             };
1084             (cx.args[i].span, msg)
1085         })
1086         .collect::<Vec<_>>();
1087
1088     let errs_len = errs.len();
1089     if !errs.is_empty() {
1090         let args_used = cx.arg_types.len() - errs_len;
1091         let args_unused = errs_len;
1092
1093         let mut diag = {
1094             if let [(sp, msg)] = &errs[..] {
1095                 let mut diag = cx.ecx.struct_span_err(*sp, *msg);
1096                 diag.span_label(*sp, *msg);
1097                 diag
1098             } else {
1099                 let mut diag = cx.ecx.struct_span_err(
1100                     errs.iter().map(|&(sp, _)| sp).collect::<Vec<Span>>(),
1101                     "multiple unused formatting arguments",
1102                 );
1103                 diag.span_label(cx.fmtsp, "multiple missing formatting specifiers");
1104                 for (sp, msg) in errs {
1105                     diag.span_label(sp, msg);
1106                 }
1107                 diag
1108             }
1109         };
1110
1111         // Used to ensure we only report translations for *one* kind of foreign format.
1112         let mut found_foreign = false;
1113         // Decide if we want to look for foreign formatting directives.
1114         if args_used < args_unused {
1115             use super::format_foreign as foreign;
1116
1117             // The set of foreign substitutions we've explained.  This prevents spamming the user
1118             // with `%d should be written as {}` over and over again.
1119             let mut explained = FxHashSet::default();
1120
1121             macro_rules! check_foreign {
1122                 ($kind:ident) => {{
1123                     let mut show_doc_note = false;
1124
1125                     let mut suggestions = vec![];
1126                     // account for `"` and account for raw strings `r#`
1127                     let padding = str_style.map(|i| i + 2).unwrap_or(1);
1128                     for sub in foreign::$kind::iter_subs(fmt_str, padding) {
1129                         let (trn, success) = match sub.translate() {
1130                             Ok(trn) => (trn, true),
1131                             Err(Some(msg)) => (msg, false),
1132
1133                             // If it has no translation, don't call it out specifically.
1134                             _ => continue,
1135                         };
1136
1137                         let pos = sub.position();
1138                         let sub = String::from(sub.as_str());
1139                         if explained.contains(&sub) {
1140                             continue;
1141                         }
1142                         explained.insert(sub.clone());
1143
1144                         if !found_foreign {
1145                             found_foreign = true;
1146                             show_doc_note = true;
1147                         }
1148
1149                         if let Some(inner_sp) = pos {
1150                             let sp = fmt_sp.from_inner(inner_sp);
1151
1152                             if success {
1153                                 suggestions.push((sp, trn));
1154                             } else {
1155                                 diag.span_note(
1156                                     sp,
1157                                     &format!("format specifiers use curly braces, and {}", trn),
1158                                 );
1159                             }
1160                         } else {
1161                             if success {
1162                                 diag.help(&format!("`{}` should be written as `{}`", sub, trn));
1163                             } else {
1164                                 diag.note(&format!(
1165                                     "`{}` should use curly braces, and {}",
1166                                     sub, trn
1167                                 ));
1168                             }
1169                         }
1170                     }
1171
1172                     if show_doc_note {
1173                         diag.note(concat!(
1174                             stringify!($kind),
1175                             " formatting not supported; see the documentation for `std::fmt`",
1176                         ));
1177                     }
1178                     if suggestions.len() > 0 {
1179                         diag.multipart_suggestion(
1180                             "format specifiers use curly braces",
1181                             suggestions,
1182                             Applicability::MachineApplicable,
1183                         );
1184                     }
1185                 }};
1186             }
1187
1188             check_foreign!(printf);
1189             if !found_foreign {
1190                 check_foreign!(shell);
1191             }
1192         }
1193         if !found_foreign && errs_len == 1 {
1194             diag.span_label(cx.fmtsp, "formatting specifier missing");
1195         }
1196
1197         diag.emit();
1198     }
1199
1200     cx.into_expr()
1201 }