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
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
8 html_playground_url = "https://play.rust-lang.org/",
9 test(attr(deny(warnings))))]
11 #![deny(rust_2018_idioms)]
14 #![feature(rustc_private)]
26 /// A piece is a portion of the format string which represents the next part
27 /// to emit. These are emitted as a stream by the `Parser` class.
28 #[derive(Copy, Clone, PartialEq)]
30 /// A literal string which should directly be emitted
32 /// This describes that formatting should process the next argument (as
33 /// specified inside) for emission.
34 NextArgument(Argument<'a>),
37 /// Representation of an argument specification.
38 #[derive(Copy, Clone, PartialEq)]
39 pub struct Argument<'a> {
40 /// Where to find this argument
41 pub position: Position<'a>,
42 /// How to format the argument
43 pub format: FormatSpec<'a>,
46 /// Specification for the formatting of an argument in the format string.
47 #[derive(Copy, Clone, PartialEq)]
48 pub struct FormatSpec<'a> {
49 /// Optionally specified character to fill alignment with
50 pub fill: Option<char>,
51 /// Optionally specified alignment
53 /// Packed version of various flags provided
55 /// The integer precision to use
56 pub precision: Count<'a>,
57 /// The string width requested for the resulting format
59 /// The descriptor string representing the name of the format desired for
60 /// this argument, this can be empty or any number of characters, although
61 /// it is required to be one word.
65 /// Enum describing where an argument for a format can be located.
66 #[derive(Copy, Clone, PartialEq)]
67 pub enum Position<'a> {
68 /// The argument is implied to be located at an index
69 ArgumentImplicitlyIs(usize),
70 /// The argument is located at a specific index given in the format
72 /// The argument has a name.
73 ArgumentNamed(&'a str),
77 pub fn index(&self) -> Option<usize> {
79 ArgumentIs(i) | ArgumentImplicitlyIs(i) => Some(*i),
85 /// Enum of alignments which are supported.
86 #[derive(Copy, Clone, PartialEq)]
88 /// The value will be aligned to the left.
90 /// The value will be aligned to the right.
92 /// The value will be aligned in the center.
94 /// The value will take on a default alignment.
98 /// Various flags which can be applied to format strings. The meaning of these
99 /// flags is defined by the formatters themselves.
100 #[derive(Copy, Clone, PartialEq)]
102 /// A `+` will be used to denote positive numbers.
104 /// A `-` will be used to denote negative numbers. This is the default.
106 /// An alternate form will be used for the value. In the case of numbers,
107 /// this means that the number will be prefixed with the supplied string.
109 /// For numbers, this means that the number will be padded with zeroes,
110 /// and the sign (`+` or `-`) will precede them.
111 FlagSignAwareZeroPad,
112 /// For Debug / `?`, format integers in lower-case hexadecimal.
114 /// For Debug / `?`, format integers in upper-case hexadecimal.
118 /// A count is used for the precision and width parameters of an integer, and
119 /// can reference either an argument or a literal integer.
120 #[derive(Copy, Clone, PartialEq)]
122 /// The count is specified explicitly.
124 /// The count is specified by the argument with the given name.
125 CountIsName(&'a str),
126 /// The count is specified by the argument at the given index.
128 /// The count is implied and cannot be explicitly specified.
132 pub struct ParseError {
133 pub description: string::String,
134 pub note: Option<string::String>,
135 pub label: string::String,
136 pub start: SpanIndex,
138 pub secondary_label: Option<(string::String, SpanIndex, SpanIndex)>,
141 /// The parser structure for interpreting the input format string. This is
142 /// modeled as an iterator over `Piece` structures to form a stream of tokens
145 /// This is a recursive-descent parser for the sake of simplicity, and if
146 /// necessary there's probably lots of room for improvement performance-wise.
147 pub struct Parser<'a> {
149 cur: iter::Peekable<str::CharIndices<'a>>,
150 /// Error messages accumulated during parsing
151 pub errors: Vec<ParseError>,
152 /// Current position of implicit positional argument pointer
154 /// `Some(raw count)` when the string is "raw", used to position spans correctly
155 style: Option<usize>,
156 /// Start and end byte offset of every successfully parsed argument
157 pub arg_places: Vec<(SpanIndex, SpanIndex)>,
158 /// Characters that need to be shifted
160 /// Span offset of the last opening brace seen, used for error reporting
161 last_opening_brace_pos: Option<SpanIndex>,
162 /// Wether the source string is comes from `println!` as opposed to `format!` or `print!`
163 append_newline: bool,
166 #[derive(Clone, Copy, Debug)]
167 pub struct SpanIndex(pub usize);
170 pub fn unwrap(self) -> usize {
175 impl<'a> Iterator for Parser<'a> {
176 type Item = Piece<'a>;
178 fn next(&mut self) -> Option<Piece<'a>> {
179 if let Some(&(pos, c)) = self.cur.peek() {
182 let curr_last_brace = self.last_opening_brace_pos;
183 self.last_opening_brace_pos = Some(self.to_span_index(pos));
185 if self.consume('{') {
186 self.last_opening_brace_pos = curr_last_brace;
188 Some(String(self.string(pos + 1)))
190 let arg = self.argument();
191 if let Some(arg_pos) = self.must_consume('}').map(|end| {
192 (self.to_span_index(pos), self.to_span_index(end + 1))
194 self.arg_places.push(arg_pos);
196 Some(NextArgument(arg))
201 if self.consume('}') {
202 Some(String(self.string(pos + 1)))
204 let err_pos = self.to_span_index(pos);
206 "unmatched `}` found",
208 "if you intended to print `}`, you can escape it using `}}`",
216 Some(String(self.string(pos)))
218 _ => Some(String(self.string(pos))),
226 impl<'a> Parser<'a> {
227 /// Creates a new parser for the given format string
230 style: Option<usize>,
232 append_newline: bool,
236 cur: s.char_indices().peekable(),
242 last_opening_brace_pos: None,
247 /// Notifies of an error. The message doesn't actually need to be of type
248 /// String, but I think it does when this eventually uses conditions so it
249 /// might as well start using it now.
250 fn err<S1: Into<string::String>, S2: Into<string::String>>(
257 self.errors.push(ParseError {
258 description: description.into(),
263 secondary_label: None,
267 /// Notifies of an error. The message doesn't actually need to be of type
268 /// String, but I think it does when this eventually uses conditions so it
269 /// might as well start using it now.
270 fn err_with_note<S1: Into<string::String>, S2: Into<string::String>, S3: Into<string::String>>(
278 self.errors.push(ParseError {
279 description: description.into(),
280 note: Some(note.into()),
284 secondary_label: None,
288 /// Optionally consumes the specified character. If the character is not at
289 /// the current position, then the current iterator isn't moved and false is
290 /// returned, otherwise the character is consumed and true is returned.
291 fn consume(&mut self, c: char) -> bool {
292 if let Some(&(_, maybe)) = self.cur.peek() {
304 fn raw(&self) -> usize {
305 self.style.map(|raw| raw + 1).unwrap_or(0)
308 fn to_span_index(&self, pos: usize) -> SpanIndex {
310 for skip in &self.skips {
313 } else if pos == *skip && self.raw() == 0 {
319 SpanIndex(self.raw() + pos + 1)
322 /// Forces consumption of the specified character. If the character is not
323 /// found, an error is emitted.
324 fn must_consume(&mut self, c: char) -> Option<usize> {
327 if let Some(&(pos, maybe)) = self.cur.peek() {
332 let pos = self.to_span_index(pos);
333 let description = format!("expected `'}}'`, found `{:?}`", maybe);
334 let label = "expected `}`".to_owned();
335 let (note, secondary_label) = if c == '}' {
336 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
337 self.last_opening_brace_pos.map(|pos| {
338 ("because of this opening brace".to_owned(), pos, pos)
343 self.errors.push(ParseError {
354 let description = format!("expected `{:?}` but string was terminated", c);
355 // point at closing `"`
356 let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
357 let pos = self.to_span_index(pos);
359 let label = format!("expected `{:?}`", c);
360 let (note, secondary_label) = if c == '}' {
361 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
362 self.last_opening_brace_pos.map(|pos| {
363 ("because of this opening brace".to_owned(), pos, pos)
368 self.errors.push(ParseError {
377 self.err(description, format!("expected `{:?}`", c), pos, pos);
383 /// Consumes all whitespace characters until the first non-whitespace character
385 while let Some(&(_, c)) = self.cur.peek() {
386 if c.is_whitespace() {
394 /// Parses all of a string which is to be considered a "raw literal" in a
395 /// format string. This is everything outside of the braces.
396 fn string(&mut self, start: usize) -> &'a str {
397 // we may not consume the character, peek the iterator
398 while let Some(&(pos, c)) = self.cur.peek() {
401 return &self.input[start..pos];
408 &self.input[start..self.input.len()]
411 /// Parses an Argument structure, or what's contained within braces inside the format string
412 fn argument(&mut self) -> Argument<'a> {
413 let pos = self.position();
414 let format = self.format();
416 // Resolve position after parsing format spec.
417 let pos = match pos {
418 Some(position) => position,
422 ArgumentImplicitlyIs(i)
432 /// Parses a positional argument for a format. This could either be an
433 /// integer index of an argument, a named argument, or a blank string.
434 /// Returns `Some(parsed_position)` if the position is not implicitly
435 /// consuming a macro argument, `None` if it's the case.
436 fn position(&mut self) -> Option<Position<'a>> {
437 if let Some(i) = self.integer() {
440 match self.cur.peek() {
441 Some(&(_, c)) if c.is_alphabetic() => Some(ArgumentNamed(self.word())),
442 Some(&(pos, c)) if c == '_' => {
443 let invalid_name = self.string(pos);
444 self.err_with_note(format!("invalid argument name `{}`", invalid_name),
445 "invalid argument name",
446 "argument names cannot start with an underscore",
447 self.to_span_index(pos),
448 self.to_span_index(pos + invalid_name.len()));
449 Some(ArgumentNamed(invalid_name))
452 // This is an `ArgumentNext`.
453 // Record the fact and do the resolution after parsing the
454 // format spec, to make things like `{:.*}` work.
460 /// Parses a format specifier at the current position, returning all of the
461 /// relevant information in the FormatSpec struct.
462 fn format(&mut self) -> FormatSpec<'a> {
463 let mut spec = FormatSpec {
467 precision: CountImplied,
469 ty: &self.input[..0],
471 if !self.consume(':') {
476 if let Some(&(_, c)) = self.cur.peek() {
477 match self.cur.clone().nth(1) {
478 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
486 if self.consume('<') {
487 spec.align = AlignLeft;
488 } else if self.consume('>') {
489 spec.align = AlignRight;
490 } else if self.consume('^') {
491 spec.align = AlignCenter;
494 if self.consume('+') {
495 spec.flags |= 1 << (FlagSignPlus as u32);
496 } else if self.consume('-') {
497 spec.flags |= 1 << (FlagSignMinus as u32);
500 if self.consume('#') {
501 spec.flags |= 1 << (FlagAlternate as u32);
503 // Width and precision
504 let mut havewidth = false;
505 if self.consume('0') {
506 // small ambiguity with '0$' as a format string. In theory this is a
507 // '0' flag and then an ill-formatted format string with just a '$'
508 // and no count, but this is better if we instead interpret this as
509 // no '0' flag and '0$' as the width instead.
510 if self.consume('$') {
511 spec.width = CountIsParam(0);
514 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
518 spec.width = self.count();
520 if self.consume('.') {
521 if self.consume('*') {
522 // Resolve `CountIsNextParam`.
523 // We can do this immediately as `position` is resolved later.
526 spec.precision = CountIsParam(i);
528 spec.precision = self.count();
531 // Optional radix followed by the actual format specifier
532 if self.consume('x') {
533 if self.consume('?') {
534 spec.flags |= 1 << (FlagDebugLowerHex as u32);
539 } else if self.consume('X') {
540 if self.consume('?') {
541 spec.flags |= 1 << (FlagDebugUpperHex as u32);
546 } else if self.consume('?') {
549 spec.ty = self.word();
554 /// Parses a Count parameter at the current position. This does not check
555 /// for 'CountIsNextParam' because that is only used in precision, not
557 fn count(&mut self) -> Count<'a> {
558 if let Some(i) = self.integer() {
559 if self.consume('$') {
565 let tmp = self.cur.clone();
566 let word = self.word();
570 } else if self.consume('$') {
579 /// Parses a word starting at the current position. A word is considered to
580 /// be an alphabetic character followed by any number of alphanumeric
582 fn word(&mut self) -> &'a str {
583 let start = match self.cur.peek() {
584 Some(&(pos, c)) if c.is_xid_start() => {
589 return &self.input[..0];
592 while let Some(&(pos, c)) = self.cur.peek() {
593 if c.is_xid_continue() {
596 return &self.input[start..pos];
599 &self.input[start..self.input.len()]
602 /// Optionally parses an integer at the current position. This doesn't deal
603 /// with overflow at all, it's just accumulating digits.
604 fn integer(&mut self) -> Option<usize> {
606 let mut found = false;
607 while let Some(&(_, c)) = self.cur.peek() {
608 if let Some(i) = c.to_digit(10) {
609 cur = cur * 10 + i as usize;
628 fn same(fmt: &'static str, p: &[Piece<'static>]) {
629 let parser = Parser::new(fmt, None, vec![], false);
630 assert!(parser.collect::<Vec<Piece<'static>>>() == p);
633 fn fmtdflt() -> FormatSpec<'static> {
638 precision: CountImplied,
644 fn musterr(s: &str) {
645 let mut p = Parser::new(s, None, vec![], false);
647 assert!(!p.errors.is_empty());
652 same("asdf", &[String("asdf")]);
653 same("a{{b", &[String("a"), String("{b")]);
654 same("a}}b", &[String("a"), String("}b")]);
655 same("a}}", &[String("a"), String("}")]);
656 same("}}", &[String("}")]);
657 same("\\}}", &[String("\\"), String("}")]);
682 fn format_nothing() {
684 &[NextArgument(Argument {
685 position: ArgumentImplicitlyIs(0),
690 fn format_position() {
692 &[NextArgument(Argument {
693 position: ArgumentIs(3),
698 fn format_position_nothing_else() {
700 &[NextArgument(Argument {
701 position: ArgumentIs(3),
708 &[NextArgument(Argument {
709 position: ArgumentIs(3),
714 precision: CountImplied,
721 fn format_align_fill() {
723 &[NextArgument(Argument {
724 position: ArgumentIs(3),
729 precision: CountImplied,
735 &[NextArgument(Argument {
736 position: ArgumentIs(3),
741 precision: CountImplied,
747 &[NextArgument(Argument {
748 position: ArgumentIs(3),
753 precision: CountImplied,
762 &[NextArgument(Argument {
763 position: ArgumentImplicitlyIs(0),
768 precision: CountImplied,
774 &[NextArgument(Argument {
775 position: ArgumentImplicitlyIs(0),
780 precision: CountIs(10),
781 width: CountIsParam(10),
786 &[NextArgument(Argument {
787 position: ArgumentImplicitlyIs(1),
792 precision: CountIsParam(0),
798 &[NextArgument(Argument {
799 position: ArgumentImplicitlyIs(0),
804 precision: CountIsParam(10),
810 &[NextArgument(Argument {
811 position: ArgumentImplicitlyIs(0),
816 precision: CountIsName("b"),
817 width: CountIsName("a"),
825 &[NextArgument(Argument {
826 position: ArgumentImplicitlyIs(0),
830 flags: (1 << FlagSignMinus as u32),
831 precision: CountImplied,
837 &[NextArgument(Argument {
838 position: ArgumentImplicitlyIs(0),
842 flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32),
843 precision: CountImplied,
850 fn format_mixture() {
851 same("abcd {3:a} efg",
853 NextArgument(Argument {
854 position: ArgumentIs(3),
859 precision: CountImplied,