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 #![cfg_attr(bootstrap, feature(or_patterns))]
14 #![feature(bool_to_option)]
26 use rustc_span::{InnerSpan, Symbol};
28 /// The type of format string that we are parsing.
29 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
31 /// A normal format string as per `format_args!`.
33 /// An inline assembly template string for `asm!`.
37 #[derive(Copy, Clone)]
38 struct InnerOffset(usize);
41 fn to(self, end: InnerOffset) -> InnerSpan {
42 InnerSpan::new(self.0, end.0)
46 /// A piece is a portion of the format string which represents the next part
47 /// to emit. These are emitted as a stream by the `Parser` class.
48 #[derive(Copy, Clone, Debug, PartialEq)]
50 /// A literal string which should directly be emitted
52 /// This describes that formatting should process the next argument (as
53 /// specified inside) for emission.
54 NextArgument(Argument<'a>),
57 /// Representation of an argument specification.
58 #[derive(Copy, Clone, Debug, PartialEq)]
59 pub struct Argument<'a> {
60 /// Where to find this argument
61 pub position: Position,
62 /// How to format the argument
63 pub format: FormatSpec<'a>,
66 /// Specification for the formatting of an argument in the format string.
67 #[derive(Copy, Clone, Debug, PartialEq)]
68 pub struct FormatSpec<'a> {
69 /// Optionally specified character to fill alignment with.
70 pub fill: Option<char>,
71 /// Optionally specified alignment.
73 /// Packed version of various flags provided.
75 /// The integer precision to use.
77 /// The span of the precision formatting flag (for diagnostics).
78 pub precision_span: Option<InnerSpan>,
79 /// The string width requested for the resulting format.
81 /// The span of the width formatting flag (for diagnostics).
82 pub width_span: Option<InnerSpan>,
83 /// The descriptor string representing the name of the format desired for
84 /// this argument, this can be empty or any number of characters, although
85 /// it is required to be one word.
87 /// The span of the descriptor string (for diagnostics).
88 pub ty_span: Option<InnerSpan>,
91 /// Enum describing where an argument for a format can be located.
92 #[derive(Copy, Clone, Debug, PartialEq)]
94 /// The argument is implied to be located at an index
95 ArgumentImplicitlyIs(usize),
96 /// The argument is located at a specific index given in the format
98 /// The argument has a name.
99 ArgumentNamed(Symbol),
103 pub fn index(&self) -> Option<usize> {
105 ArgumentIs(i) | ArgumentImplicitlyIs(i) => Some(*i),
111 /// Enum of alignments which are supported.
112 #[derive(Copy, Clone, Debug, PartialEq)]
114 /// The value will be aligned to the left.
116 /// The value will be aligned to the right.
118 /// The value will be aligned in the center.
120 /// The value will take on a default alignment.
124 /// Various flags which can be applied to format strings. The meaning of these
125 /// flags is defined by the formatters themselves.
126 #[derive(Copy, Clone, Debug, PartialEq)]
128 /// A `+` will be used to denote positive numbers.
130 /// A `-` will be used to denote negative numbers. This is the default.
132 /// An alternate form will be used for the value. In the case of numbers,
133 /// this means that the number will be prefixed with the supplied string.
135 /// For numbers, this means that the number will be padded with zeroes,
136 /// and the sign (`+` or `-`) will precede them.
137 FlagSignAwareZeroPad,
138 /// For Debug / `?`, format integers in lower-case hexadecimal.
140 /// For Debug / `?`, format integers in upper-case hexadecimal.
144 /// A count is used for the precision and width parameters of an integer, and
145 /// can reference either an argument or a literal integer.
146 #[derive(Copy, Clone, Debug, PartialEq)]
148 /// The count is specified explicitly.
150 /// The count is specified by the argument with the given name.
152 /// The count is specified by the argument at the given index.
154 /// The count is implied and cannot be explicitly specified.
158 pub struct ParseError {
159 pub description: string::String,
160 pub note: Option<string::String>,
161 pub label: string::String,
163 pub secondary_label: Option<(string::String, InnerSpan)>,
166 /// The parser structure for interpreting the input format string. This is
167 /// modeled as an iterator over `Piece` structures to form a stream of tokens
170 /// This is a recursive-descent parser for the sake of simplicity, and if
171 /// necessary there's probably lots of room for improvement performance-wise.
172 pub struct Parser<'a> {
175 cur: iter::Peekable<str::CharIndices<'a>>,
176 /// Error messages accumulated during parsing
177 pub errors: Vec<ParseError>,
178 /// Current position of implicit positional argument pointer
180 /// `Some(raw count)` when the string is "raw", used to position spans correctly
181 style: Option<usize>,
182 /// Start and end byte offset of every successfully parsed argument
183 pub arg_places: Vec<InnerSpan>,
184 /// Characters that need to be shifted
186 /// Span of the last opening brace seen, used for error reporting
187 last_opening_brace: Option<InnerSpan>,
188 /// Whether the source string is comes from `println!` as opposed to `format!` or `print!`
189 append_newline: bool,
190 /// Whether this formatting string is a literal or it comes from a macro.
191 pub is_literal: bool,
192 /// Start position of the current line.
193 cur_line_start: usize,
194 /// Start and end byte offset of every line of the format string. Excludes
195 /// newline characters and leading whitespace.
196 pub line_spans: Vec<InnerSpan>,
199 impl<'a> Iterator for Parser<'a> {
200 type Item = Piece<'a>;
202 fn next(&mut self) -> Option<Piece<'a>> {
203 if let Some(&(pos, c)) = self.cur.peek() {
206 let curr_last_brace = self.last_opening_brace;
207 let byte_pos = self.to_span_index(pos);
208 self.last_opening_brace = Some(byte_pos.to(InnerOffset(byte_pos.0 + 1)));
210 if self.consume('{') {
211 self.last_opening_brace = curr_last_brace;
213 Some(String(self.string(pos + 1)))
215 let arg = self.argument();
216 if let Some(rbrace_byte_idx) = self.must_consume('}') {
217 let lbrace_inner_offset = self.to_span_index(pos);
218 let rbrace_inner_offset = self.to_span_index(rbrace_byte_idx);
220 self.arg_places.push(
221 lbrace_inner_offset.to(InnerOffset(rbrace_inner_offset.0 + 1)),
225 Some(NextArgument(arg))
230 if self.consume('}') {
231 Some(String(self.string(pos + 1)))
233 let err_pos = self.to_span_index(pos);
235 "unmatched `}` found",
237 "if you intended to print `}`, you can escape it using `}}`",
243 _ => Some(String(self.string(pos))),
247 let start = self.to_span_index(self.cur_line_start);
248 let end = self.to_span_index(self.input.len());
249 let span = start.to(end);
250 if self.line_spans.last() != Some(&span) {
251 self.line_spans.push(span);
259 impl<'a> Parser<'a> {
260 /// Creates a new parser for the given format string
263 style: Option<usize>,
264 snippet: Option<string::String>,
265 append_newline: bool,
268 let (skips, is_literal) = find_skips_from_snippet(snippet, style);
272 cur: s.char_indices().peekable(),
278 last_opening_brace: None,
286 /// Notifies of an error. The message doesn't actually need to be of type
287 /// String, but I think it does when this eventually uses conditions so it
288 /// might as well start using it now.
289 fn err<S1: Into<string::String>, S2: Into<string::String>>(
295 self.errors.push(ParseError {
296 description: description.into(),
300 secondary_label: None,
304 /// Notifies of an error. The message doesn't actually need to be of type
305 /// String, but I think it does when this eventually uses conditions so it
306 /// might as well start using it now.
308 S1: Into<string::String>,
309 S2: Into<string::String>,
310 S3: Into<string::String>,
318 self.errors.push(ParseError {
319 description: description.into(),
320 note: Some(note.into()),
323 secondary_label: None,
327 /// Optionally consumes the specified character. If the character is not at
328 /// the current position, then the current iterator isn't moved and `false` is
329 /// returned, otherwise the character is consumed and `true` is returned.
330 fn consume(&mut self, c: char) -> bool {
331 self.consume_pos(c).is_some()
334 /// Optionally consumes the specified character. If the character is not at
335 /// the current position, then the current iterator isn't moved and `None` is
336 /// returned, otherwise the character is consumed and the current position is
338 fn consume_pos(&mut self, c: char) -> Option<usize> {
339 if let Some(&(pos, maybe)) = self.cur.peek() {
348 fn to_span_index(&self, pos: usize) -> InnerOffset {
350 // This handles the raw string case, the raw argument is the number of #
351 // in r###"..."### (we need to add one because of the `r`).
352 let raw = self.style.map_or(0, |raw| raw + 1);
353 for skip in &self.skips {
356 } else if pos == *skip && raw == 0 {
362 InnerOffset(raw + pos + 1)
365 /// Forces consumption of the specified character. If the character is not
366 /// found, an error is emitted.
367 fn must_consume(&mut self, c: char) -> Option<usize> {
370 if let Some(&(pos, maybe)) = self.cur.peek() {
375 let pos = self.to_span_index(pos);
376 let description = format!("expected `'}}'`, found `{:?}`", maybe);
377 let label = "expected `}`".to_owned();
378 let (note, secondary_label) = if c == '}' {
381 "if you intended to print `{`, you can escape it using `{{`".to_owned(),
383 self.last_opening_brace
384 .map(|sp| ("because of this opening brace".to_owned(), sp)),
389 self.errors.push(ParseError {
399 let description = format!("expected `{:?}` but string was terminated", c);
400 // point at closing `"`
401 let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
402 let pos = self.to_span_index(pos);
404 let label = format!("expected `{:?}`", c);
405 let (note, secondary_label) = if c == '}' {
408 "if you intended to print `{`, you can escape it using `{{`".to_owned(),
410 self.last_opening_brace
411 .map(|sp| ("because of this opening brace".to_owned(), sp)),
416 self.errors.push(ParseError {
424 self.err(description, format!("expected `{:?}`", c), pos.to(pos));
430 /// Consumes all whitespace characters until the first non-whitespace character
432 while let Some(&(_, c)) = self.cur.peek() {
433 if c.is_whitespace() {
441 /// Parses all of a string which is to be considered a "raw literal" in a
442 /// format string. This is everything outside of the braces.
443 fn string(&mut self, start: usize) -> &'a str {
444 // we may not consume the character, peek the iterator
445 while let Some(&(pos, c)) = self.cur.peek() {
448 return &self.input[start..pos];
450 '\n' if self.is_literal => {
451 let start = self.to_span_index(self.cur_line_start);
452 let end = self.to_span_index(pos);
453 self.line_spans.push(start.to(end));
454 self.cur_line_start = pos + 1;
458 if self.is_literal && pos == self.cur_line_start && c.is_whitespace() {
459 self.cur_line_start = pos + c.len_utf8();
465 &self.input[start..self.input.len()]
468 /// Parses an `Argument` structure, or what's contained within braces inside the format string.
469 fn argument(&mut self) -> Argument<'a> {
470 let pos = self.position();
471 let format = match self.mode {
472 ParseMode::Format => self.format(),
473 ParseMode::InlineAsm => self.inline_asm(),
476 // Resolve position after parsing format spec.
477 let pos = match pos {
478 Some(position) => position,
482 ArgumentImplicitlyIs(i)
486 Argument { position: pos, format }
489 /// Parses a positional argument for a format. This could either be an
490 /// integer index of an argument, a named argument, or a blank string.
491 /// Returns `Some(parsed_position)` if the position is not implicitly
492 /// consuming a macro argument, `None` if it's the case.
493 fn position(&mut self) -> Option<Position> {
494 if let Some(i) = self.integer() {
497 match self.cur.peek() {
498 Some(&(_, c)) if rustc_lexer::is_id_start(c) => {
499 Some(ArgumentNamed(Symbol::intern(self.word())))
502 // This is an `ArgumentNext`.
503 // Record the fact and do the resolution after parsing the
504 // format spec, to make things like `{:.*}` work.
510 /// Parses a format specifier at the current position, returning all of the
511 /// relevant information in the `FormatSpec` struct.
512 fn format(&mut self) -> FormatSpec<'a> {
513 let mut spec = FormatSpec {
517 precision: CountImplied,
518 precision_span: None,
521 ty: &self.input[..0],
524 if !self.consume(':') {
529 if let Some(&(_, c)) = self.cur.peek() {
530 if let Some((_, '>' | '<' | '^')) = self.cur.clone().nth(1) {
536 if self.consume('<') {
537 spec.align = AlignLeft;
538 } else if self.consume('>') {
539 spec.align = AlignRight;
540 } else if self.consume('^') {
541 spec.align = AlignCenter;
544 if self.consume('+') {
545 spec.flags |= 1 << (FlagSignPlus as u32);
546 } else if self.consume('-') {
547 spec.flags |= 1 << (FlagSignMinus as u32);
550 if self.consume('#') {
551 spec.flags |= 1 << (FlagAlternate as u32);
553 // Width and precision
554 let mut havewidth = false;
556 if self.consume('0') {
557 // small ambiguity with '0$' as a format string. In theory this is a
558 // '0' flag and then an ill-formatted format string with just a '$'
559 // and no count, but this is better if we instead interpret this as
560 // no '0' flag and '0$' as the width instead.
561 if self.consume('$') {
562 spec.width = CountIsParam(0);
565 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
569 let width_span_start = if let Some((pos, _)) = self.cur.peek() { *pos } else { 0 };
570 let (w, sp) = self.count(width_span_start);
572 spec.width_span = sp;
574 if let Some(start) = self.consume_pos('.') {
575 if let Some(end) = self.consume_pos('*') {
576 // Resolve `CountIsNextParam`.
577 // We can do this immediately as `position` is resolved later.
580 spec.precision = CountIsParam(i);
581 spec.precision_span =
582 Some(self.to_span_index(start).to(self.to_span_index(end + 1)));
584 let (p, sp) = self.count(start);
586 spec.precision_span = sp;
589 let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
590 // Optional radix followed by the actual format specifier
591 if self.consume('x') {
592 if self.consume('?') {
593 spec.flags |= 1 << (FlagDebugLowerHex as u32);
598 } else if self.consume('X') {
599 if self.consume('?') {
600 spec.flags |= 1 << (FlagDebugUpperHex as u32);
605 } else if self.consume('?') {
608 spec.ty = self.word();
609 let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
610 if !spec.ty.is_empty() {
611 spec.ty_span = ty_span_start
612 .and_then(|s| ty_span_end.map(|e| (s, e)))
613 .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
619 /// Parses an inline assembly template modifier at the current position, returning the modifier
620 /// in the `ty` field of the `FormatSpec` struct.
621 fn inline_asm(&mut self) -> FormatSpec<'a> {
622 let mut spec = FormatSpec {
626 precision: CountImplied,
627 precision_span: None,
630 ty: &self.input[..0],
633 if !self.consume(':') {
637 let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
638 spec.ty = self.word();
639 let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
640 if !spec.ty.is_empty() {
641 spec.ty_span = ty_span_start
642 .and_then(|s| ty_span_end.map(|e| (s, e)))
643 .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
649 /// Parses a `Count` parameter at the current position. This does not check
650 /// for 'CountIsNextParam' because that is only used in precision, not
652 fn count(&mut self, start: usize) -> (Count, Option<InnerSpan>) {
653 if let Some(i) = self.integer() {
654 if let Some(end) = self.consume_pos('$') {
655 let span = self.to_span_index(start).to(self.to_span_index(end + 1));
656 (CountIsParam(i), Some(span))
661 let tmp = self.cur.clone();
662 let word = self.word();
666 } else if self.consume('$') {
667 (CountIsName(Symbol::intern(word)), None)
675 /// Parses a word starting at the current position. A word is the same as
676 /// Rust identifier, except that it can't start with `_` character.
677 fn word(&mut self) -> &'a str {
678 let start = match self.cur.peek() {
679 Some(&(pos, c)) if rustc_lexer::is_id_start(c) => {
688 while let Some(&(pos, c)) = self.cur.peek() {
689 if rustc_lexer::is_id_continue(c) {
696 let end = end.unwrap_or(self.input.len());
697 let word = &self.input[start..end];
700 "invalid argument name `_`",
701 "invalid argument name",
702 "argument name cannot be a single underscore",
703 self.to_span_index(start).to(self.to_span_index(end)),
709 /// Optionally parses an integer at the current position. This doesn't deal
710 /// with overflow at all, it's just accumulating digits.
711 fn integer(&mut self) -> Option<usize> {
713 let mut found = false;
714 while let Some(&(_, c)) = self.cur.peek() {
715 if let Some(i) = c.to_digit(10) {
716 cur = cur * 10 + i as usize;
727 /// Finds the indices of all characters that have been processed and differ between the actual
728 /// written code (code snippet) and the `InternedString` that gets processed in the `Parser`
729 /// in order to properly synthethise the intra-string `Span`s for error diagnostics.
730 fn find_skips_from_snippet(
731 snippet: Option<string::String>,
732 str_style: Option<usize>,
733 ) -> (Vec<usize>, bool) {
734 let snippet = match snippet {
735 Some(ref s) if s.starts_with('"') || s.starts_with("r\"") || s.starts_with("r#") => s,
736 _ => return (vec![], false),
739 fn find_skips(snippet: &str, is_raw: bool) -> Vec<usize> {
740 let mut s = snippet.char_indices().peekable();
741 let mut skips = vec![];
742 while let Some((pos, c)) = s.next() {
743 match (c, s.peek()) {
744 // skip whitespace and empty lines ending in '\\'
745 ('\\', Some((next_pos, '\n'))) if !is_raw => {
747 skips.push(*next_pos);
750 while let Some((pos, c)) = s.peek() {
751 if matches!(c, ' ' | '\n' | '\t') {
759 ('\\', Some((next_pos, 'n' | 't' | 'r' | '0' | '\\' | '\'' | '\"'))) => {
760 skips.push(*next_pos);
763 ('\\', Some((_, 'x'))) if !is_raw => {
765 // consume `\xAB` literal
766 if let Some((pos, _)) = s.next() {
773 ('\\', Some((_, 'u'))) if !is_raw => {
774 if let Some((pos, _)) = s.next() {
777 if let Some((next_pos, next_c)) = s.next() {
779 skips.push(next_pos);
780 let mut i = 0; // consume up to 6 hexanumeric chars + closing `}`
781 while let (Some((next_pos, c)), true) = (s.next(), i < 7) {
783 skips.push(next_pos);
785 skips.push(next_pos);
792 } else if next_c.is_digit(16) {
793 skips.push(next_pos);
794 // We suggest adding `{` and `}` when appropriate, accept it here as if
796 let mut i = 0; // consume up to 6 hexanumeric chars
797 while let (Some((next_pos, c)), _) = (s.next(), i < 6) {
799 skips.push(next_pos);
814 let r_start = str_style.map_or(0, |r| r + 1);
815 let r_end = str_style.unwrap_or(0);
816 let s = &snippet[r_start + 1..snippet.len() - r_end - 1];
817 (find_skips(s, str_style.is_some()), true)