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 /// A piece is a portion of the format string which represents the next part
28 /// to emit. These are emitted as a stream by the `Parser` class.
29 #[derive(Copy, Clone, PartialEq)]
31 /// A literal string which should directly be emitted
33 /// This describes that formatting should process the next argument (as
34 /// specified inside) for emission.
35 NextArgument(Argument<'a>),
38 /// Representation of an argument specification.
39 #[derive(Copy, Clone, PartialEq)]
40 pub struct Argument<'a> {
41 /// Where to find this argument
42 pub position: Position<'a>,
43 /// How to format the argument
44 pub format: FormatSpec<'a>,
47 /// Specification for the formatting of an argument in the format string.
48 #[derive(Copy, Clone, PartialEq)]
49 pub struct FormatSpec<'a> {
50 /// Optionally specified character to fill alignment with
51 pub fill: Option<char>,
52 /// Optionally specified alignment
54 /// Packed version of various flags provided
56 /// The integer precision to use
57 pub precision: Count<'a>,
58 /// The string width requested for the resulting format
60 /// The descriptor string representing the name of the format desired for
61 /// this argument, this can be empty or any number of characters, although
62 /// it is required to be one word.
66 /// Enum describing where an argument for a format can be located.
67 #[derive(Copy, Clone, PartialEq)]
68 pub enum Position<'a> {
69 /// The argument is implied to be located at an index
70 ArgumentImplicitlyIs(usize),
71 /// The argument is located at a specific index given in the format
73 /// The argument has a name.
74 ArgumentNamed(&'a str),
78 pub fn index(&self) -> Option<usize> {
80 ArgumentIs(i) | ArgumentImplicitlyIs(i) => Some(*i),
86 /// Enum of alignments which are supported.
87 #[derive(Copy, Clone, PartialEq)]
89 /// The value will be aligned to the left.
91 /// The value will be aligned to the right.
93 /// The value will be aligned in the center.
95 /// The value will take on a default alignment.
99 /// Various flags which can be applied to format strings. The meaning of these
100 /// flags is defined by the formatters themselves.
101 #[derive(Copy, Clone, PartialEq)]
103 /// A `+` will be used to denote positive numbers.
105 /// A `-` will be used to denote negative numbers. This is the default.
107 /// An alternate form will be used for the value. In the case of numbers,
108 /// this means that the number will be prefixed with the supplied string.
110 /// For numbers, this means that the number will be padded with zeroes,
111 /// and the sign (`+` or `-`) will precede them.
112 FlagSignAwareZeroPad,
113 /// For Debug / `?`, format integers in lower-case hexadecimal.
115 /// For Debug / `?`, format integers in upper-case hexadecimal.
119 /// A count is used for the precision and width parameters of an integer, and
120 /// can reference either an argument or a literal integer.
121 #[derive(Copy, Clone, PartialEq)]
123 /// The count is specified explicitly.
125 /// The count is specified by the argument with the given name.
126 CountIsName(&'a str),
127 /// The count is specified by the argument at the given index.
129 /// The count is implied and cannot be explicitly specified.
133 pub struct ParseError {
134 pub description: string::String,
135 pub note: Option<string::String>,
136 pub label: string::String,
137 pub start: SpanIndex,
139 pub secondary_label: Option<(string::String, SpanIndex, SpanIndex)>,
142 /// The parser structure for interpreting the input format string. This is
143 /// modeled as an iterator over `Piece` structures to form a stream of tokens
146 /// This is a recursive-descent parser for the sake of simplicity, and if
147 /// necessary there's probably lots of room for improvement performance-wise.
148 pub struct Parser<'a> {
150 cur: iter::Peekable<str::CharIndices<'a>>,
151 /// Error messages accumulated during parsing
152 pub errors: Vec<ParseError>,
153 /// Current position of implicit positional argument pointer
155 /// `Some(raw count)` when the string is "raw", used to position spans correctly
156 style: Option<usize>,
157 /// Start and end byte offset of every successfully parsed argument
158 pub arg_places: Vec<(SpanIndex, SpanIndex)>,
159 /// Characters that need to be shifted
161 /// Span offset of the last opening brace seen, used for error reporting
162 last_opening_brace_pos: Option<SpanIndex>,
163 /// Wether the source string is comes from `println!` as opposed to `format!` or `print!`
164 append_newline: bool,
167 #[derive(Clone, Copy, Debug)]
168 pub struct SpanIndex(pub usize);
171 pub fn unwrap(self) -> usize {
176 impl<'a> Iterator for Parser<'a> {
177 type Item = Piece<'a>;
179 fn next(&mut self) -> Option<Piece<'a>> {
180 if let Some(&(pos, c)) = self.cur.peek() {
183 let curr_last_brace = self.last_opening_brace_pos;
184 self.last_opening_brace_pos = Some(self.to_span_index(pos));
186 if self.consume('{') {
187 self.last_opening_brace_pos = curr_last_brace;
189 Some(String(self.string(pos + 1)))
191 let arg = self.argument();
192 if let Some(arg_pos) = self.must_consume('}').map(|end| {
193 (self.to_span_index(pos), self.to_span_index(end + 1))
195 self.arg_places.push(arg_pos);
197 Some(NextArgument(arg))
202 if self.consume('}') {
203 Some(String(self.string(pos + 1)))
205 let err_pos = self.to_span_index(pos);
207 "unmatched `}` found",
209 "if you intended to print `}`, you can escape it using `}}`",
217 Some(String(self.string(pos)))
219 _ => Some(String(self.string(pos))),
227 impl<'a> Parser<'a> {
228 /// Creates a new parser for the given format string
231 style: Option<usize>,
233 append_newline: bool,
237 cur: s.char_indices().peekable(),
243 last_opening_brace_pos: None,
248 /// Notifies of an error. The message doesn't actually need to be of type
249 /// String, but I think it does when this eventually uses conditions so it
250 /// might as well start using it now.
251 fn err<S1: Into<string::String>, S2: Into<string::String>>(
258 self.errors.push(ParseError {
259 description: description.into(),
264 secondary_label: None,
268 /// Notifies of an error. The message doesn't actually need to be of type
269 /// String, but I think it does when this eventually uses conditions so it
270 /// might as well start using it now.
271 fn err_with_note<S1: Into<string::String>, S2: Into<string::String>, S3: Into<string::String>>(
279 self.errors.push(ParseError {
280 description: description.into(),
281 note: Some(note.into()),
285 secondary_label: None,
289 /// Optionally consumes the specified character. If the character is not at
290 /// the current position, then the current iterator isn't moved and false is
291 /// returned, otherwise the character is consumed and true is returned.
292 fn consume(&mut self, c: char) -> bool {
293 if let Some(&(_, maybe)) = self.cur.peek() {
305 fn to_span_index(&self, pos: usize) -> SpanIndex {
307 let raw = self.style.map(|raw| raw + 1).unwrap_or(0);
308 for skip in &self.skips {
311 } else if pos == *skip && raw == 0 {
317 SpanIndex(raw + pos + 1)
320 /// Forces consumption of the specified character. If the character is not
321 /// found, an error is emitted.
322 fn must_consume(&mut self, c: char) -> Option<usize> {
325 if let Some(&(pos, maybe)) = self.cur.peek() {
330 let pos = self.to_span_index(pos);
331 let description = format!("expected `'}}'`, found `{:?}`", maybe);
332 let label = "expected `}`".to_owned();
333 let (note, secondary_label) = if c == '}' {
334 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
335 self.last_opening_brace_pos.map(|pos| {
336 ("because of this opening brace".to_owned(), pos, pos)
341 self.errors.push(ParseError {
352 let description = format!("expected `{:?}` but string was terminated", c);
353 // point at closing `"`
354 let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
355 let pos = self.to_span_index(pos);
357 let label = format!("expected `{:?}`", c);
358 let (note, secondary_label) = if c == '}' {
359 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
360 self.last_opening_brace_pos.map(|pos| {
361 ("because of this opening brace".to_owned(), pos, pos)
366 self.errors.push(ParseError {
375 self.err(description, format!("expected `{:?}`", c), pos, pos);
381 /// Consumes all whitespace characters until the first non-whitespace character
383 while let Some(&(_, c)) = self.cur.peek() {
384 if c.is_whitespace() {
392 /// Parses all of a string which is to be considered a "raw literal" in a
393 /// format string. This is everything outside of the braces.
394 fn string(&mut self, start: usize) -> &'a str {
395 // we may not consume the character, peek the iterator
396 while let Some(&(pos, c)) = self.cur.peek() {
399 return &self.input[start..pos];
406 &self.input[start..self.input.len()]
409 /// Parses an Argument structure, or what's contained within braces inside the format string
410 fn argument(&mut self) -> Argument<'a> {
411 let pos = self.position();
412 let format = self.format();
414 // Resolve position after parsing format spec.
415 let pos = match pos {
416 Some(position) => position,
420 ArgumentImplicitlyIs(i)
430 /// Parses a positional argument for a format. This could either be an
431 /// integer index of an argument, a named argument, or a blank string.
432 /// Returns `Some(parsed_position)` if the position is not implicitly
433 /// consuming a macro argument, `None` if it's the case.
434 fn position(&mut self) -> Option<Position<'a>> {
435 if let Some(i) = self.integer() {
438 match self.cur.peek() {
439 Some(&(_, c)) if c.is_alphabetic() => Some(ArgumentNamed(self.word())),
440 Some(&(pos, c)) if c == '_' => {
441 let invalid_name = self.string(pos);
442 self.err_with_note(format!("invalid argument name `{}`", invalid_name),
443 "invalid argument name",
444 "argument names cannot start with an underscore",
445 self.to_span_index(pos),
446 self.to_span_index(pos + invalid_name.len()));
447 Some(ArgumentNamed(invalid_name))
450 // This is an `ArgumentNext`.
451 // Record the fact and do the resolution after parsing the
452 // format spec, to make things like `{:.*}` work.
458 /// Parses a format specifier at the current position, returning all of the
459 /// relevant information in the FormatSpec struct.
460 fn format(&mut self) -> FormatSpec<'a> {
461 let mut spec = FormatSpec {
465 precision: CountImplied,
467 ty: &self.input[..0],
469 if !self.consume(':') {
474 if let Some(&(_, c)) = self.cur.peek() {
475 match self.cur.clone().nth(1) {
476 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
484 if self.consume('<') {
485 spec.align = AlignLeft;
486 } else if self.consume('>') {
487 spec.align = AlignRight;
488 } else if self.consume('^') {
489 spec.align = AlignCenter;
492 if self.consume('+') {
493 spec.flags |= 1 << (FlagSignPlus as u32);
494 } else if self.consume('-') {
495 spec.flags |= 1 << (FlagSignMinus as u32);
498 if self.consume('#') {
499 spec.flags |= 1 << (FlagAlternate as u32);
501 // Width and precision
502 let mut havewidth = false;
503 if self.consume('0') {
504 // small ambiguity with '0$' as a format string. In theory this is a
505 // '0' flag and then an ill-formatted format string with just a '$'
506 // and no count, but this is better if we instead interpret this as
507 // no '0' flag and '0$' as the width instead.
508 if self.consume('$') {
509 spec.width = CountIsParam(0);
512 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
516 spec.width = self.count();
518 if self.consume('.') {
519 if self.consume('*') {
520 // Resolve `CountIsNextParam`.
521 // We can do this immediately as `position` is resolved later.
524 spec.precision = CountIsParam(i);
526 spec.precision = self.count();
529 // Optional radix followed by the actual format specifier
530 if self.consume('x') {
531 if self.consume('?') {
532 spec.flags |= 1 << (FlagDebugLowerHex as u32);
537 } else if self.consume('X') {
538 if self.consume('?') {
539 spec.flags |= 1 << (FlagDebugUpperHex as u32);
544 } else if self.consume('?') {
547 spec.ty = self.word();
552 /// Parses a Count parameter at the current position. This does not check
553 /// for 'CountIsNextParam' because that is only used in precision, not
555 fn count(&mut self) -> Count<'a> {
556 if let Some(i) = self.integer() {
557 if self.consume('$') {
563 let tmp = self.cur.clone();
564 let word = self.word();
568 } else if self.consume('$') {
577 /// Parses a word starting at the current position. A word is considered to
578 /// be an alphabetic character followed by any number of alphanumeric
580 fn word(&mut self) -> &'a str {
581 let start = match self.cur.peek() {
582 Some(&(pos, c)) if c.is_xid_start() => {
587 return &self.input[..0];
590 while let Some(&(pos, c)) = self.cur.peek() {
591 if c.is_xid_continue() {
594 return &self.input[start..pos];
597 &self.input[start..self.input.len()]
600 /// Optionally parses an integer at the current position. This doesn't deal
601 /// with overflow at all, it's just accumulating digits.
602 fn integer(&mut self) -> Option<usize> {
604 let mut found = false;
605 while let Some(&(_, c)) = self.cur.peek() {
606 if let Some(i) = c.to_digit(10) {
607 cur = cur * 10 + i as usize;
626 fn same(fmt: &'static str, p: &[Piece<'static>]) {
627 let parser = Parser::new(fmt, None, vec![], false);
628 assert!(parser.collect::<Vec<Piece<'static>>>() == p);
631 fn fmtdflt() -> FormatSpec<'static> {
636 precision: CountImplied,
642 fn musterr(s: &str) {
643 let mut p = Parser::new(s, None, vec![], false);
645 assert!(!p.errors.is_empty());
650 same("asdf", &[String("asdf")]);
651 same("a{{b", &[String("a"), String("{b")]);
652 same("a}}b", &[String("a"), String("}b")]);
653 same("a}}", &[String("a"), String("}")]);
654 same("}}", &[String("}")]);
655 same("\\}}", &[String("\\"), String("}")]);
680 fn format_nothing() {
682 &[NextArgument(Argument {
683 position: ArgumentImplicitlyIs(0),
688 fn format_position() {
690 &[NextArgument(Argument {
691 position: ArgumentIs(3),
696 fn format_position_nothing_else() {
698 &[NextArgument(Argument {
699 position: ArgumentIs(3),
706 &[NextArgument(Argument {
707 position: ArgumentIs(3),
712 precision: CountImplied,
719 fn format_align_fill() {
721 &[NextArgument(Argument {
722 position: ArgumentIs(3),
727 precision: CountImplied,
733 &[NextArgument(Argument {
734 position: ArgumentIs(3),
739 precision: CountImplied,
745 &[NextArgument(Argument {
746 position: ArgumentIs(3),
751 precision: CountImplied,
760 &[NextArgument(Argument {
761 position: ArgumentImplicitlyIs(0),
766 precision: CountImplied,
772 &[NextArgument(Argument {
773 position: ArgumentImplicitlyIs(0),
778 precision: CountIs(10),
779 width: CountIsParam(10),
784 &[NextArgument(Argument {
785 position: ArgumentImplicitlyIs(1),
790 precision: CountIsParam(0),
796 &[NextArgument(Argument {
797 position: ArgumentImplicitlyIs(0),
802 precision: CountIsParam(10),
808 &[NextArgument(Argument {
809 position: ArgumentImplicitlyIs(0),
814 precision: CountIsName("b"),
815 width: CountIsName("a"),
823 &[NextArgument(Argument {
824 position: ArgumentImplicitlyIs(0),
828 flags: (1 << FlagSignMinus as u32),
829 precision: CountImplied,
835 &[NextArgument(Argument {
836 position: ArgumentImplicitlyIs(0),
840 flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32),
841 precision: CountImplied,
848 fn format_mixture() {
849 same("abcd {3:a} efg",
851 NextArgument(Argument {
852 position: ArgumentIs(3),
857 precision: CountImplied,