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)))
13 #![feature(bool_to_option)]
25 use rustc_span::{InnerSpan, Symbol};
27 /// The type of format string that we are parsing.
28 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
30 /// A normal format string as per `format_args!`.
32 /// An inline assembly template string for `asm!`.
36 #[derive(Copy, Clone)]
37 struct InnerOffset(usize);
40 fn to(self, end: InnerOffset) -> InnerSpan {
41 InnerSpan::new(self.0, end.0)
45 /// A piece is a portion of the format string which represents the next part
46 /// to emit. These are emitted as a stream by the `Parser` class.
47 #[derive(Copy, Clone, Debug, PartialEq)]
49 /// A literal string which should directly be emitted
51 /// This describes that formatting should process the next argument (as
52 /// specified inside) for emission.
53 NextArgument(Argument<'a>),
56 /// Representation of an argument specification.
57 #[derive(Copy, Clone, Debug, PartialEq)]
58 pub struct Argument<'a> {
59 /// Where to find this argument
60 pub position: Position,
61 /// How to format the argument
62 pub format: FormatSpec<'a>,
65 /// Specification for the formatting of an argument in the format string.
66 #[derive(Copy, Clone, Debug, PartialEq)]
67 pub struct FormatSpec<'a> {
68 /// Optionally specified character to fill alignment with.
69 pub fill: Option<char>,
70 /// Optionally specified alignment.
72 /// Packed version of various flags provided.
74 /// The integer precision to use.
76 /// The span of the precision formatting flag (for diagnostics).
77 pub precision_span: Option<InnerSpan>,
78 /// The string width requested for the resulting format.
80 /// The span of the width formatting flag (for diagnostics).
81 pub width_span: Option<InnerSpan>,
82 /// The descriptor string representing the name of the format desired for
83 /// this argument, this can be empty or any number of characters, although
84 /// it is required to be one word.
86 /// The span of the descriptor string (for diagnostics).
87 pub ty_span: Option<InnerSpan>,
90 /// Enum describing where an argument for a format can be located.
91 #[derive(Copy, Clone, Debug, PartialEq)]
93 /// The argument is implied to be located at an index
94 ArgumentImplicitlyIs(usize),
95 /// The argument is located at a specific index given in the format
97 /// The argument has a name.
98 ArgumentNamed(Symbol, InnerSpan),
102 pub fn index(&self) -> Option<usize> {
104 ArgumentIs(i) | ArgumentImplicitlyIs(i) => Some(*i),
110 /// Enum of alignments which are supported.
111 #[derive(Copy, Clone, Debug, PartialEq)]
113 /// The value will be aligned to the left.
115 /// The value will be aligned to the right.
117 /// The value will be aligned in the center.
119 /// The value will take on a default alignment.
123 /// Various flags which can be applied to format strings. The meaning of these
124 /// flags is defined by the formatters themselves.
125 #[derive(Copy, Clone, Debug, PartialEq)]
127 /// A `+` will be used to denote positive numbers.
129 /// A `-` will be used to denote negative numbers. This is the default.
131 /// An alternate form will be used for the value. In the case of numbers,
132 /// this means that the number will be prefixed with the supplied string.
134 /// For numbers, this means that the number will be padded with zeroes,
135 /// and the sign (`+` or `-`) will precede them.
136 FlagSignAwareZeroPad,
137 /// For Debug / `?`, format integers in lower-case hexadecimal.
139 /// For Debug / `?`, format integers in upper-case hexadecimal.
143 /// A count is used for the precision and width parameters of an integer, and
144 /// can reference either an argument or a literal integer.
145 #[derive(Copy, Clone, Debug, PartialEq)]
147 /// The count is specified explicitly.
149 /// The count is specified by the argument with the given name.
150 CountIsName(Symbol, InnerSpan),
151 /// The count is specified by the argument at the given index.
153 /// The count is implied and cannot be explicitly specified.
157 pub struct ParseError {
158 pub description: string::String,
159 pub note: Option<string::String>,
160 pub label: string::String,
162 pub secondary_label: Option<(string::String, InnerSpan)>,
165 /// The parser structure for interpreting the input format string. This is
166 /// modeled as an iterator over `Piece` structures to form a stream of tokens
169 /// This is a recursive-descent parser for the sake of simplicity, and if
170 /// necessary there's probably lots of room for improvement performance-wise.
171 pub struct Parser<'a> {
174 cur: iter::Peekable<str::CharIndices<'a>>,
175 /// Error messages accumulated during parsing
176 pub errors: Vec<ParseError>,
177 /// Current position of implicit positional argument pointer
179 /// `Some(raw count)` when the string is "raw", used to position spans correctly
180 style: Option<usize>,
181 /// Start and end byte offset of every successfully parsed argument
182 pub arg_places: Vec<InnerSpan>,
183 /// Characters that need to be shifted
185 /// Span of the last opening brace seen, used for error reporting
186 last_opening_brace: Option<InnerSpan>,
187 /// Whether the source string is comes from `println!` as opposed to `format!` or `print!`
188 append_newline: bool,
189 /// Whether this formatting string is a literal or it comes from a macro.
190 pub is_literal: bool,
191 /// Start position of the current line.
192 cur_line_start: usize,
193 /// Start and end byte offset of every line of the format string. Excludes
194 /// newline characters and leading whitespace.
195 pub line_spans: Vec<InnerSpan>,
198 impl<'a> Iterator for Parser<'a> {
199 type Item = Piece<'a>;
201 fn next(&mut self) -> Option<Piece<'a>> {
202 if let Some(&(pos, c)) = self.cur.peek() {
205 let curr_last_brace = self.last_opening_brace;
206 let byte_pos = self.to_span_index(pos);
207 self.last_opening_brace = Some(byte_pos.to(InnerOffset(byte_pos.0 + 1)));
209 if self.consume('{') {
210 self.last_opening_brace = curr_last_brace;
212 Some(String(self.string(pos + 1)))
214 let arg = self.argument();
215 if let Some(rbrace_byte_idx) = self.must_consume('}') {
216 let lbrace_inner_offset = self.to_span_index(pos);
217 let rbrace_inner_offset = self.to_span_index(rbrace_byte_idx);
219 self.arg_places.push(
220 lbrace_inner_offset.to(InnerOffset(rbrace_inner_offset.0 + 1)),
224 Some(NextArgument(arg))
229 if self.consume('}') {
230 Some(String(self.string(pos + 1)))
232 let err_pos = self.to_span_index(pos);
234 "unmatched `}` found",
236 "if you intended to print `}`, you can escape it using `}}`",
242 _ => Some(String(self.string(pos))),
246 let start = self.to_span_index(self.cur_line_start);
247 let end = self.to_span_index(self.input.len());
248 let span = start.to(end);
249 if self.line_spans.last() != Some(&span) {
250 self.line_spans.push(span);
258 impl<'a> Parser<'a> {
259 /// Creates a new parser for the given format string
262 style: Option<usize>,
263 snippet: Option<string::String>,
264 append_newline: bool,
267 let (skips, is_literal) = find_skips_from_snippet(snippet, style);
271 cur: s.char_indices().peekable(),
277 last_opening_brace: None,
285 /// Notifies of an error. The message doesn't actually need to be of type
286 /// String, but I think it does when this eventually uses conditions so it
287 /// might as well start using it now.
288 fn err<S1: Into<string::String>, S2: Into<string::String>>(
294 self.errors.push(ParseError {
295 description: description.into(),
299 secondary_label: None,
303 /// Notifies of an error. The message doesn't actually need to be of type
304 /// String, but I think it does when this eventually uses conditions so it
305 /// might as well start using it now.
307 S1: Into<string::String>,
308 S2: Into<string::String>,
309 S3: Into<string::String>,
317 self.errors.push(ParseError {
318 description: description.into(),
319 note: Some(note.into()),
322 secondary_label: None,
326 /// Optionally consumes the specified character. If the character is not at
327 /// the current position, then the current iterator isn't moved and `false` is
328 /// returned, otherwise the character is consumed and `true` is returned.
329 fn consume(&mut self, c: char) -> bool {
330 self.consume_pos(c).is_some()
333 /// Optionally consumes the specified character. If the character is not at
334 /// the current position, then the current iterator isn't moved and `None` is
335 /// returned, otherwise the character is consumed and the current position is
337 fn consume_pos(&mut self, c: char) -> Option<usize> {
338 if let Some(&(pos, maybe)) = self.cur.peek() {
347 fn to_span_index(&self, pos: usize) -> InnerOffset {
349 // This handles the raw string case, the raw argument is the number of #
350 // in r###"..."### (we need to add one because of the `r`).
351 let raw = self.style.map_or(0, |raw| raw + 1);
352 for skip in &self.skips {
355 } else if pos == *skip && raw == 0 {
361 InnerOffset(raw + pos + 1)
364 /// Forces consumption of the specified character. If the character is not
365 /// found, an error is emitted.
366 fn must_consume(&mut self, c: char) -> Option<usize> {
369 if let Some(&(pos, maybe)) = self.cur.peek() {
374 let pos = self.to_span_index(pos);
375 let description = format!("expected `'}}'`, found `{:?}`", maybe);
376 let label = "expected `}`".to_owned();
377 let (note, secondary_label) = if c == '}' {
380 "if you intended to print `{`, you can escape it using `{{`".to_owned(),
382 self.last_opening_brace
383 .map(|sp| ("because of this opening brace".to_owned(), sp)),
388 self.errors.push(ParseError {
398 let description = format!("expected `{:?}` but string was terminated", c);
399 // point at closing `"`
400 let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
401 let pos = self.to_span_index(pos);
403 let label = format!("expected `{:?}`", c);
404 let (note, secondary_label) = if c == '}' {
407 "if you intended to print `{`, you can escape it using `{{`".to_owned(),
409 self.last_opening_brace
410 .map(|sp| ("because of this opening brace".to_owned(), sp)),
415 self.errors.push(ParseError {
423 self.err(description, format!("expected `{:?}`", c), pos.to(pos));
429 /// Consumes all whitespace characters until the first non-whitespace character
431 while let Some(&(_, c)) = self.cur.peek() {
432 if c.is_whitespace() {
440 /// Parses all of a string which is to be considered a "raw literal" in a
441 /// format string. This is everything outside of the braces.
442 fn string(&mut self, start: usize) -> &'a str {
443 // we may not consume the character, peek the iterator
444 while let Some(&(pos, c)) = self.cur.peek() {
447 return &self.input[start..pos];
449 '\n' if self.is_literal => {
450 let start = self.to_span_index(self.cur_line_start);
451 let end = self.to_span_index(pos);
452 self.line_spans.push(start.to(end));
453 self.cur_line_start = pos + 1;
457 if self.is_literal && pos == self.cur_line_start && c.is_whitespace() {
458 self.cur_line_start = pos + c.len_utf8();
464 &self.input[start..self.input.len()]
467 /// Parses an `Argument` structure, or what's contained within braces inside the format string.
468 fn argument(&mut self) -> Argument<'a> {
469 let pos = self.position();
470 let format = match self.mode {
471 ParseMode::Format => self.format(),
472 ParseMode::InlineAsm => self.inline_asm(),
475 // Resolve position after parsing format spec.
476 let pos = match pos {
477 Some(position) => position,
481 ArgumentImplicitlyIs(i)
485 Argument { position: pos, format }
488 /// Parses a positional argument for a format. This could either be an
489 /// integer index of an argument, a named argument, or a blank string.
490 /// Returns `Some(parsed_position)` if the position is not implicitly
491 /// consuming a macro argument, `None` if it's the case.
492 fn position(&mut self) -> Option<Position> {
493 if let Some(i) = self.integer() {
496 match self.cur.peek() {
497 Some(&(start, c)) if rustc_lexer::is_id_start(c) => {
498 let word = self.word();
499 let end = start + word.len();
500 let span = self.to_span_index(start).to(self.to_span_index(end));
501 Some(ArgumentNamed(Symbol::intern(word), span))
504 // This is an `ArgumentNext`.
505 // Record the fact and do the resolution after parsing the
506 // format spec, to make things like `{:.*}` work.
512 /// Parses a format specifier at the current position, returning all of the
513 /// relevant information in the `FormatSpec` struct.
514 fn format(&mut self) -> FormatSpec<'a> {
515 let mut spec = FormatSpec {
519 precision: CountImplied,
520 precision_span: None,
523 ty: &self.input[..0],
526 if !self.consume(':') {
531 if let Some(&(_, c)) = self.cur.peek() {
532 if let Some((_, '>' | '<' | '^')) = self.cur.clone().nth(1) {
538 if self.consume('<') {
539 spec.align = AlignLeft;
540 } else if self.consume('>') {
541 spec.align = AlignRight;
542 } else if self.consume('^') {
543 spec.align = AlignCenter;
546 if self.consume('+') {
547 spec.flags |= 1 << (FlagSignPlus as u32);
548 } else if self.consume('-') {
549 spec.flags |= 1 << (FlagSignMinus as u32);
552 if self.consume('#') {
553 spec.flags |= 1 << (FlagAlternate as u32);
555 // Width and precision
556 let mut havewidth = false;
558 if self.consume('0') {
559 // small ambiguity with '0$' as a format string. In theory this is a
560 // '0' flag and then an ill-formatted format string with just a '$'
561 // and no count, but this is better if we instead interpret this as
562 // no '0' flag and '0$' as the width instead.
563 if self.consume('$') {
564 spec.width = CountIsParam(0);
567 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
571 let width_span_start = if let Some((pos, _)) = self.cur.peek() { *pos } else { 0 };
572 let (w, sp) = self.count(width_span_start);
574 spec.width_span = sp;
576 if let Some(start) = self.consume_pos('.') {
577 if let Some(end) = self.consume_pos('*') {
578 // Resolve `CountIsNextParam`.
579 // We can do this immediately as `position` is resolved later.
582 spec.precision = CountIsParam(i);
583 spec.precision_span =
584 Some(self.to_span_index(start).to(self.to_span_index(end + 1)));
586 let (p, sp) = self.count(start);
588 spec.precision_span = sp;
591 let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
592 // Optional radix followed by the actual format specifier
593 if self.consume('x') {
594 if self.consume('?') {
595 spec.flags |= 1 << (FlagDebugLowerHex as u32);
600 } else if self.consume('X') {
601 if self.consume('?') {
602 spec.flags |= 1 << (FlagDebugUpperHex as u32);
607 } else if self.consume('?') {
610 spec.ty = self.word();
611 let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
612 if !spec.ty.is_empty() {
613 spec.ty_span = ty_span_start
614 .and_then(|s| ty_span_end.map(|e| (s, e)))
615 .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
621 /// Parses an inline assembly template modifier at the current position, returning the modifier
622 /// in the `ty` field of the `FormatSpec` struct.
623 fn inline_asm(&mut self) -> FormatSpec<'a> {
624 let mut spec = FormatSpec {
628 precision: CountImplied,
629 precision_span: None,
632 ty: &self.input[..0],
635 if !self.consume(':') {
639 let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
640 spec.ty = self.word();
641 let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
642 if !spec.ty.is_empty() {
643 spec.ty_span = ty_span_start
644 .and_then(|s| ty_span_end.map(|e| (s, e)))
645 .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
651 /// Parses a `Count` parameter at the current position. This does not check
652 /// for 'CountIsNextParam' because that is only used in precision, not
654 fn count(&mut self, start: usize) -> (Count, Option<InnerSpan>) {
655 if let Some(i) = self.integer() {
656 if let Some(end) = self.consume_pos('$') {
657 let span = self.to_span_index(start).to(self.to_span_index(end + 1));
658 (CountIsParam(i), Some(span))
663 let tmp = self.cur.clone();
664 let word = self.word();
668 } else if let Some(end) = self.consume_pos('$') {
669 let span = self.to_span_index(start + 1).to(self.to_span_index(end));
670 (CountIsName(Symbol::intern(word), span), None)
678 /// Parses a word starting at the current position. A word is the same as
679 /// Rust identifier, except that it can't start with `_` character.
680 fn word(&mut self) -> &'a str {
681 let start = match self.cur.peek() {
682 Some(&(pos, c)) if rustc_lexer::is_id_start(c) => {
691 while let Some(&(pos, c)) = self.cur.peek() {
692 if rustc_lexer::is_id_continue(c) {
699 let end = end.unwrap_or(self.input.len());
700 let word = &self.input[start..end];
703 "invalid argument name `_`",
704 "invalid argument name",
705 "argument name cannot be a single underscore",
706 self.to_span_index(start).to(self.to_span_index(end)),
712 /// Optionally parses an integer at the current position. This doesn't deal
713 /// with overflow at all, it's just accumulating digits.
714 fn integer(&mut self) -> Option<usize> {
716 let mut found = false;
717 while let Some(&(_, c)) = self.cur.peek() {
718 if let Some(i) = c.to_digit(10) {
719 cur = cur * 10 + i as usize;
730 /// Finds the indices of all characters that have been processed and differ between the actual
731 /// written code (code snippet) and the `InternedString` that gets processed in the `Parser`
732 /// in order to properly synthesise the intra-string `Span`s for error diagnostics.
733 fn find_skips_from_snippet(
734 snippet: Option<string::String>,
735 str_style: Option<usize>,
736 ) -> (Vec<usize>, bool) {
737 let snippet = match snippet {
738 Some(ref s) if s.starts_with('"') || s.starts_with("r\"") || s.starts_with("r#") => s,
739 _ => return (vec![], false),
742 fn find_skips(snippet: &str, is_raw: bool) -> Vec<usize> {
743 let mut s = snippet.char_indices().peekable();
744 let mut skips = vec![];
745 while let Some((pos, c)) = s.next() {
746 match (c, s.peek()) {
747 // skip whitespace and empty lines ending in '\\'
748 ('\\', Some((next_pos, '\n'))) if !is_raw => {
750 skips.push(*next_pos);
753 while let Some((pos, c)) = s.peek() {
754 if matches!(c, ' ' | '\n' | '\t') {
762 ('\\', Some((next_pos, 'n' | 't' | 'r' | '0' | '\\' | '\'' | '\"'))) => {
763 skips.push(*next_pos);
766 ('\\', Some((_, 'x'))) if !is_raw => {
768 // consume `\xAB` literal
769 if let Some((pos, _)) = s.next() {
776 ('\\', Some((_, 'u'))) if !is_raw => {
777 if let Some((pos, _)) = s.next() {
780 if let Some((next_pos, next_c)) = s.next() {
782 skips.push(next_pos);
783 let mut i = 0; // consume up to 6 hexanumeric chars + closing `}`
784 while let (Some((next_pos, c)), true) = (s.next(), i < 7) {
786 skips.push(next_pos);
788 skips.push(next_pos);
795 } else if next_c.is_digit(16) {
796 skips.push(next_pos);
797 // We suggest adding `{` and `}` when appropriate, accept it here as if
799 let mut i = 0; // consume up to 6 hexanumeric chars
800 while let (Some((next_pos, c)), _) = (s.next(), i < 6) {
802 skips.push(next_pos);
817 let r_start = str_style.map_or(0, |r| r + 1);
818 let r_end = str_style.unwrap_or(0);
819 let s = &snippet[r_start + 1..snippet.len() - r_end - 1];
820 (find_skips(s, str_style.is_some()), true)