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/",
9 html_playground_url = "https://play.rust-lang.org/",
10 test(attr(deny(warnings)))
13 #![feature(rustc_private)]
14 #![feature(unicode_internals)]
15 #![feature(bool_to_option)]
27 use rustc_span::{InnerSpan, Symbol};
29 #[derive(Copy, Clone)]
30 struct InnerOffset(usize);
33 fn to(self, end: InnerOffset) -> InnerSpan {
34 InnerSpan::new(self.0, end.0)
38 /// A piece is a portion of the format string which represents the next part
39 /// to emit. These are emitted as a stream by the `Parser` class.
40 #[derive(Copy, Clone, Debug, PartialEq)]
42 /// A literal string which should directly be emitted
44 /// This describes that formatting should process the next argument (as
45 /// specified inside) for emission.
46 NextArgument(Argument<'a>),
49 /// Representation of an argument specification.
50 #[derive(Copy, Clone, Debug, PartialEq)]
51 pub struct Argument<'a> {
52 /// Where to find this argument
53 pub position: Position,
54 /// How to format the argument
55 pub format: FormatSpec<'a>,
58 /// Specification for the formatting of an argument in the format string.
59 #[derive(Copy, Clone, Debug, PartialEq)]
60 pub struct FormatSpec<'a> {
61 /// Optionally specified character to fill alignment with.
62 pub fill: Option<char>,
63 /// Optionally specified alignment.
65 /// Packed version of various flags provided.
67 /// The integer precision to use.
69 /// The span of the precision formatting flag (for diagnostics).
70 pub precision_span: Option<InnerSpan>,
71 /// The string width requested for the resulting format.
73 /// The span of the width formatting flag (for diagnostics).
74 pub width_span: Option<InnerSpan>,
75 /// The descriptor string representing the name of the format desired for
76 /// this argument, this can be empty or any number of characters, although
77 /// it is required to be one word.
79 /// The span of the descriptor string (for diagnostics).
80 pub ty_span: Option<InnerSpan>,
83 /// Enum describing where an argument for a format can be located.
84 #[derive(Copy, Clone, Debug, PartialEq)]
86 /// The argument is implied to be located at an index
87 ArgumentImplicitlyIs(usize),
88 /// The argument is located at a specific index given in the format
90 /// The argument has a name.
91 ArgumentNamed(Symbol),
95 pub fn index(&self) -> Option<usize> {
97 ArgumentIs(i) | ArgumentImplicitlyIs(i) => Some(*i),
103 /// Enum of alignments which are supported.
104 #[derive(Copy, Clone, Debug, PartialEq)]
106 /// The value will be aligned to the left.
108 /// The value will be aligned to the right.
110 /// The value will be aligned in the center.
112 /// The value will take on a default alignment.
116 /// Various flags which can be applied to format strings. The meaning of these
117 /// flags is defined by the formatters themselves.
118 #[derive(Copy, Clone, Debug, PartialEq)]
120 /// A `+` will be used to denote positive numbers.
122 /// A `-` will be used to denote negative numbers. This is the default.
124 /// An alternate form will be used for the value. In the case of numbers,
125 /// this means that the number will be prefixed with the supplied string.
127 /// For numbers, this means that the number will be padded with zeroes,
128 /// and the sign (`+` or `-`) will precede them.
129 FlagSignAwareZeroPad,
130 /// For Debug / `?`, format integers in lower-case hexadecimal.
132 /// For Debug / `?`, format integers in upper-case hexadecimal.
136 /// A count is used for the precision and width parameters of an integer, and
137 /// can reference either an argument or a literal integer.
138 #[derive(Copy, Clone, Debug, PartialEq)]
140 /// The count is specified explicitly.
142 /// The count is specified by the argument with the given name.
144 /// The count is specified by the argument at the given index.
146 /// The count is implied and cannot be explicitly specified.
150 pub struct ParseError {
151 pub description: string::String,
152 pub note: Option<string::String>,
153 pub label: string::String,
155 pub secondary_label: Option<(string::String, InnerSpan)>,
158 /// The parser structure for interpreting the input format string. This is
159 /// modeled as an iterator over `Piece` structures to form a stream of tokens
162 /// This is a recursive-descent parser for the sake of simplicity, and if
163 /// necessary there's probably lots of room for improvement performance-wise.
164 pub struct Parser<'a> {
166 cur: iter::Peekable<str::CharIndices<'a>>,
167 /// Error messages accumulated during parsing
168 pub errors: Vec<ParseError>,
169 /// Current position of implicit positional argument pointer
171 /// `Some(raw count)` when the string is "raw", used to position spans correctly
172 style: Option<usize>,
173 /// Start and end byte offset of every successfully parsed argument
174 pub arg_places: Vec<InnerSpan>,
175 /// Characters that need to be shifted
177 /// Span of the last opening brace seen, used for error reporting
178 last_opening_brace: Option<InnerSpan>,
179 /// Wether the source string is comes from `println!` as opposed to `format!` or `print!`
180 append_newline: bool,
183 impl<'a> Iterator for Parser<'a> {
184 type Item = Piece<'a>;
186 fn next(&mut self) -> Option<Piece<'a>> {
187 if let Some(&(pos, c)) = self.cur.peek() {
190 let curr_last_brace = self.last_opening_brace;
191 let byte_pos = self.to_span_index(pos);
192 self.last_opening_brace = Some(byte_pos.to(InnerOffset(byte_pos.0 + 1)));
194 if self.consume('{') {
195 self.last_opening_brace = curr_last_brace;
197 Some(String(self.string(pos + 1)))
199 let arg = self.argument();
200 if let Some(end) = self.must_consume('}') {
201 let start = self.to_span_index(pos);
202 let end = self.to_span_index(end + 1);
203 self.arg_places.push(start.to(end));
205 Some(NextArgument(arg))
210 if self.consume('}') {
211 Some(String(self.string(pos + 1)))
213 let err_pos = self.to_span_index(pos);
215 "unmatched `}` found",
217 "if you intended to print `}`, you can escape it using `}}`",
223 '\n' => Some(String(self.string(pos))),
224 _ => Some(String(self.string(pos))),
232 impl<'a> Parser<'a> {
233 /// Creates a new parser for the given format string
236 style: Option<usize>,
238 append_newline: bool,
242 cur: s.char_indices().peekable(),
248 last_opening_brace: None,
253 /// Notifies of an error. The message doesn't actually need to be of type
254 /// String, but I think it does when this eventually uses conditions so it
255 /// might as well start using it now.
256 fn err<S1: Into<string::String>, S2: Into<string::String>>(
262 self.errors.push(ParseError {
263 description: description.into(),
267 secondary_label: None,
271 /// Notifies of an error. The message doesn't actually need to be of type
272 /// String, but I think it does when this eventually uses conditions so it
273 /// might as well start using it now.
275 S1: Into<string::String>,
276 S2: Into<string::String>,
277 S3: Into<string::String>,
285 self.errors.push(ParseError {
286 description: description.into(),
287 note: Some(note.into()),
290 secondary_label: None,
294 /// Optionally consumes the specified character. If the character is not at
295 /// the current position, then the current iterator isn't moved and `false` is
296 /// returned, otherwise the character is consumed and `true` is returned.
297 fn consume(&mut self, c: char) -> bool {
298 self.consume_pos(c).is_some()
301 /// Optionally consumes the specified character. If the character is not at
302 /// the current position, then the current iterator isn't moved and `None` is
303 /// returned, otherwise the character is consumed and the current position is
305 fn consume_pos(&mut self, c: char) -> Option<usize> {
306 if let Some(&(pos, maybe)) = self.cur.peek() {
315 fn to_span_index(&self, pos: usize) -> InnerOffset {
317 // This handles the raw string case, the raw argument is the number of #
318 // in r###"..."### (we need to add one because of the `r`).
319 let raw = self.style.map(|raw| raw + 1).unwrap_or(0);
320 for skip in &self.skips {
323 } else if pos == *skip && raw == 0 {
329 InnerOffset(raw + pos + 1)
332 /// Forces consumption of the specified character. If the character is not
333 /// found, an error is emitted.
334 fn must_consume(&mut self, c: char) -> Option<usize> {
337 if let Some(&(pos, maybe)) = self.cur.peek() {
342 let pos = self.to_span_index(pos);
343 let description = format!("expected `'}}'`, found `{:?}`", maybe);
344 let label = "expected `}`".to_owned();
345 let (note, secondary_label) = if c == '}' {
348 "if you intended to print `{`, you can escape it using `{{`".to_owned(),
350 self.last_opening_brace
351 .map(|sp| ("because of this opening brace".to_owned(), sp)),
356 self.errors.push(ParseError {
366 let description = format!("expected `{:?}` but string was terminated", c);
367 // point at closing `"`
368 let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
369 let pos = self.to_span_index(pos);
371 let label = format!("expected `{:?}`", c);
372 let (note, secondary_label) = if c == '}' {
375 "if you intended to print `{`, you can escape it using `{{`".to_owned(),
377 self.last_opening_brace
378 .map(|sp| ("because of this opening brace".to_owned(), sp)),
383 self.errors.push(ParseError {
391 self.err(description, format!("expected `{:?}`", c), pos.to(pos));
397 /// Consumes all whitespace characters until the first non-whitespace character
399 while let Some(&(_, c)) = self.cur.peek() {
400 if c.is_whitespace() {
408 /// Parses all of a string which is to be considered a "raw literal" in a
409 /// format string. This is everything outside of the braces.
410 fn string(&mut self, start: usize) -> &'a str {
411 // we may not consume the character, peek the iterator
412 while let Some(&(pos, c)) = self.cur.peek() {
415 return &self.input[start..pos];
422 &self.input[start..self.input.len()]
425 /// Parses an `Argument` structure, or what's contained within braces inside the format string.
426 fn argument(&mut self) -> Argument<'a> {
427 let pos = self.position();
428 let format = self.format();
430 // Resolve position after parsing format spec.
431 let pos = match pos {
432 Some(position) => position,
436 ArgumentImplicitlyIs(i)
440 Argument { position: pos, format }
443 /// Parses a positional argument for a format. This could either be an
444 /// integer index of an argument, a named argument, or a blank string.
445 /// Returns `Some(parsed_position)` if the position is not implicitly
446 /// consuming a macro argument, `None` if it's the case.
447 fn position(&mut self) -> Option<Position> {
448 if let Some(i) = self.integer() {
451 match self.cur.peek() {
452 Some(&(_, c)) if rustc_lexer::is_id_start(c) => {
453 Some(ArgumentNamed(Symbol::intern(self.word())))
456 // This is an `ArgumentNext`.
457 // Record the fact and do the resolution after parsing the
458 // format spec, to make things like `{:.*}` work.
464 /// Parses a format specifier at the current position, returning all of the
465 /// relevant information in the `FormatSpec` struct.
466 fn format(&mut self) -> FormatSpec<'a> {
467 let mut spec = FormatSpec {
471 precision: CountImplied,
472 precision_span: None,
475 ty: &self.input[..0],
478 if !self.consume(':') {
483 if let Some(&(_, c)) = self.cur.peek() {
484 match self.cur.clone().nth(1) {
485 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
493 if self.consume('<') {
494 spec.align = AlignLeft;
495 } else if self.consume('>') {
496 spec.align = AlignRight;
497 } else if self.consume('^') {
498 spec.align = AlignCenter;
501 if self.consume('+') {
502 spec.flags |= 1 << (FlagSignPlus as u32);
503 } else if self.consume('-') {
504 spec.flags |= 1 << (FlagSignMinus as u32);
507 if self.consume('#') {
508 spec.flags |= 1 << (FlagAlternate as u32);
510 // Width and precision
511 let mut havewidth = false;
513 if self.consume('0') {
514 // small ambiguity with '0$' as a format string. In theory this is a
515 // '0' flag and then an ill-formatted format string with just a '$'
516 // and no count, but this is better if we instead interpret this as
517 // no '0' flag and '0$' as the width instead.
518 if self.consume('$') {
519 spec.width = CountIsParam(0);
522 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
526 let width_span_start = if let Some((pos, _)) = self.cur.peek() { *pos } else { 0 };
527 let (w, sp) = self.count(width_span_start);
529 spec.width_span = sp;
531 if let Some(start) = self.consume_pos('.') {
532 if let Some(end) = self.consume_pos('*') {
533 // Resolve `CountIsNextParam`.
534 // We can do this immediately as `position` is resolved later.
537 spec.precision = CountIsParam(i);
538 spec.precision_span =
539 Some(self.to_span_index(start).to(self.to_span_index(end + 1)));
541 let (p, sp) = self.count(start);
543 spec.precision_span = sp;
546 let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
547 // Optional radix followed by the actual format specifier
548 if self.consume('x') {
549 if self.consume('?') {
550 spec.flags |= 1 << (FlagDebugLowerHex as u32);
555 } else if self.consume('X') {
556 if self.consume('?') {
557 spec.flags |= 1 << (FlagDebugUpperHex as u32);
562 } else if self.consume('?') {
565 spec.ty = self.word();
566 let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
567 if !spec.ty.is_empty() {
568 spec.ty_span = ty_span_start
569 .and_then(|s| ty_span_end.map(|e| (s, e)))
570 .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
576 /// Parses a `Count` parameter at the current position. This does not check
577 /// for 'CountIsNextParam' because that is only used in precision, not
579 fn count(&mut self, start: usize) -> (Count, Option<InnerSpan>) {
580 if let Some(i) = self.integer() {
581 if let Some(end) = self.consume_pos('$') {
582 let span = self.to_span_index(start).to(self.to_span_index(end + 1));
583 (CountIsParam(i), Some(span))
588 let tmp = self.cur.clone();
589 let word = self.word();
593 } else if self.consume('$') {
594 (CountIsName(Symbol::intern(word)), None)
602 /// Parses a word starting at the current position. A word is the same as
603 /// Rust identifier, except that it can't start with `_` character.
604 fn word(&mut self) -> &'a str {
605 let start = match self.cur.peek() {
606 Some(&(pos, c)) if rustc_lexer::is_id_start(c) => {
615 while let Some(&(pos, c)) = self.cur.peek() {
616 if rustc_lexer::is_id_continue(c) {
623 let end = end.unwrap_or(self.input.len());
624 let word = &self.input[start..end];
627 "invalid argument name `_`",
628 "invalid argument name",
629 "argument name cannot be a single underscore",
630 self.to_span_index(start).to(self.to_span_index(end)),
636 /// Optionally parses an integer at the current position. This doesn't deal
637 /// with overflow at all, it's just accumulating digits.
638 fn integer(&mut self) -> Option<usize> {
640 let mut found = false;
641 while let Some(&(_, c)) = self.cur.peek() {
642 if let Some(i) = c.to_digit(10) {
643 cur = cur * 10 + i as usize;