1 //! Macro support for format strings
3 //! These structures are used when parsing format strings for the compiler.
4 //! Parsing does not happen at runtime: structures of `std::fmt::rt` are
8 html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/",
9 html_playground_url = "https://play.rust-lang.org/",
10 test(attr(deny(warnings)))
12 #![deny(rustc::untranslatable_diagnostic)]
13 #![deny(rustc::diagnostic_outside_of_impl)]
14 // We want to be able to build this crate with a stable compiler, so no
15 // `#![feature]` attributes should be added.
27 // Note: copied from rustc_span
28 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
29 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
30 pub struct InnerSpan {
36 pub fn new(start: usize, end: usize) -> InnerSpan {
37 InnerSpan { start, end }
41 /// The type of format string that we are parsing.
42 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
44 /// A normal format string as per `format_args!`.
46 /// An inline assembly template string for `asm!`.
50 #[derive(Copy, Clone)]
51 struct InnerOffset(usize);
54 fn to(self, end: InnerOffset) -> InnerSpan {
55 InnerSpan::new(self.0, end.0)
59 /// A piece is a portion of the format string which represents the next part
60 /// to emit. These are emitted as a stream by the `Parser` class.
61 #[derive(Copy, Clone, Debug, PartialEq)]
63 /// A literal string which should directly be emitted
65 /// This describes that formatting should process the next argument (as
66 /// specified inside) for emission.
67 NextArgument(Argument<'a>),
70 /// Representation of an argument specification.
71 #[derive(Copy, Clone, Debug, PartialEq)]
72 pub struct Argument<'a> {
73 /// Where to find this argument
74 pub position: Position<'a>,
75 /// The span of the position indicator. Includes any whitespace in implicit
76 /// positions (`{ }`).
77 pub position_span: InnerSpan,
78 /// How to format the argument
79 pub format: FormatSpec<'a>,
82 /// Specification for the formatting of an argument in the format string.
83 #[derive(Copy, Clone, Debug, PartialEq)]
84 pub struct FormatSpec<'a> {
85 /// Optionally specified character to fill alignment with.
86 pub fill: Option<char>,
87 /// Optionally specified alignment.
89 /// Packed version of various flags provided.
91 /// The integer precision to use.
92 pub precision: Count<'a>,
93 /// The span of the precision formatting flag (for diagnostics).
94 pub precision_span: Option<InnerSpan>,
95 /// The string width requested for the resulting format.
97 /// The span of the width formatting flag (for diagnostics).
98 pub width_span: Option<InnerSpan>,
99 /// The descriptor string representing the name of the format desired for
100 /// this argument, this can be empty or any number of characters, although
101 /// it is required to be one word.
103 /// The span of the descriptor string (for diagnostics).
104 pub ty_span: Option<InnerSpan>,
107 /// Enum describing where an argument for a format can be located.
108 #[derive(Copy, Clone, Debug, PartialEq)]
109 pub enum Position<'a> {
110 /// The argument is implied to be located at an index
111 ArgumentImplicitlyIs(usize),
112 /// The argument is located at a specific index given in the format,
114 /// The argument has a name.
115 ArgumentNamed(&'a str),
119 pub fn index(&self) -> Option<usize> {
121 ArgumentIs(i, ..) | ArgumentImplicitlyIs(i) => Some(*i),
127 /// Enum of alignments which are supported.
128 #[derive(Copy, Clone, Debug, PartialEq)]
130 /// The value will be aligned to the left.
132 /// The value will be aligned to the right.
134 /// The value will be aligned in the center.
136 /// The value will take on a default alignment.
140 /// Various flags which can be applied to format strings. The meaning of these
141 /// flags is defined by the formatters themselves.
142 #[derive(Copy, Clone, Debug, PartialEq)]
144 /// A `+` will be used to denote positive numbers.
146 /// A `-` will be used to denote negative numbers. This is the default.
148 /// An alternate form will be used for the value. In the case of numbers,
149 /// this means that the number will be prefixed with the supplied string.
151 /// For numbers, this means that the number will be padded with zeroes,
152 /// and the sign (`+` or `-`) will precede them.
153 FlagSignAwareZeroPad,
154 /// For Debug / `?`, format integers in lower-case hexadecimal.
156 /// For Debug / `?`, format integers in upper-case hexadecimal.
160 /// A count is used for the precision and width parameters of an integer, and
161 /// can reference either an argument or a literal integer.
162 #[derive(Copy, Clone, Debug, PartialEq)]
164 /// The count is specified explicitly.
166 /// The count is specified by the argument with the given name.
167 CountIsName(&'a str, InnerSpan),
168 /// The count is specified by the argument at the given index.
170 /// The count is specified by a star (like in `{:.*}`) that refers to the argument at the given index.
172 /// The count is implied and cannot be explicitly specified.
176 pub struct ParseError {
177 pub description: string::String,
178 pub note: Option<string::String>,
179 pub label: string::String,
181 pub secondary_label: Option<(string::String, InnerSpan)>,
182 pub should_be_replaced_with_positional_argument: bool,
185 /// The parser structure for interpreting the input format string. This is
186 /// modeled as an iterator over `Piece` structures to form a stream of tokens
189 /// This is a recursive-descent parser for the sake of simplicity, and if
190 /// necessary there's probably lots of room for improvement performance-wise.
191 pub struct Parser<'a> {
194 cur: iter::Peekable<str::CharIndices<'a>>,
195 /// Error messages accumulated during parsing
196 pub errors: Vec<ParseError>,
197 /// Current position of implicit positional argument pointer
199 /// `Some(raw count)` when the string is "raw", used to position spans correctly
200 style: Option<usize>,
201 /// Start and end byte offset of every successfully parsed argument
202 pub arg_places: Vec<InnerSpan>,
203 /// Characters that need to be shifted
205 /// Span of the last opening brace seen, used for error reporting
206 last_opening_brace: Option<InnerSpan>,
207 /// Whether the source string is comes from `println!` as opposed to `format!` or `print!`
208 append_newline: bool,
209 /// Whether this formatting string is a literal or it comes from a macro.
210 pub is_literal: bool,
211 /// Start position of the current line.
212 cur_line_start: usize,
213 /// Start and end byte offset of every line of the format string. Excludes
214 /// newline characters and leading whitespace.
215 pub line_spans: Vec<InnerSpan>,
218 impl<'a> Iterator for Parser<'a> {
219 type Item = Piece<'a>;
221 fn next(&mut self) -> Option<Piece<'a>> {
222 if let Some(&(pos, c)) = self.cur.peek() {
225 let curr_last_brace = self.last_opening_brace;
226 let byte_pos = self.to_span_index(pos);
227 let lbrace_end = InnerOffset(byte_pos.0 + 1);
228 self.last_opening_brace = Some(byte_pos.to(lbrace_end));
230 if self.consume('{') {
231 self.last_opening_brace = curr_last_brace;
233 Some(String(self.string(pos + 1)))
235 let arg = self.argument(lbrace_end);
236 if let Some(rbrace_byte_idx) = self.must_consume('}') {
237 let lbrace_inner_offset = self.to_span_index(pos);
238 let rbrace_inner_offset = self.to_span_index(rbrace_byte_idx);
240 self.arg_places.push(
241 lbrace_inner_offset.to(InnerOffset(rbrace_inner_offset.0 + 1)),
245 self.suggest_positional_arg_instead_of_captured_arg(arg);
247 Some(NextArgument(arg))
252 if self.consume('}') {
253 Some(String(self.string(pos + 1)))
255 let err_pos = self.to_span_index(pos);
257 "unmatched `}` found",
259 "if you intended to print `}`, you can escape it using `}}`",
265 _ => Some(String(self.string(pos))),
269 let span = self.span(self.cur_line_start, self.input.len());
270 if self.line_spans.last() != Some(&span) {
271 self.line_spans.push(span);
279 impl<'a> Parser<'a> {
280 /// Creates a new parser for the given format string
283 style: Option<usize>,
284 snippet: Option<string::String>,
285 append_newline: bool,
288 let (skips, is_literal) = find_skips_from_snippet(snippet, style);
292 cur: s.char_indices().peekable(),
298 last_opening_brace: None,
306 /// Notifies of an error. The message doesn't actually need to be of type
307 /// String, but I think it does when this eventually uses conditions so it
308 /// might as well start using it now.
309 fn err<S1: Into<string::String>, S2: Into<string::String>>(
315 self.errors.push(ParseError {
316 description: description.into(),
320 secondary_label: None,
321 should_be_replaced_with_positional_argument: false,
325 /// Notifies of an error. The message doesn't actually need to be of type
326 /// String, but I think it does when this eventually uses conditions so it
327 /// might as well start using it now.
329 S1: Into<string::String>,
330 S2: Into<string::String>,
331 S3: Into<string::String>,
339 self.errors.push(ParseError {
340 description: description.into(),
341 note: Some(note.into()),
344 secondary_label: None,
345 should_be_replaced_with_positional_argument: false,
349 /// Optionally consumes the specified character. If the character is not at
350 /// the current position, then the current iterator isn't moved and `false` is
351 /// returned, otherwise the character is consumed and `true` is returned.
352 fn consume(&mut self, c: char) -> bool {
353 self.consume_pos(c).is_some()
356 /// Optionally consumes the specified character. If the character is not at
357 /// the current position, then the current iterator isn't moved and `None` is
358 /// returned, otherwise the character is consumed and the current position is
360 fn consume_pos(&mut self, c: char) -> Option<usize> {
361 if let Some(&(pos, maybe)) = self.cur.peek() {
370 fn to_span_index(&self, pos: usize) -> InnerOffset {
372 // This handles the raw string case, the raw argument is the number of #
373 // in r###"..."### (we need to add one because of the `r`).
374 let raw = self.style.map_or(0, |raw| raw + 1);
375 for skip in &self.skips {
378 } else if pos == *skip && raw == 0 {
384 InnerOffset(raw + pos + 1)
387 fn span(&self, start_pos: usize, end_pos: usize) -> InnerSpan {
388 let start = self.to_span_index(start_pos);
389 let end = self.to_span_index(end_pos);
393 /// Forces consumption of the specified character. If the character is not
394 /// found, an error is emitted.
395 fn must_consume(&mut self, c: char) -> Option<usize> {
398 if let Some(&(pos, maybe)) = self.cur.peek() {
403 let pos = self.to_span_index(pos);
404 let description = format!("expected `'}}'`, found `{:?}`", maybe);
405 let label = "expected `}`".to_owned();
406 let (note, secondary_label) = if c == '}' {
409 "if you intended to print `{`, you can escape it using `{{`".to_owned(),
411 self.last_opening_brace
412 .map(|sp| ("because of this opening brace".to_owned(), sp)),
417 self.errors.push(ParseError {
423 should_be_replaced_with_positional_argument: false,
428 let description = format!("expected `{:?}` but string was terminated", c);
429 // point at closing `"`
430 let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
431 let pos = self.to_span_index(pos);
433 let label = format!("expected `{:?}`", c);
434 let (note, secondary_label) = if c == '}' {
437 "if you intended to print `{`, you can escape it using `{{`".to_owned(),
439 self.last_opening_brace
440 .map(|sp| ("because of this opening brace".to_owned(), sp)),
445 self.errors.push(ParseError {
451 should_be_replaced_with_positional_argument: false,
454 self.err(description, format!("expected `{:?}`", c), pos.to(pos));
460 /// Consumes all whitespace characters until the first non-whitespace character
462 while let Some(&(_, c)) = self.cur.peek() {
463 if c.is_whitespace() {
471 /// Parses all of a string which is to be considered a "raw literal" in a
472 /// format string. This is everything outside of the braces.
473 fn string(&mut self, start: usize) -> &'a str {
474 // we may not consume the character, peek the iterator
475 while let Some(&(pos, c)) = self.cur.peek() {
478 return &self.input[start..pos];
480 '\n' if self.is_literal => {
481 self.line_spans.push(self.span(self.cur_line_start, pos));
482 self.cur_line_start = pos + 1;
486 if self.is_literal && pos == self.cur_line_start && c.is_whitespace() {
487 self.cur_line_start = pos + c.len_utf8();
493 &self.input[start..self.input.len()]
496 /// Parses an `Argument` structure, or what's contained within braces inside the format string.
497 fn argument(&mut self, start: InnerOffset) -> Argument<'a> {
498 let pos = self.position();
503 .find(|(_, ch)| !ch.is_whitespace())
504 .map_or(start, |(end, _)| self.to_span_index(end));
505 let position_span = start.to(end);
507 let format = match self.mode {
508 ParseMode::Format => self.format(),
509 ParseMode::InlineAsm => self.inline_asm(),
512 // Resolve position after parsing format spec.
513 let pos = match pos {
514 Some(position) => position,
518 ArgumentImplicitlyIs(i)
522 Argument { position: pos, position_span, format }
525 /// Parses a positional argument for a format. This could either be an
526 /// integer index of an argument, a named argument, or a blank string.
527 /// Returns `Some(parsed_position)` if the position is not implicitly
528 /// consuming a macro argument, `None` if it's the case.
529 fn position(&mut self) -> Option<Position<'a>> {
530 if let Some(i) = self.integer() {
533 match self.cur.peek() {
534 Some(&(_, c)) if rustc_lexer::is_id_start(c) => Some(ArgumentNamed(self.word())),
536 // This is an `ArgumentNext`.
537 // Record the fact and do the resolution after parsing the
538 // format spec, to make things like `{:.*}` work.
544 fn current_pos(&mut self) -> usize {
545 if let Some(&(pos, _)) = self.cur.peek() { pos } else { self.input.len() }
548 /// Parses a format specifier at the current position, returning all of the
549 /// relevant information in the `FormatSpec` struct.
550 fn format(&mut self) -> FormatSpec<'a> {
551 let mut spec = FormatSpec {
555 precision: CountImplied,
556 precision_span: None,
559 ty: &self.input[..0],
562 if !self.consume(':') {
567 if let Some(&(_, c)) = self.cur.peek() {
568 if let Some((_, '>' | '<' | '^')) = self.cur.clone().nth(1) {
574 if self.consume('<') {
575 spec.align = AlignLeft;
576 } else if self.consume('>') {
577 spec.align = AlignRight;
578 } else if self.consume('^') {
579 spec.align = AlignCenter;
582 if self.consume('+') {
583 spec.flags |= 1 << (FlagSignPlus as u32);
584 } else if self.consume('-') {
585 spec.flags |= 1 << (FlagSignMinus as u32);
588 if self.consume('#') {
589 spec.flags |= 1 << (FlagAlternate as u32);
591 // Width and precision
592 let mut havewidth = false;
594 if self.consume('0') {
595 // small ambiguity with '0$' as a format string. In theory this is a
596 // '0' flag and then an ill-formatted format string with just a '$'
597 // and no count, but this is better if we instead interpret this as
598 // no '0' flag and '0$' as the width instead.
599 if let Some(end) = self.consume_pos('$') {
600 spec.width = CountIsParam(0);
601 spec.width_span = Some(self.span(end - 1, end + 1));
604 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
609 let start = self.current_pos();
610 spec.width = self.count(start);
611 if spec.width != CountImplied {
612 let end = self.current_pos();
613 spec.width_span = Some(self.span(start, end));
617 if let Some(start) = self.consume_pos('.') {
618 if self.consume('*') {
619 // Resolve `CountIsNextParam`.
620 // We can do this immediately as `position` is resolved later.
623 spec.precision = CountIsStar(i);
625 spec.precision = self.count(start + 1);
627 let end = self.current_pos();
628 spec.precision_span = Some(self.span(start, end));
631 let ty_span_start = self.current_pos();
632 // Optional radix followed by the actual format specifier
633 if self.consume('x') {
634 if self.consume('?') {
635 spec.flags |= 1 << (FlagDebugLowerHex as u32);
640 } else if self.consume('X') {
641 if self.consume('?') {
642 spec.flags |= 1 << (FlagDebugUpperHex as u32);
647 } else if self.consume('?') {
650 spec.ty = self.word();
651 if !spec.ty.is_empty() {
652 let ty_span_end = self.current_pos();
653 spec.ty_span = Some(self.span(ty_span_start, ty_span_end));
659 /// Parses an inline assembly template modifier at the current position, returning the modifier
660 /// in the `ty` field of the `FormatSpec` struct.
661 fn inline_asm(&mut self) -> FormatSpec<'a> {
662 let mut spec = FormatSpec {
666 precision: CountImplied,
667 precision_span: None,
670 ty: &self.input[..0],
673 if !self.consume(':') {
677 let ty_span_start = self.current_pos();
678 spec.ty = self.word();
679 if !spec.ty.is_empty() {
680 let ty_span_end = self.current_pos();
681 spec.ty_span = Some(self.span(ty_span_start, ty_span_end));
687 /// Parses a `Count` parameter at the current position. This does not check
688 /// for 'CountIsNextParam' because that is only used in precision, not
690 fn count(&mut self, start: usize) -> Count<'a> {
691 if let Some(i) = self.integer() {
692 if self.consume('$') { CountIsParam(i) } else { CountIs(i) }
694 let tmp = self.cur.clone();
695 let word = self.word();
699 } else if let Some(end) = self.consume_pos('$') {
700 let name_span = self.span(start, end);
701 CountIsName(word, name_span)
709 /// Parses a word starting at the current position. A word is the same as
710 /// Rust identifier, except that it can't start with `_` character.
711 fn word(&mut self) -> &'a str {
712 let start = match self.cur.peek() {
713 Some(&(pos, c)) if rustc_lexer::is_id_start(c) => {
722 while let Some(&(pos, c)) = self.cur.peek() {
723 if rustc_lexer::is_id_continue(c) {
730 let end = end.unwrap_or(self.input.len());
731 let word = &self.input[start..end];
734 "invalid argument name `_`",
735 "invalid argument name",
736 "argument name cannot be a single underscore",
737 self.span(start, end),
743 /// Optionally parses an integer at the current position. This doesn't deal
744 /// with overflow at all, it's just accumulating digits.
745 fn integer(&mut self) -> Option<usize> {
747 let mut found = false;
748 while let Some(&(_, c)) = self.cur.peek() {
749 if let Some(i) = c.to_digit(10) {
750 cur = cur * 10 + i as usize;
757 if found { Some(cur) } else { None }
760 fn suggest_positional_arg_instead_of_captured_arg(&mut self, arg: Argument<'a>) {
761 if let Some(end) = self.consume_pos('.') {
762 let byte_pos = self.to_span_index(end);
763 let start = InnerOffset(byte_pos.0 + 1);
764 let field = self.argument(start);
765 // We can only parse `foo.bar` field access, any deeper nesting,
766 // or another type of expression, like method calls, are not supported
767 if !self.consume('}') {
770 if let ArgumentNamed(_) = arg.position {
771 if let ArgumentNamed(_) = field.position {
775 description: "field access isn't supported".to_string(),
777 label: "not supported".to_string(),
778 span: InnerSpan::new(arg.position_span.start, field.position_span.end),
779 secondary_label: None,
780 should_be_replaced_with_positional_argument: true,
789 /// Finds the indices of all characters that have been processed and differ between the actual
790 /// written code (code snippet) and the `InternedString` that gets processed in the `Parser`
791 /// in order to properly synthesise the intra-string `Span`s for error diagnostics.
792 fn find_skips_from_snippet(
793 snippet: Option<string::String>,
794 str_style: Option<usize>,
795 ) -> (Vec<usize>, bool) {
796 let snippet = match snippet {
797 Some(ref s) if s.starts_with('"') || s.starts_with("r\"") || s.starts_with("r#") => s,
798 _ => return (vec![], false),
801 fn find_skips(snippet: &str, is_raw: bool) -> Vec<usize> {
802 let mut s = snippet.char_indices().peekable();
803 let mut skips = vec![];
804 while let Some((pos, c)) = s.next() {
805 match (c, s.peek()) {
806 // skip whitespace and empty lines ending in '\\'
807 ('\\', Some((next_pos, '\n'))) if !is_raw => {
809 skips.push(*next_pos);
812 while let Some((pos, c)) = s.peek() {
813 if matches!(c, ' ' | '\n' | '\t') {
821 ('\\', Some((next_pos, 'n' | 't' | 'r' | '0' | '\\' | '\'' | '\"'))) => {
822 skips.push(*next_pos);
825 ('\\', Some((_, 'x'))) if !is_raw => {
827 // consume `\xAB` literal
828 if let Some((pos, _)) = s.next() {
835 ('\\', Some((_, 'u'))) if !is_raw => {
836 if let Some((pos, _)) = s.next() {
839 if let Some((next_pos, next_c)) = s.next() {
841 skips.push(next_pos);
842 let mut i = 0; // consume up to 6 hexanumeric chars + closing `}`
843 while let (Some((next_pos, c)), true) = (s.next(), i < 7) {
845 skips.push(next_pos);
847 skips.push(next_pos);
854 } else if next_c.is_digit(16) {
855 skips.push(next_pos);
856 // We suggest adding `{` and `}` when appropriate, accept it here as if
858 let mut i = 0; // consume up to 6 hexanumeric chars
859 while let (Some((next_pos, c)), _) = (s.next(), i < 6) {
861 skips.push(next_pos);
876 let r_start = str_style.map_or(0, |r| r + 1);
877 let r_end = str_style.unwrap_or(0);
878 let s = &snippet[r_start + 1..snippet.len() - r_end - 1];
879 (find_skips(s, str_style.is_some()), true)