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_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
8 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
9 html_root_url = "https://doc.rust-lang.org/nightly/",
10 html_playground_url = "https://play.rust-lang.org/",
11 test(attr(deny(warnings))))]
15 pub use self::Piece::*;
16 pub use self::Position::*;
17 pub use self::Alignment::*;
18 pub use self::Flag::*;
19 pub use self::Count::*;
25 /// A piece is a portion of the format string which represents the next part
26 /// to emit. These are emitted as a stream by the `Parser` class.
27 #[derive(Copy, Clone, PartialEq)]
29 /// A literal string which should directly be emitted
31 /// This describes that formatting should process the next argument (as
32 /// specified inside) for emission.
33 NextArgument(Argument<'a>),
36 /// Representation of an argument specification.
37 #[derive(Copy, Clone, PartialEq)]
38 pub struct Argument<'a> {
39 /// Where to find this argument
40 pub position: Position<'a>,
41 /// How to format the argument
42 pub format: FormatSpec<'a>,
45 /// Specification for the formatting of an argument in the format string.
46 #[derive(Copy, Clone, PartialEq)]
47 pub struct FormatSpec<'a> {
48 /// Optionally specified character to fill alignment with
49 pub fill: Option<char>,
50 /// Optionally specified alignment
52 /// Packed version of various flags provided
54 /// The integer precision to use
55 pub precision: Count<'a>,
56 /// The string width requested for the resulting format
58 /// The descriptor string representing the name of the format desired for
59 /// this argument, this can be empty or any number of characters, although
60 /// it is required to be one word.
64 /// Enum describing where an argument for a format can be located.
65 #[derive(Copy, Clone, PartialEq)]
66 pub enum Position<'a> {
67 /// The argument is implied to be located at an index
68 ArgumentImplicitlyIs(usize),
69 /// The argument is located at a specific index given in the format
71 /// The argument has a name.
72 ArgumentNamed(&'a str),
75 /// Enum of alignments which are supported.
76 #[derive(Copy, Clone, PartialEq)]
78 /// The value will be aligned to the left.
80 /// The value will be aligned to the right.
82 /// The value will be aligned in the center.
84 /// The value will take on a default alignment.
88 /// Various flags which can be applied to format strings. The meaning of these
89 /// flags is defined by the formatters themselves.
90 #[derive(Copy, Clone, PartialEq)]
92 /// A `+` will be used to denote positive numbers.
94 /// A `-` will be used to denote negative numbers. This is the default.
96 /// An alternate form will be used for the value. In the case of numbers,
97 /// this means that the number will be prefixed with the supplied string.
99 /// For numbers, this means that the number will be padded with zeroes,
100 /// and the sign (`+` or `-`) will precede them.
101 FlagSignAwareZeroPad,
102 /// For Debug / `?`, format integers in lower-case hexadecimal.
104 /// For Debug / `?`, format integers in upper-case hexadecimal.
108 /// A count is used for the precision and width parameters of an integer, and
109 /// can reference either an argument or a literal integer.
110 #[derive(Copy, Clone, PartialEq)]
112 /// The count is specified explicitly.
114 /// The count is specified by the argument with the given name.
115 CountIsName(&'a str),
116 /// The count is specified by the argument at the given index.
118 /// The count is implied and cannot be explicitly specified.
122 pub struct ParseError {
123 pub description: string::String,
124 pub note: Option<string::String>,
125 pub label: string::String,
126 pub start: SpanIndex,
128 pub secondary_label: Option<(string::String, SpanIndex, SpanIndex)>,
131 /// The parser structure for interpreting the input format string. This is
132 /// modeled as an iterator over `Piece` structures to form a stream of tokens
135 /// This is a recursive-descent parser for the sake of simplicity, and if
136 /// necessary there's probably lots of room for improvement performance-wise.
137 pub struct Parser<'a> {
139 cur: iter::Peekable<str::CharIndices<'a>>,
140 /// Error messages accumulated during parsing
141 pub errors: Vec<ParseError>,
142 /// Current position of implicit positional argument pointer
144 /// `Some(raw count)` when the string is "raw", used to position spans correctly
145 style: Option<usize>,
146 /// Start and end byte offset of every successfully parsed argument
147 pub arg_places: Vec<(SpanIndex, SpanIndex)>,
148 /// Characters that need to be shifted
150 /// Span offset of the last opening brace seen, used for error reporting
151 last_opening_brace_pos: Option<SpanIndex>,
152 /// Wether the source string is comes from `println!` as opposed to `format!` or `print!`
153 append_newline: bool,
156 #[derive(Clone, Copy, Debug)]
157 pub struct SpanIndex(pub usize);
160 pub fn unwrap(self) -> usize {
165 impl<'a> Iterator for Parser<'a> {
166 type Item = Piece<'a>;
168 fn next(&mut self) -> Option<Piece<'a>> {
169 if let Some(&(pos, c)) = self.cur.peek() {
172 let curr_last_brace = self.last_opening_brace_pos;
173 self.last_opening_brace_pos = Some(self.to_span_index(pos));
175 if self.consume('{') {
176 self.last_opening_brace_pos = curr_last_brace;
178 Some(String(self.string(pos + 1)))
180 let arg = self.argument();
181 if let Some(arg_pos) = self.must_consume('}').map(|end| {
182 (self.to_span_index(pos), self.to_span_index(end + 1))
184 self.arg_places.push(arg_pos);
186 Some(NextArgument(arg))
191 if self.consume('}') {
192 Some(String(self.string(pos + 1)))
194 let err_pos = self.to_span_index(pos);
196 "unmatched `}` found",
198 "if you intended to print `}`, you can escape it using `}}`",
206 Some(String(self.string(pos)))
208 _ => Some(String(self.string(pos))),
216 impl<'a> Parser<'a> {
217 /// Creates a new parser for the given format string
220 style: Option<usize>,
222 append_newline: bool,
226 cur: s.char_indices().peekable(),
232 last_opening_brace_pos: None,
237 /// Notifies of an error. The message doesn't actually need to be of type
238 /// String, but I think it does when this eventually uses conditions so it
239 /// might as well start using it now.
240 fn err<S1: Into<string::String>, S2: Into<string::String>>(
247 self.errors.push(ParseError {
248 description: description.into(),
253 secondary_label: None,
257 /// Notifies of an error. The message doesn't actually need to be of type
258 /// String, but I think it does when this eventually uses conditions so it
259 /// might as well start using it now.
260 fn err_with_note<S1: Into<string::String>, S2: Into<string::String>, S3: Into<string::String>>(
268 self.errors.push(ParseError {
269 description: description.into(),
270 note: Some(note.into()),
274 secondary_label: None,
278 /// Optionally consumes the specified character. If the character is not at
279 /// the current position, then the current iterator isn't moved and false is
280 /// returned, otherwise the character is consumed and true is returned.
281 fn consume(&mut self, c: char) -> bool {
282 if let Some(&(_, maybe)) = self.cur.peek() {
294 fn raw(&self) -> usize {
295 self.style.map(|raw| raw + 1).unwrap_or(0)
298 fn to_span_index(&self, pos: usize) -> SpanIndex {
300 for skip in &self.skips {
303 } else if pos == *skip && self.raw() == 0 {
309 SpanIndex(self.raw() + pos + 1)
312 /// Forces consumption of the specified character. If the character is not
313 /// found, an error is emitted.
314 fn must_consume(&mut self, c: char) -> Option<usize> {
317 if let Some(&(pos, maybe)) = self.cur.peek() {
322 let pos = self.to_span_index(pos);
323 let description = format!("expected `'}}'`, found `{:?}`", maybe);
324 let label = "expected `}`".to_owned();
325 let (note, secondary_label) = if c == '}' {
326 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
327 self.last_opening_brace_pos.map(|pos| {
328 ("because of this opening brace".to_owned(), pos, pos)
333 self.errors.push(ParseError {
344 let description = format!("expected `{:?}` but string was terminated", c);
345 // point at closing `"`
346 let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
347 let pos = self.to_span_index(pos);
349 let label = format!("expected `{:?}`", c);
350 let (note, secondary_label) = if c == '}' {
351 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
352 self.last_opening_brace_pos.map(|pos| {
353 ("because of this opening brace".to_owned(), pos, pos)
358 self.errors.push(ParseError {
367 self.err(description, format!("expected `{:?}`", c), pos, pos);
373 /// Consumes all whitespace characters until the first non-whitespace character
375 while let Some(&(_, c)) = self.cur.peek() {
376 if c.is_whitespace() {
384 /// Parses all of a string which is to be considered a "raw literal" in a
385 /// format string. This is everything outside of the braces.
386 fn string(&mut self, start: usize) -> &'a str {
387 // we may not consume the character, peek the iterator
388 while let Some(&(pos, c)) = self.cur.peek() {
391 return &self.input[start..pos];
398 &self.input[start..self.input.len()]
401 /// Parses an Argument structure, or what's contained within braces inside the format string
402 fn argument(&mut self) -> Argument<'a> {
403 let pos = self.position();
404 let format = self.format();
406 // Resolve position after parsing format spec.
407 let pos = match pos {
408 Some(position) => position,
412 ArgumentImplicitlyIs(i)
422 /// Parses a positional argument for a format. This could either be an
423 /// integer index of an argument, a named argument, or a blank string.
424 /// Returns `Some(parsed_position)` if the position is not implicitly
425 /// consuming a macro argument, `None` if it's the case.
426 fn position(&mut self) -> Option<Position<'a>> {
427 if let Some(i) = self.integer() {
430 match self.cur.peek() {
431 Some(&(_, c)) if c.is_alphabetic() => Some(ArgumentNamed(self.word())),
432 Some(&(pos, c)) if c == '_' => {
433 let invalid_name = self.string(pos);
434 self.err_with_note(format!("invalid argument name `{}`", invalid_name),
435 "invalid argument name",
436 "argument names cannot start with an underscore",
437 self.to_span_index(pos),
438 self.to_span_index(pos + invalid_name.len()));
439 Some(ArgumentNamed(invalid_name))
442 // This is an `ArgumentNext`.
443 // Record the fact and do the resolution after parsing the
444 // format spec, to make things like `{:.*}` work.
450 /// Parses a format specifier at the current position, returning all of the
451 /// relevant information in the FormatSpec struct.
452 fn format(&mut self) -> FormatSpec<'a> {
453 let mut spec = FormatSpec {
457 precision: CountImplied,
459 ty: &self.input[..0],
461 if !self.consume(':') {
466 if let Some(&(_, c)) = self.cur.peek() {
467 match self.cur.clone().nth(1) {
468 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
476 if self.consume('<') {
477 spec.align = AlignLeft;
478 } else if self.consume('>') {
479 spec.align = AlignRight;
480 } else if self.consume('^') {
481 spec.align = AlignCenter;
484 if self.consume('+') {
485 spec.flags |= 1 << (FlagSignPlus as u32);
486 } else if self.consume('-') {
487 spec.flags |= 1 << (FlagSignMinus as u32);
490 if self.consume('#') {
491 spec.flags |= 1 << (FlagAlternate as u32);
493 // Width and precision
494 let mut havewidth = false;
495 if self.consume('0') {
496 // small ambiguity with '0$' as a format string. In theory this is a
497 // '0' flag and then an ill-formatted format string with just a '$'
498 // and no count, but this is better if we instead interpret this as
499 // no '0' flag and '0$' as the width instead.
500 if self.consume('$') {
501 spec.width = CountIsParam(0);
504 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
508 spec.width = self.count();
510 if self.consume('.') {
511 if self.consume('*') {
512 // Resolve `CountIsNextParam`.
513 // We can do this immediately as `position` is resolved later.
516 spec.precision = CountIsParam(i);
518 spec.precision = self.count();
521 // Optional radix followed by the actual format specifier
522 if self.consume('x') {
523 if self.consume('?') {
524 spec.flags |= 1 << (FlagDebugLowerHex as u32);
529 } else if self.consume('X') {
530 if self.consume('?') {
531 spec.flags |= 1 << (FlagDebugUpperHex as u32);
536 } else if self.consume('?') {
539 spec.ty = self.word();
544 /// Parses a Count parameter at the current position. This does not check
545 /// for 'CountIsNextParam' because that is only used in precision, not
547 fn count(&mut self) -> Count<'a> {
548 if let Some(i) = self.integer() {
549 if self.consume('$') {
555 let tmp = self.cur.clone();
556 let word = self.word();
560 } else if self.consume('$') {
569 /// Parses a word starting at the current position. A word is considered to
570 /// be an alphabetic character followed by any number of alphanumeric
572 fn word(&mut self) -> &'a str {
573 let start = match self.cur.peek() {
574 Some(&(pos, c)) if c.is_xid_start() => {
579 return &self.input[..0];
582 while let Some(&(pos, c)) = self.cur.peek() {
583 if c.is_xid_continue() {
586 return &self.input[start..pos];
589 &self.input[start..self.input.len()]
592 /// Optionally parses an integer at the current position. This doesn't deal
593 /// with overflow at all, it's just accumulating digits.
594 fn integer(&mut self) -> Option<usize> {
596 let mut found = false;
597 while let Some(&(_, c)) = self.cur.peek() {
598 if let Some(i) = c.to_digit(10) {
599 cur = cur * 10 + i as usize;
618 fn same(fmt: &'static str, p: &[Piece<'static>]) {
619 let parser = Parser::new(fmt, None, vec![], false);
620 assert!(parser.collect::<Vec<Piece<'static>>>() == p);
623 fn fmtdflt() -> FormatSpec<'static> {
628 precision: CountImplied,
634 fn musterr(s: &str) {
635 let mut p = Parser::new(s, None, vec![], false);
637 assert!(!p.errors.is_empty());
642 same("asdf", &[String("asdf")]);
643 same("a{{b", &[String("a"), String("{b")]);
644 same("a}}b", &[String("a"), String("}b")]);
645 same("a}}", &[String("a"), String("}")]);
646 same("}}", &[String("}")]);
647 same("\\}}", &[String("\\"), String("}")]);
672 fn format_nothing() {
674 &[NextArgument(Argument {
675 position: ArgumentImplicitlyIs(0),
680 fn format_position() {
682 &[NextArgument(Argument {
683 position: ArgumentIs(3),
688 fn format_position_nothing_else() {
690 &[NextArgument(Argument {
691 position: ArgumentIs(3),
698 &[NextArgument(Argument {
699 position: ArgumentIs(3),
704 precision: CountImplied,
711 fn format_align_fill() {
713 &[NextArgument(Argument {
714 position: ArgumentIs(3),
719 precision: CountImplied,
725 &[NextArgument(Argument {
726 position: ArgumentIs(3),
731 precision: CountImplied,
737 &[NextArgument(Argument {
738 position: ArgumentIs(3),
743 precision: CountImplied,
752 &[NextArgument(Argument {
753 position: ArgumentImplicitlyIs(0),
758 precision: CountImplied,
764 &[NextArgument(Argument {
765 position: ArgumentImplicitlyIs(0),
770 precision: CountIs(10),
771 width: CountIsParam(10),
776 &[NextArgument(Argument {
777 position: ArgumentImplicitlyIs(1),
782 precision: CountIsParam(0),
788 &[NextArgument(Argument {
789 position: ArgumentImplicitlyIs(0),
794 precision: CountIsParam(10),
800 &[NextArgument(Argument {
801 position: ArgumentImplicitlyIs(0),
806 precision: CountIsName("b"),
807 width: CountIsName("a"),
815 &[NextArgument(Argument {
816 position: ArgumentImplicitlyIs(0),
820 flags: (1 << FlagSignMinus as u32),
821 precision: CountImplied,
827 &[NextArgument(Argument {
828 position: ArgumentImplicitlyIs(0),
832 flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32),
833 precision: CountImplied,
840 fn format_mixture() {
841 same("abcd {3:a} efg",
843 NextArgument(Argument {
844 position: ArgumentIs(3),
849 precision: CountImplied,