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.
26 // Note: copied from rustc_span
27 /// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
28 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
29 pub struct InnerSpan {
35 pub fn new(start: usize, end: usize) -> InnerSpan {
36 InnerSpan { start, end }
40 /// The location and before/after width of a character whose width has changed from its source code
42 #[derive(Copy, Clone, PartialEq, Eq)]
43 pub struct InnerWidthMapping {
44 /// Index of the character in the source
46 /// The inner width in characters
48 /// The transformed width in characters
52 impl InnerWidthMapping {
53 pub fn new(position: usize, before: usize, after: usize) -> InnerWidthMapping {
54 InnerWidthMapping { position, before, after }
58 /// Whether the input string is a literal. If yes, it contains the inner width mappings.
59 #[derive(Clone, PartialEq, Eq)]
60 enum InputStringKind {
62 Literal { width_mappings: Vec<InnerWidthMapping> },
65 /// The type of format string that we are parsing.
66 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
68 /// A normal format string as per `format_args!`.
70 /// An inline assembly template string for `asm!`.
74 #[derive(Copy, Clone)]
75 struct InnerOffset(usize);
78 fn to(self, end: InnerOffset) -> InnerSpan {
79 InnerSpan::new(self.0, end.0)
83 /// A piece is a portion of the format string which represents the next part
84 /// to emit. These are emitted as a stream by the `Parser` class.
85 #[derive(Clone, Debug, PartialEq)]
87 /// A literal string which should directly be emitted
89 /// This describes that formatting should process the next argument (as
90 /// specified inside) for emission.
91 NextArgument(Box<Argument<'a>>),
94 /// Representation of an argument specification.
95 #[derive(Copy, Clone, Debug, PartialEq)]
96 pub struct Argument<'a> {
97 /// Where to find this argument
98 pub position: Position<'a>,
99 /// The span of the position indicator. Includes any whitespace in implicit
100 /// positions (`{ }`).
101 pub position_span: InnerSpan,
102 /// How to format the argument
103 pub format: FormatSpec<'a>,
106 /// Specification for the formatting of an argument in the format string.
107 #[derive(Copy, Clone, Debug, PartialEq)]
108 pub struct FormatSpec<'a> {
109 /// Optionally specified character to fill alignment with.
110 pub fill: Option<char>,
111 /// Optionally specified alignment.
112 pub align: Alignment,
113 /// The `+` or `-` flag.
114 pub sign: Option<Sign>,
119 /// The `x` or `X` flag. (Only for `Debug`.)
120 pub debug_hex: Option<DebugHex>,
121 /// The integer precision to use.
122 pub precision: Count<'a>,
123 /// The span of the precision formatting flag (for diagnostics).
124 pub precision_span: Option<InnerSpan>,
125 /// The string width requested for the resulting format.
126 pub width: Count<'a>,
127 /// The span of the width formatting flag (for diagnostics).
128 pub width_span: Option<InnerSpan>,
129 /// The descriptor string representing the name of the format desired for
130 /// this argument, this can be empty or any number of characters, although
131 /// it is required to be one word.
133 /// The span of the descriptor string (for diagnostics).
134 pub ty_span: Option<InnerSpan>,
137 /// Enum describing where an argument for a format can be located.
138 #[derive(Copy, Clone, Debug, PartialEq)]
139 pub enum Position<'a> {
140 /// The argument is implied to be located at an index
141 ArgumentImplicitlyIs(usize),
142 /// The argument is located at a specific index given in the format,
144 /// The argument has a name.
145 ArgumentNamed(&'a str),
149 pub fn index(&self) -> Option<usize> {
151 ArgumentIs(i, ..) | ArgumentImplicitlyIs(i) => Some(*i),
157 /// Enum of alignments which are supported.
158 #[derive(Copy, Clone, Debug, PartialEq)]
160 /// The value will be aligned to the left.
162 /// The value will be aligned to the right.
164 /// The value will be aligned in the center.
166 /// The value will take on a default alignment.
170 /// Enum for the sign flags.
171 #[derive(Copy, Clone, Debug, PartialEq)]
179 /// Enum for the debug hex flags.
180 #[derive(Copy, Clone, Debug, PartialEq)]
182 /// The `x` flag in `{:x?}`.
184 /// The `X` flag in `{:X?}`.
188 /// A count is used for the precision and width parameters of an integer, and
189 /// can reference either an argument or a literal integer.
190 #[derive(Copy, Clone, Debug, PartialEq)]
192 /// The count is specified explicitly.
194 /// The count is specified by the argument with the given name.
195 CountIsName(&'a str, InnerSpan),
196 /// The count is specified by the argument at the given index.
198 /// The count is specified by a star (like in `{:.*}`) that refers to the argument at the given index.
200 /// The count is implied and cannot be explicitly specified.
204 pub struct ParseError {
205 pub description: string::String,
206 pub note: Option<string::String>,
207 pub label: string::String,
209 pub secondary_label: Option<(string::String, InnerSpan)>,
210 pub should_be_replaced_with_positional_argument: bool,
213 /// The parser structure for interpreting the input format string. This is
214 /// modeled as an iterator over `Piece` structures to form a stream of tokens
217 /// This is a recursive-descent parser for the sake of simplicity, and if
218 /// necessary there's probably lots of room for improvement performance-wise.
219 pub struct Parser<'a> {
222 cur: iter::Peekable<str::CharIndices<'a>>,
223 /// Error messages accumulated during parsing
224 pub errors: Vec<ParseError>,
225 /// Current position of implicit positional argument pointer
227 /// `Some(raw count)` when the string is "raw", used to position spans correctly
228 style: Option<usize>,
229 /// Start and end byte offset of every successfully parsed argument
230 pub arg_places: Vec<InnerSpan>,
231 /// Characters whose length has been changed from their in-code representation
232 width_map: Vec<InnerWidthMapping>,
233 /// Span of the last opening brace seen, used for error reporting
234 last_opening_brace: Option<InnerSpan>,
235 /// Whether the source string is comes from `println!` as opposed to `format!` or `print!`
236 append_newline: bool,
237 /// Whether this formatting string is a literal or it comes from a macro.
238 pub is_literal: bool,
239 /// Start position of the current line.
240 cur_line_start: usize,
241 /// Start and end byte offset of every line of the format string. Excludes
242 /// newline characters and leading whitespace.
243 pub line_spans: Vec<InnerSpan>,
246 impl<'a> Iterator for Parser<'a> {
247 type Item = Piece<'a>;
249 fn next(&mut self) -> Option<Piece<'a>> {
250 if let Some(&(pos, c)) = self.cur.peek() {
253 let curr_last_brace = self.last_opening_brace;
254 let byte_pos = self.to_span_index(pos);
255 let lbrace_end = InnerOffset(byte_pos.0 + self.to_span_width(pos));
256 self.last_opening_brace = Some(byte_pos.to(lbrace_end));
258 if self.consume('{') {
259 self.last_opening_brace = curr_last_brace;
261 Some(String(self.string(pos + 1)))
263 let arg = self.argument(lbrace_end);
264 if let Some(rbrace_pos) = self.must_consume('}') {
266 let lbrace_byte_pos = self.to_span_index(pos);
267 let rbrace_byte_pos = self.to_span_index(rbrace_pos);
269 let width = self.to_span_width(rbrace_pos);
271 self.arg_places.push(
272 lbrace_byte_pos.to(InnerOffset(rbrace_byte_pos.0 + width)),
276 self.suggest_positional_arg_instead_of_captured_arg(arg);
278 Some(NextArgument(Box::new(arg)))
283 if self.consume('}') {
284 Some(String(self.string(pos + 1)))
286 let err_pos = self.to_span_index(pos);
288 "unmatched `}` found",
290 "if you intended to print `}`, you can escape it using `}}`",
296 _ => Some(String(self.string(pos))),
300 let span = self.span(self.cur_line_start, self.input.len());
301 if self.line_spans.last() != Some(&span) {
302 self.line_spans.push(span);
310 impl<'a> Parser<'a> {
311 /// Creates a new parser for the given format string
314 style: Option<usize>,
315 snippet: Option<string::String>,
316 append_newline: bool,
319 let input_string_kind = find_width_map_from_snippet(snippet, style);
320 let (width_map, is_literal) = match input_string_kind {
321 InputStringKind::Literal { width_mappings } => (width_mappings, true),
322 InputStringKind::NotALiteral => (Vec::new(), false),
328 cur: s.char_indices().peekable(),
334 last_opening_brace: None,
342 /// Notifies of an error. The message doesn't actually need to be of type
343 /// String, but I think it does when this eventually uses conditions so it
344 /// might as well start using it now.
345 fn err<S1: Into<string::String>, S2: Into<string::String>>(
351 self.errors.push(ParseError {
352 description: description.into(),
356 secondary_label: None,
357 should_be_replaced_with_positional_argument: false,
361 /// Notifies of an error. The message doesn't actually need to be of type
362 /// String, but I think it does when this eventually uses conditions so it
363 /// might as well start using it now.
365 S1: Into<string::String>,
366 S2: Into<string::String>,
367 S3: Into<string::String>,
375 self.errors.push(ParseError {
376 description: description.into(),
377 note: Some(note.into()),
380 secondary_label: None,
381 should_be_replaced_with_positional_argument: false,
385 /// Optionally consumes the specified character. If the character is not at
386 /// the current position, then the current iterator isn't moved and `false` is
387 /// returned, otherwise the character is consumed and `true` is returned.
388 fn consume(&mut self, c: char) -> bool {
389 self.consume_pos(c).is_some()
392 /// Optionally consumes the specified character. If the character is not at
393 /// the current position, then the current iterator isn't moved and `None` is
394 /// returned, otherwise the character is consumed and the current position is
396 fn consume_pos(&mut self, c: char) -> Option<usize> {
397 if let Some(&(pos, maybe)) = self.cur.peek() {
406 fn remap_pos(&self, mut pos: usize) -> InnerOffset {
407 for width in &self.width_map {
408 if pos > width.position {
409 pos += width.before - width.after;
410 } else if pos == width.position && width.after == 0 {
420 fn to_span_index(&self, pos: usize) -> InnerOffset {
421 // This handles the raw string case, the raw argument is the number of #
422 // in r###"..."### (we need to add one because of the `r`).
423 let raw = self.style.map_or(0, |raw| raw + 1);
424 let pos = self.remap_pos(pos);
425 InnerOffset(raw + pos.0 + 1)
428 fn to_span_width(&self, pos: usize) -> usize {
429 let pos = self.remap_pos(pos);
430 match self.width_map.iter().find(|w| w.position == pos.0) {
436 fn span(&self, start_pos: usize, end_pos: usize) -> InnerSpan {
437 let start = self.to_span_index(start_pos);
438 let end = self.to_span_index(end_pos);
442 /// Forces consumption of the specified character. If the character is not
443 /// found, an error is emitted.
444 fn must_consume(&mut self, c: char) -> Option<usize> {
447 if let Some(&(pos, maybe)) = self.cur.peek() {
452 let pos = self.to_span_index(pos);
453 let description = format!("expected `'}}'`, found `{maybe:?}`");
454 let label = "expected `}`".to_owned();
455 let (note, secondary_label) = if c == '}' {
458 "if you intended to print `{`, you can escape it using `{{`".to_owned(),
460 self.last_opening_brace
461 .map(|sp| ("because of this opening brace".to_owned(), sp)),
466 self.errors.push(ParseError {
472 should_be_replaced_with_positional_argument: false,
477 let description = format!("expected `{c:?}` but string was terminated");
478 // point at closing `"`
479 let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
480 let pos = self.to_span_index(pos);
482 let label = format!("expected `{c:?}`");
483 let (note, secondary_label) = if c == '}' {
486 "if you intended to print `{`, you can escape it using `{{`".to_owned(),
488 self.last_opening_brace
489 .map(|sp| ("because of this opening brace".to_owned(), sp)),
494 self.errors.push(ParseError {
500 should_be_replaced_with_positional_argument: false,
503 self.err(description, format!("expected `{c:?}`"), pos.to(pos));
509 /// Consumes all whitespace characters until the first non-whitespace character
511 while let Some(&(_, c)) = self.cur.peek() {
512 if c.is_whitespace() {
520 /// Parses all of a string which is to be considered a "raw literal" in a
521 /// format string. This is everything outside of the braces.
522 fn string(&mut self, start: usize) -> &'a str {
523 // we may not consume the character, peek the iterator
524 while let Some(&(pos, c)) = self.cur.peek() {
527 return &self.input[start..pos];
529 '\n' if self.is_literal => {
530 self.line_spans.push(self.span(self.cur_line_start, pos));
531 self.cur_line_start = pos + 1;
535 if self.is_literal && pos == self.cur_line_start && c.is_whitespace() {
536 self.cur_line_start = pos + c.len_utf8();
542 &self.input[start..self.input.len()]
545 /// Parses an `Argument` structure, or what's contained within braces inside the format string.
546 fn argument(&mut self, start: InnerOffset) -> Argument<'a> {
547 let pos = self.position();
552 .find(|(_, ch)| !ch.is_whitespace())
553 .map_or(start, |(end, _)| self.to_span_index(end));
554 let position_span = start.to(end);
556 let format = match self.mode {
557 ParseMode::Format => self.format(),
558 ParseMode::InlineAsm => self.inline_asm(),
561 // Resolve position after parsing format spec.
562 let pos = match pos {
563 Some(position) => position,
567 ArgumentImplicitlyIs(i)
571 Argument { position: pos, position_span, format }
574 /// Parses a positional argument for a format. This could either be an
575 /// integer index of an argument, a named argument, or a blank string.
576 /// Returns `Some(parsed_position)` if the position is not implicitly
577 /// consuming a macro argument, `None` if it's the case.
578 fn position(&mut self) -> Option<Position<'a>> {
579 if let Some(i) = self.integer() {
582 match self.cur.peek() {
583 Some(&(_, c)) if rustc_lexer::is_id_start(c) => Some(ArgumentNamed(self.word())),
585 // This is an `ArgumentNext`.
586 // Record the fact and do the resolution after parsing the
587 // format spec, to make things like `{:.*}` work.
593 fn current_pos(&mut self) -> usize {
594 if let Some(&(pos, _)) = self.cur.peek() { pos } else { self.input.len() }
597 /// Parses a format specifier at the current position, returning all of the
598 /// relevant information in the `FormatSpec` struct.
599 fn format(&mut self) -> FormatSpec<'a> {
600 let mut spec = FormatSpec {
607 precision: CountImplied,
608 precision_span: None,
611 ty: &self.input[..0],
614 if !self.consume(':') {
619 if let Some(&(_, c)) = self.cur.peek() {
620 if let Some((_, '>' | '<' | '^')) = self.cur.clone().nth(1) {
626 if self.consume('<') {
627 spec.align = AlignLeft;
628 } else if self.consume('>') {
629 spec.align = AlignRight;
630 } else if self.consume('^') {
631 spec.align = AlignCenter;
634 if self.consume('+') {
635 spec.sign = Some(Sign::Plus);
636 } else if self.consume('-') {
637 spec.sign = Some(Sign::Minus);
640 if self.consume('#') {
641 spec.alternate = true;
643 // Width and precision
644 let mut havewidth = false;
646 if self.consume('0') {
647 // small ambiguity with '0$' as a format string. In theory this is a
648 // '0' flag and then an ill-formatted format string with just a '$'
649 // and no count, but this is better if we instead interpret this as
650 // no '0' flag and '0$' as the width instead.
651 if let Some(end) = self.consume_pos('$') {
652 spec.width = CountIsParam(0);
653 spec.width_span = Some(self.span(end - 1, end + 1));
656 spec.zero_pad = true;
661 let start = self.current_pos();
662 spec.width = self.count(start);
663 if spec.width != CountImplied {
664 let end = self.current_pos();
665 spec.width_span = Some(self.span(start, end));
669 if let Some(start) = self.consume_pos('.') {
670 if self.consume('*') {
671 // Resolve `CountIsNextParam`.
672 // We can do this immediately as `position` is resolved later.
675 spec.precision = CountIsStar(i);
677 spec.precision = self.count(start + 1);
679 let end = self.current_pos();
680 spec.precision_span = Some(self.span(start, end));
683 let ty_span_start = self.current_pos();
684 // Optional radix followed by the actual format specifier
685 if self.consume('x') {
686 if self.consume('?') {
687 spec.debug_hex = Some(DebugHex::Lower);
692 } else if self.consume('X') {
693 if self.consume('?') {
694 spec.debug_hex = Some(DebugHex::Upper);
699 } else if self.consume('?') {
702 spec.ty = self.word();
703 if !spec.ty.is_empty() {
704 let ty_span_end = self.current_pos();
705 spec.ty_span = Some(self.span(ty_span_start, ty_span_end));
711 /// Parses an inline assembly template modifier at the current position, returning the modifier
712 /// in the `ty` field of the `FormatSpec` struct.
713 fn inline_asm(&mut self) -> FormatSpec<'a> {
714 let mut spec = FormatSpec {
721 precision: CountImplied,
722 precision_span: None,
725 ty: &self.input[..0],
728 if !self.consume(':') {
732 let ty_span_start = self.current_pos();
733 spec.ty = self.word();
734 if !spec.ty.is_empty() {
735 let ty_span_end = self.current_pos();
736 spec.ty_span = Some(self.span(ty_span_start, ty_span_end));
742 /// Parses a `Count` parameter at the current position. This does not check
743 /// for 'CountIsNextParam' because that is only used in precision, not
745 fn count(&mut self, start: usize) -> Count<'a> {
746 if let Some(i) = self.integer() {
747 if self.consume('$') { CountIsParam(i) } else { CountIs(i) }
749 let tmp = self.cur.clone();
750 let word = self.word();
754 } else if let Some(end) = self.consume_pos('$') {
755 let name_span = self.span(start, end);
756 CountIsName(word, name_span)
764 /// Parses a word starting at the current position. A word is the same as
765 /// Rust identifier, except that it can't start with `_` character.
766 fn word(&mut self) -> &'a str {
767 let start = match self.cur.peek() {
768 Some(&(pos, c)) if rustc_lexer::is_id_start(c) => {
777 while let Some(&(pos, c)) = self.cur.peek() {
778 if rustc_lexer::is_id_continue(c) {
785 let end = end.unwrap_or(self.input.len());
786 let word = &self.input[start..end];
789 "invalid argument name `_`",
790 "invalid argument name",
791 "argument name cannot be a single underscore",
792 self.span(start, end),
798 fn integer(&mut self) -> Option<usize> {
799 let mut cur: usize = 0;
800 let mut found = false;
801 let mut overflow = false;
802 let start = self.current_pos();
803 while let Some(&(_, c)) = self.cur.peek() {
804 if let Some(i) = c.to_digit(10) {
805 let (tmp, mul_overflow) = cur.overflowing_mul(10);
806 let (tmp, add_overflow) = tmp.overflowing_add(i as usize);
807 if mul_overflow || add_overflow {
819 let end = self.current_pos();
820 let overflowed_int = &self.input[start..end];
823 "integer `{}` does not fit into the type `usize` whose range is `0..={}`",
827 "integer out of range for `usize`",
828 self.span(start, end),
832 if found { Some(cur) } else { None }
835 fn suggest_positional_arg_instead_of_captured_arg(&mut self, arg: Argument<'a>) {
836 if let Some(end) = self.consume_pos('.') {
837 let byte_pos = self.to_span_index(end);
838 let start = InnerOffset(byte_pos.0 + 1);
839 let field = self.argument(start);
840 // We can only parse `foo.bar` field access, any deeper nesting,
841 // or another type of expression, like method calls, are not supported
842 if !self.consume('}') {
845 if let ArgumentNamed(_) = arg.position {
846 if let ArgumentNamed(_) = field.position {
850 description: "field access isn't supported".to_string(),
852 label: "not supported".to_string(),
853 span: InnerSpan::new(arg.position_span.start, field.position_span.end),
854 secondary_label: None,
855 should_be_replaced_with_positional_argument: true,
864 /// Finds the indices of all characters that have been processed and differ between the actual
865 /// written code (code snippet) and the `InternedString` that gets processed in the `Parser`
866 /// in order to properly synthesise the intra-string `Span`s for error diagnostics.
867 fn find_width_map_from_snippet(
868 snippet: Option<string::String>,
869 str_style: Option<usize>,
870 ) -> InputStringKind {
871 let snippet = match snippet {
872 Some(ref s) if s.starts_with('"') || s.starts_with("r\"") || s.starts_with("r#") => s,
873 _ => return InputStringKind::NotALiteral,
876 if str_style.is_some() {
877 return InputStringKind::Literal { width_mappings: Vec::new() };
880 let snippet = &snippet[1..snippet.len() - 1];
882 let mut s = snippet.char_indices();
883 let mut width_mappings = vec![];
884 while let Some((pos, c)) = s.next() {
885 match (c, s.clone().next()) {
886 // skip whitespace and empty lines ending in '\\'
887 ('\\', Some((_, '\n'))) => {
891 while let Some((_, c)) = s.clone().next() {
892 if matches!(c, ' ' | '\n' | '\t') {
900 width_mappings.push(InnerWidthMapping::new(pos, width, 0));
902 ('\\', Some((_, 'n' | 't' | 'r' | '0' | '\\' | '\'' | '\"'))) => {
903 width_mappings.push(InnerWidthMapping::new(pos, 2, 1));
906 ('\\', Some((_, 'x'))) => {
907 // consume `\xAB` literal
909 width_mappings.push(InnerWidthMapping::new(pos, 4, 1));
911 ('\\', Some((_, 'u'))) => {
915 if let Some((_, next_c)) = s.next() {
917 // consume up to 6 hexanumeric chars
919 s.clone().take(6).take_while(|(_, c)| c.is_digit(16)).count();
924 .and_then(|digits| u32::from_str_radix(digits, 16).ok())
925 .and_then(char::from_u32)
926 .map_or(1, char::len_utf8);
928 // Skip the digits, for chars that encode to more than 1 utf-8 byte
929 // exclude as many digits as it is greater than 1 byte
931 // So for a 3 byte character, exclude 2 digits
932 let required_skips = digits_len.saturating_sub(len_utf8.saturating_sub(1));
934 // skip '{' and '}' also
935 width += required_skips + 2;
938 } else if next_c.is_digit(16) {
941 // We suggest adding `{` and `}` when appropriate, accept it here as if
943 let mut i = 0; // consume up to 6 hexanumeric chars
944 while let (Some((_, c)), _) = (s.next(), i < 6) {
955 width_mappings.push(InnerWidthMapping::new(pos, width, 1));
961 InputStringKind::Literal { width_mappings }
964 // Assert a reasonable size for `Piece`
965 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
966 rustc_data_structures::static_assert_size!(Piece<'_>, 16);