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),
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.
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(&(_, c)) if rustc_lexer::is_id_start(c) => {
498 Some(ArgumentNamed(Symbol::intern(self.word())))
501 // This is an `ArgumentNext`.
502 // Record the fact and do the resolution after parsing the
503 // format spec, to make things like `{:.*}` work.
509 /// Parses a format specifier at the current position, returning all of the
510 /// relevant information in the `FormatSpec` struct.
511 fn format(&mut self) -> FormatSpec<'a> {
512 let mut spec = FormatSpec {
516 precision: CountImplied,
517 precision_span: None,
520 ty: &self.input[..0],
523 if !self.consume(':') {
528 if let Some(&(_, c)) = self.cur.peek() {
529 if let Some((_, '>' | '<' | '^')) = self.cur.clone().nth(1) {
535 if self.consume('<') {
536 spec.align = AlignLeft;
537 } else if self.consume('>') {
538 spec.align = AlignRight;
539 } else if self.consume('^') {
540 spec.align = AlignCenter;
543 if self.consume('+') {
544 spec.flags |= 1 << (FlagSignPlus as u32);
545 } else if self.consume('-') {
546 spec.flags |= 1 << (FlagSignMinus as u32);
549 if self.consume('#') {
550 spec.flags |= 1 << (FlagAlternate as u32);
552 // Width and precision
553 let mut havewidth = false;
555 if self.consume('0') {
556 // small ambiguity with '0$' as a format string. In theory this is a
557 // '0' flag and then an ill-formatted format string with just a '$'
558 // and no count, but this is better if we instead interpret this as
559 // no '0' flag and '0$' as the width instead.
560 if self.consume('$') {
561 spec.width = CountIsParam(0);
564 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
568 let width_span_start = if let Some((pos, _)) = self.cur.peek() { *pos } else { 0 };
569 let (w, sp) = self.count(width_span_start);
571 spec.width_span = sp;
573 if let Some(start) = self.consume_pos('.') {
574 if let Some(end) = self.consume_pos('*') {
575 // Resolve `CountIsNextParam`.
576 // We can do this immediately as `position` is resolved later.
579 spec.precision = CountIsParam(i);
580 spec.precision_span =
581 Some(self.to_span_index(start).to(self.to_span_index(end + 1)));
583 let (p, sp) = self.count(start);
585 spec.precision_span = sp;
588 let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
589 // Optional radix followed by the actual format specifier
590 if self.consume('x') {
591 if self.consume('?') {
592 spec.flags |= 1 << (FlagDebugLowerHex as u32);
597 } else if self.consume('X') {
598 if self.consume('?') {
599 spec.flags |= 1 << (FlagDebugUpperHex as u32);
604 } else if self.consume('?') {
607 spec.ty = self.word();
608 let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
609 if !spec.ty.is_empty() {
610 spec.ty_span = ty_span_start
611 .and_then(|s| ty_span_end.map(|e| (s, e)))
612 .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
618 /// Parses an inline assembly template modifier at the current position, returning the modifier
619 /// in the `ty` field of the `FormatSpec` struct.
620 fn inline_asm(&mut self) -> FormatSpec<'a> {
621 let mut spec = FormatSpec {
625 precision: CountImplied,
626 precision_span: None,
629 ty: &self.input[..0],
632 if !self.consume(':') {
636 let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
637 spec.ty = self.word();
638 let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
639 if !spec.ty.is_empty() {
640 spec.ty_span = ty_span_start
641 .and_then(|s| ty_span_end.map(|e| (s, e)))
642 .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
648 /// Parses a `Count` parameter at the current position. This does not check
649 /// for 'CountIsNextParam' because that is only used in precision, not
651 fn count(&mut self, start: usize) -> (Count, Option<InnerSpan>) {
652 if let Some(i) = self.integer() {
653 if let Some(end) = self.consume_pos('$') {
654 let span = self.to_span_index(start).to(self.to_span_index(end + 1));
655 (CountIsParam(i), Some(span))
660 let tmp = self.cur.clone();
661 let word = self.word();
665 } else if self.consume('$') {
666 (CountIsName(Symbol::intern(word)), None)
674 /// Parses a word starting at the current position. A word is the same as
675 /// Rust identifier, except that it can't start with `_` character.
676 fn word(&mut self) -> &'a str {
677 let start = match self.cur.peek() {
678 Some(&(pos, c)) if rustc_lexer::is_id_start(c) => {
687 while let Some(&(pos, c)) = self.cur.peek() {
688 if rustc_lexer::is_id_continue(c) {
695 let end = end.unwrap_or(self.input.len());
696 let word = &self.input[start..end];
699 "invalid argument name `_`",
700 "invalid argument name",
701 "argument name cannot be a single underscore",
702 self.to_span_index(start).to(self.to_span_index(end)),
708 /// Optionally parses an integer at the current position. This doesn't deal
709 /// with overflow at all, it's just accumulating digits.
710 fn integer(&mut self) -> Option<usize> {
712 let mut found = false;
713 while let Some(&(_, c)) = self.cur.peek() {
714 if let Some(i) = c.to_digit(10) {
715 cur = cur * 10 + i as usize;
726 /// Finds the indices of all characters that have been processed and differ between the actual
727 /// written code (code snippet) and the `InternedString` that gets processed in the `Parser`
728 /// in order to properly synthethise the intra-string `Span`s for error diagnostics.
729 fn find_skips_from_snippet(
730 snippet: Option<string::String>,
731 str_style: Option<usize>,
732 ) -> (Vec<usize>, bool) {
733 let snippet = match snippet {
734 Some(ref s) if s.starts_with('"') || s.starts_with("r\"") || s.starts_with("r#") => s,
735 _ => return (vec![], false),
738 fn find_skips(snippet: &str, is_raw: bool) -> Vec<usize> {
739 let mut s = snippet.char_indices().peekable();
740 let mut skips = vec![];
741 while let Some((pos, c)) = s.next() {
742 match (c, s.peek()) {
743 // skip whitespace and empty lines ending in '\\'
744 ('\\', Some((next_pos, '\n'))) if !is_raw => {
746 skips.push(*next_pos);
749 while let Some((pos, c)) = s.peek() {
750 if matches!(c, ' ' | '\n' | '\t') {
758 ('\\', Some((next_pos, 'n' | 't' | 'r' | '0' | '\\' | '\'' | '\"'))) => {
759 skips.push(*next_pos);
762 ('\\', Some((_, 'x'))) if !is_raw => {
764 // consume `\xAB` literal
765 if let Some((pos, _)) = s.next() {
772 ('\\', Some((_, 'u'))) if !is_raw => {
773 if let Some((pos, _)) = s.next() {
776 if let Some((next_pos, next_c)) = s.next() {
778 skips.push(next_pos);
779 let mut i = 0; // consume up to 6 hexanumeric chars + closing `}`
780 while let (Some((next_pos, c)), true) = (s.next(), i < 7) {
782 skips.push(next_pos);
784 skips.push(next_pos);
791 } else if next_c.is_digit(16) {
792 skips.push(next_pos);
793 // We suggest adding `{` and `}` when appropriate, accept it here as if
795 let mut i = 0; // consume up to 6 hexanumeric chars
796 while let (Some((next_pos, c)), _) = (s.next(), i < 6) {
798 skips.push(next_pos);
813 let r_start = str_style.map_or(0, |r| r + 1);
814 let r_end = str_style.unwrap_or(0);
815 let s = &snippet[r_start + 1..snippet.len() - r_end - 1];
816 (find_skips(s, str_style.is_some()), true)