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)]
15 #![feature(rustc_private)]
27 use syntax_pos::Symbol;
29 /// A piece is a portion of the format string which represents the next part
30 /// to emit. These are emitted as a stream by the `Parser` class.
31 #[derive(Copy, Clone, PartialEq)]
33 /// A literal string which should directly be emitted
35 /// This describes that formatting should process the next argument (as
36 /// specified inside) for emission.
37 NextArgument(Argument<'a>),
40 /// Representation of an argument specification.
41 #[derive(Copy, Clone, PartialEq)]
42 pub struct Argument<'a> {
43 /// Where to find this argument
44 pub position: Position,
45 /// How to format the argument
46 pub format: FormatSpec<'a>,
49 /// Specification for the formatting of an argument in the format string.
50 #[derive(Copy, Clone, PartialEq)]
51 pub struct FormatSpec<'a> {
52 /// Optionally specified character to fill alignment with
53 pub fill: Option<char>,
54 /// Optionally specified alignment
56 /// Packed version of various flags provided
58 /// The integer precision to use
60 /// The string width requested for the resulting format
62 /// The descriptor string representing the name of the format desired for
63 /// this argument, this can be empty or any number of characters, although
64 /// it is required to be one word.
68 /// Enum describing where an argument for a format can be located.
69 #[derive(Copy, Clone, PartialEq)]
71 /// The argument is implied to be located at an index
72 ArgumentImplicitlyIs(usize),
73 /// The argument is located at a specific index given in the format
75 /// The argument has a name.
76 ArgumentNamed(Symbol),
80 pub fn index(&self) -> Option<usize> {
82 ArgumentIs(i) | ArgumentImplicitlyIs(i) => Some(*i),
88 /// Enum of alignments which are supported.
89 #[derive(Copy, Clone, PartialEq)]
91 /// The value will be aligned to the left.
93 /// The value will be aligned to the right.
95 /// The value will be aligned in the center.
97 /// The value will take on a default alignment.
101 /// Various flags which can be applied to format strings. The meaning of these
102 /// flags is defined by the formatters themselves.
103 #[derive(Copy, Clone, PartialEq)]
105 /// A `+` will be used to denote positive numbers.
107 /// A `-` will be used to denote negative numbers. This is the default.
109 /// An alternate form will be used for the value. In the case of numbers,
110 /// this means that the number will be prefixed with the supplied string.
112 /// For numbers, this means that the number will be padded with zeroes,
113 /// and the sign (`+` or `-`) will precede them.
114 FlagSignAwareZeroPad,
115 /// For Debug / `?`, format integers in lower-case hexadecimal.
117 /// For Debug / `?`, format integers in upper-case hexadecimal.
121 /// A count is used for the precision and width parameters of an integer, and
122 /// can reference either an argument or a literal integer.
123 #[derive(Copy, Clone, PartialEq)]
125 /// The count is specified explicitly.
127 /// The count is specified by the argument with the given name.
129 /// The count is specified by the argument at the given index.
131 /// The count is implied and cannot be explicitly specified.
135 pub struct ParseError {
136 pub description: string::String,
137 pub note: Option<string::String>,
138 pub label: string::String,
139 pub start: SpanIndex,
141 pub secondary_label: Option<(string::String, SpanIndex, SpanIndex)>,
144 /// The parser structure for interpreting the input format string. This is
145 /// modeled as an iterator over `Piece` structures to form a stream of tokens
148 /// This is a recursive-descent parser for the sake of simplicity, and if
149 /// necessary there's probably lots of room for improvement performance-wise.
150 pub struct Parser<'a> {
152 cur: iter::Peekable<str::CharIndices<'a>>,
153 /// Error messages accumulated during parsing
154 pub errors: Vec<ParseError>,
155 /// Current position of implicit positional argument pointer
157 /// `Some(raw count)` when the string is "raw", used to position spans correctly
158 style: Option<usize>,
159 /// Start and end byte offset of every successfully parsed argument
160 pub arg_places: Vec<(SpanIndex, SpanIndex)>,
161 /// Characters that need to be shifted
163 /// Span offset of the last opening brace seen, used for error reporting
164 last_opening_brace_pos: Option<SpanIndex>,
165 /// Wether the source string is comes from `println!` as opposed to `format!` or `print!`
166 append_newline: bool,
169 #[derive(Clone, Copy, Debug)]
170 pub struct SpanIndex(pub usize);
173 pub fn unwrap(self) -> usize {
178 impl<'a> Iterator for Parser<'a> {
179 type Item = Piece<'a>;
181 fn next(&mut self) -> Option<Piece<'a>> {
182 if let Some(&(pos, c)) = self.cur.peek() {
185 let curr_last_brace = self.last_opening_brace_pos;
186 self.last_opening_brace_pos = Some(self.to_span_index(pos));
188 if self.consume('{') {
189 self.last_opening_brace_pos = curr_last_brace;
191 Some(String(self.string(pos + 1)))
193 let arg = self.argument();
194 if let Some(arg_pos) = self.must_consume('}').map(|end| {
195 (self.to_span_index(pos), self.to_span_index(end + 1))
197 self.arg_places.push(arg_pos);
199 Some(NextArgument(arg))
204 if self.consume('}') {
205 Some(String(self.string(pos + 1)))
207 let err_pos = self.to_span_index(pos);
209 "unmatched `}` found",
211 "if you intended to print `}`, you can escape it using `}}`",
219 Some(String(self.string(pos)))
221 _ => Some(String(self.string(pos))),
229 impl<'a> Parser<'a> {
230 /// Creates a new parser for the given format string
233 style: Option<usize>,
235 append_newline: bool,
239 cur: s.char_indices().peekable(),
245 last_opening_brace_pos: None,
250 /// Notifies of an error. The message doesn't actually need to be of type
251 /// String, but I think it does when this eventually uses conditions so it
252 /// might as well start using it now.
253 fn err<S1: Into<string::String>, S2: Into<string::String>>(
260 self.errors.push(ParseError {
261 description: description.into(),
266 secondary_label: None,
270 /// Notifies of an error. The message doesn't actually need to be of type
271 /// String, but I think it does when this eventually uses conditions so it
272 /// might as well start using it now.
273 fn err_with_note<S1: Into<string::String>, S2: Into<string::String>, S3: Into<string::String>>(
281 self.errors.push(ParseError {
282 description: description.into(),
283 note: Some(note.into()),
287 secondary_label: None,
291 /// Optionally consumes the specified character. If the character is not at
292 /// the current position, then the current iterator isn't moved and false is
293 /// returned, otherwise the character is consumed and true is returned.
294 fn consume(&mut self, c: char) -> bool {
295 if let Some(&(_, maybe)) = self.cur.peek() {
307 fn to_span_index(&self, pos: usize) -> SpanIndex {
309 let raw = self.style.map(|raw| raw + 1).unwrap_or(0);
310 for skip in &self.skips {
313 } else if pos == *skip && raw == 0 {
319 SpanIndex(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> {
437 if let Some(i) = self.integer() {
440 match self.cur.peek() {
441 Some(&(_, c)) if c.is_alphabetic() => {
442 Some(ArgumentNamed(Symbol::intern(self.word())))
444 Some(&(pos, c)) if c == '_' => {
445 let invalid_name = self.string(pos);
446 self.err_with_note(format!("invalid argument name `{}`", invalid_name),
447 "invalid argument name",
448 "argument names cannot start with an underscore",
449 self.to_span_index(pos),
450 self.to_span_index(pos + invalid_name.len()));
451 Some(ArgumentNamed(Symbol::intern(invalid_name)))
454 // This is an `ArgumentNext`.
455 // Record the fact and do the resolution after parsing the
456 // format spec, to make things like `{:.*}` work.
462 /// Parses a format specifier at the current position, returning all of the
463 /// relevant information in the FormatSpec struct.
464 fn format(&mut self) -> FormatSpec<'a> {
465 let mut spec = FormatSpec {
469 precision: CountImplied,
471 ty: &self.input[..0],
473 if !self.consume(':') {
478 if let Some(&(_, c)) = self.cur.peek() {
479 match self.cur.clone().nth(1) {
480 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
488 if self.consume('<') {
489 spec.align = AlignLeft;
490 } else if self.consume('>') {
491 spec.align = AlignRight;
492 } else if self.consume('^') {
493 spec.align = AlignCenter;
496 if self.consume('+') {
497 spec.flags |= 1 << (FlagSignPlus as u32);
498 } else if self.consume('-') {
499 spec.flags |= 1 << (FlagSignMinus as u32);
502 if self.consume('#') {
503 spec.flags |= 1 << (FlagAlternate as u32);
505 // Width and precision
506 let mut havewidth = false;
507 if self.consume('0') {
508 // small ambiguity with '0$' as a format string. In theory this is a
509 // '0' flag and then an ill-formatted format string with just a '$'
510 // and no count, but this is better if we instead interpret this as
511 // no '0' flag and '0$' as the width instead.
512 if self.consume('$') {
513 spec.width = CountIsParam(0);
516 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
520 spec.width = self.count();
522 if self.consume('.') {
523 if self.consume('*') {
524 // Resolve `CountIsNextParam`.
525 // We can do this immediately as `position` is resolved later.
528 spec.precision = CountIsParam(i);
530 spec.precision = self.count();
533 // Optional radix followed by the actual format specifier
534 if self.consume('x') {
535 if self.consume('?') {
536 spec.flags |= 1 << (FlagDebugLowerHex as u32);
541 } else if self.consume('X') {
542 if self.consume('?') {
543 spec.flags |= 1 << (FlagDebugUpperHex as u32);
548 } else if self.consume('?') {
551 spec.ty = self.word();
556 /// Parses a Count parameter at the current position. This does not check
557 /// for 'CountIsNextParam' because that is only used in precision, not
559 fn count(&mut self) -> Count {
560 if let Some(i) = self.integer() {
561 if self.consume('$') {
567 let tmp = self.cur.clone();
568 let word = self.word();
572 } else if self.consume('$') {
573 CountIsName(Symbol::intern(word))
581 /// Parses a word starting at the current position. A word is considered to
582 /// be an alphabetic character followed by any number of alphanumeric
584 fn word(&mut self) -> &'a str {
585 let start = match self.cur.peek() {
586 Some(&(pos, c)) if c.is_xid_start() => {
591 return &self.input[..0];
594 while let Some(&(pos, c)) = self.cur.peek() {
595 if c.is_xid_continue() {
598 return &self.input[start..pos];
601 &self.input[start..self.input.len()]
604 /// Optionally parses an integer at the current position. This doesn't deal
605 /// with overflow at all, it's just accumulating digits.
606 fn integer(&mut self) -> Option<usize> {
608 let mut found = false;
609 while let Some(&(_, c)) = self.cur.peek() {
610 if let Some(i) = c.to_digit(10) {
611 cur = cur * 10 + i as usize;
630 fn same(fmt: &'static str, p: &[Piece<'static>]) {
631 let parser = Parser::new(fmt, None, vec![], false);
632 assert!(parser.collect::<Vec<Piece<'static>>>() == p);
635 fn fmtdflt() -> FormatSpec<'static> {
640 precision: CountImplied,
646 fn musterr(s: &str) {
647 let mut p = Parser::new(s, None, vec![], false);
649 assert!(!p.errors.is_empty());
654 same("asdf", &[String("asdf")]);
655 same("a{{b", &[String("a"), String("{b")]);
656 same("a}}b", &[String("a"), String("}b")]);
657 same("a}}", &[String("a"), String("}")]);
658 same("}}", &[String("}")]);
659 same("\\}}", &[String("\\"), String("}")]);
684 fn format_nothing() {
686 &[NextArgument(Argument {
687 position: ArgumentImplicitlyIs(0),
692 fn format_position() {
694 &[NextArgument(Argument {
695 position: ArgumentIs(3),
700 fn format_position_nothing_else() {
702 &[NextArgument(Argument {
703 position: ArgumentIs(3),
710 &[NextArgument(Argument {
711 position: ArgumentIs(3),
716 precision: CountImplied,
723 fn format_align_fill() {
725 &[NextArgument(Argument {
726 position: ArgumentIs(3),
731 precision: CountImplied,
737 &[NextArgument(Argument {
738 position: ArgumentIs(3),
743 precision: CountImplied,
749 &[NextArgument(Argument {
750 position: ArgumentIs(3),
755 precision: CountImplied,
763 use syntax_pos::{GLOBALS, Globals, edition};
764 GLOBALS.set(&Globals::new(edition::DEFAULT_EDITION), || {
766 &[NextArgument(Argument {
767 position: ArgumentImplicitlyIs(0),
772 precision: CountImplied,
778 &[NextArgument(Argument {
779 position: ArgumentImplicitlyIs(0),
784 precision: CountIs(10),
785 width: CountIsParam(10),
790 &[NextArgument(Argument {
791 position: ArgumentImplicitlyIs(1),
796 precision: CountIsParam(0),
802 &[NextArgument(Argument {
803 position: ArgumentImplicitlyIs(0),
808 precision: CountIsParam(10),
814 &[NextArgument(Argument {
815 position: ArgumentImplicitlyIs(0),
820 precision: CountIsName(Symbol::intern("b")),
821 width: CountIsName(Symbol::intern("a")),
830 &[NextArgument(Argument {
831 position: ArgumentImplicitlyIs(0),
835 flags: (1 << FlagSignMinus as u32),
836 precision: CountImplied,
842 &[NextArgument(Argument {
843 position: ArgumentImplicitlyIs(0),
847 flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32),
848 precision: CountImplied,
855 fn format_mixture() {
856 same("abcd {3:a} efg",
858 NextArgument(Argument {
859 position: ArgumentIs(3),
864 precision: CountImplied,