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)]
12 #![cfg_attr(not(stage0), deny(internal))]
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 raw(&self) -> usize {
306 self.style.map(|raw| raw + 1).unwrap_or(0)
309 fn to_span_index(&self, pos: usize) -> SpanIndex {
311 for skip in &self.skips {
314 } else if pos == *skip && self.raw() == 0 {
320 SpanIndex(self.raw() + pos + 1)
323 /// Forces consumption of the specified character. If the character is not
324 /// found, an error is emitted.
325 fn must_consume(&mut self, c: char) -> Option<usize> {
328 if let Some(&(pos, maybe)) = self.cur.peek() {
333 let pos = self.to_span_index(pos);
334 let description = format!("expected `'}}'`, found `{:?}`", maybe);
335 let label = "expected `}`".to_owned();
336 let (note, secondary_label) = if c == '}' {
337 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
338 self.last_opening_brace_pos.map(|pos| {
339 ("because of this opening brace".to_owned(), pos, pos)
344 self.errors.push(ParseError {
355 let description = format!("expected `{:?}` but string was terminated", c);
356 // point at closing `"`
357 let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
358 let pos = self.to_span_index(pos);
360 let label = format!("expected `{:?}`", c);
361 let (note, secondary_label) = if c == '}' {
362 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
363 self.last_opening_brace_pos.map(|pos| {
364 ("because of this opening brace".to_owned(), pos, pos)
369 self.errors.push(ParseError {
378 self.err(description, format!("expected `{:?}`", c), pos, pos);
384 /// Consumes all whitespace characters until the first non-whitespace character
386 while let Some(&(_, c)) = self.cur.peek() {
387 if c.is_whitespace() {
395 /// Parses all of a string which is to be considered a "raw literal" in a
396 /// format string. This is everything outside of the braces.
397 fn string(&mut self, start: usize) -> &'a str {
398 // we may not consume the character, peek the iterator
399 while let Some(&(pos, c)) = self.cur.peek() {
402 return &self.input[start..pos];
409 &self.input[start..self.input.len()]
412 /// Parses an Argument structure, or what's contained within braces inside the format string
413 fn argument(&mut self) -> Argument<'a> {
414 let pos = self.position();
415 let format = self.format();
417 // Resolve position after parsing format spec.
418 let pos = match pos {
419 Some(position) => position,
423 ArgumentImplicitlyIs(i)
433 /// Parses a positional argument for a format. This could either be an
434 /// integer index of an argument, a named argument, or a blank string.
435 /// Returns `Some(parsed_position)` if the position is not implicitly
436 /// consuming a macro argument, `None` if it's the case.
437 fn position(&mut self) -> Option<Position<'a>> {
438 if let Some(i) = self.integer() {
441 match self.cur.peek() {
442 Some(&(_, c)) if c.is_alphabetic() => Some(ArgumentNamed(self.word())),
443 Some(&(pos, c)) if c == '_' => {
444 let invalid_name = self.string(pos);
445 self.err_with_note(format!("invalid argument name `{}`", invalid_name),
446 "invalid argument name",
447 "argument names cannot start with an underscore",
448 self.to_span_index(pos),
449 self.to_span_index(pos + invalid_name.len()));
450 Some(ArgumentNamed(invalid_name))
453 // This is an `ArgumentNext`.
454 // Record the fact and do the resolution after parsing the
455 // format spec, to make things like `{:.*}` work.
461 /// Parses a format specifier at the current position, returning all of the
462 /// relevant information in the FormatSpec struct.
463 fn format(&mut self) -> FormatSpec<'a> {
464 let mut spec = FormatSpec {
468 precision: CountImplied,
470 ty: &self.input[..0],
472 if !self.consume(':') {
477 if let Some(&(_, c)) = self.cur.peek() {
478 match self.cur.clone().nth(1) {
479 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
487 if self.consume('<') {
488 spec.align = AlignLeft;
489 } else if self.consume('>') {
490 spec.align = AlignRight;
491 } else if self.consume('^') {
492 spec.align = AlignCenter;
495 if self.consume('+') {
496 spec.flags |= 1 << (FlagSignPlus as u32);
497 } else if self.consume('-') {
498 spec.flags |= 1 << (FlagSignMinus as u32);
501 if self.consume('#') {
502 spec.flags |= 1 << (FlagAlternate as u32);
504 // Width and precision
505 let mut havewidth = false;
506 if self.consume('0') {
507 // small ambiguity with '0$' as a format string. In theory this is a
508 // '0' flag and then an ill-formatted format string with just a '$'
509 // and no count, but this is better if we instead interpret this as
510 // no '0' flag and '0$' as the width instead.
511 if self.consume('$') {
512 spec.width = CountIsParam(0);
515 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
519 spec.width = self.count();
521 if self.consume('.') {
522 if self.consume('*') {
523 // Resolve `CountIsNextParam`.
524 // We can do this immediately as `position` is resolved later.
527 spec.precision = CountIsParam(i);
529 spec.precision = self.count();
532 // Optional radix followed by the actual format specifier
533 if self.consume('x') {
534 if self.consume('?') {
535 spec.flags |= 1 << (FlagDebugLowerHex as u32);
540 } else if self.consume('X') {
541 if self.consume('?') {
542 spec.flags |= 1 << (FlagDebugUpperHex as u32);
547 } else if self.consume('?') {
550 spec.ty = self.word();
555 /// Parses a Count parameter at the current position. This does not check
556 /// for 'CountIsNextParam' because that is only used in precision, not
558 fn count(&mut self) -> Count<'a> {
559 if let Some(i) = self.integer() {
560 if self.consume('$') {
566 let tmp = self.cur.clone();
567 let word = self.word();
571 } else if self.consume('$') {
580 /// Parses a word starting at the current position. A word is considered to
581 /// be an alphabetic character followed by any number of alphanumeric
583 fn word(&mut self) -> &'a str {
584 let start = match self.cur.peek() {
585 Some(&(pos, c)) if c.is_xid_start() => {
590 return &self.input[..0];
593 while let Some(&(pos, c)) = self.cur.peek() {
594 if c.is_xid_continue() {
597 return &self.input[start..pos];
600 &self.input[start..self.input.len()]
603 /// Optionally parses an integer at the current position. This doesn't deal
604 /// with overflow at all, it's just accumulating digits.
605 fn integer(&mut self) -> Option<usize> {
607 let mut found = false;
608 while let Some(&(_, c)) = self.cur.peek() {
609 if let Some(i) = c.to_digit(10) {
610 cur = cur * 10 + i as usize;
629 fn same(fmt: &'static str, p: &[Piece<'static>]) {
630 let parser = Parser::new(fmt, None, vec![], false);
631 assert!(parser.collect::<Vec<Piece<'static>>>() == p);
634 fn fmtdflt() -> FormatSpec<'static> {
639 precision: CountImplied,
645 fn musterr(s: &str) {
646 let mut p = Parser::new(s, None, vec![], false);
648 assert!(!p.errors.is_empty());
653 same("asdf", &[String("asdf")]);
654 same("a{{b", &[String("a"), String("{b")]);
655 same("a}}b", &[String("a"), String("}b")]);
656 same("a}}", &[String("a"), String("}")]);
657 same("}}", &[String("}")]);
658 same("\\}}", &[String("\\"), String("}")]);
683 fn format_nothing() {
685 &[NextArgument(Argument {
686 position: ArgumentImplicitlyIs(0),
691 fn format_position() {
693 &[NextArgument(Argument {
694 position: ArgumentIs(3),
699 fn format_position_nothing_else() {
701 &[NextArgument(Argument {
702 position: ArgumentIs(3),
709 &[NextArgument(Argument {
710 position: ArgumentIs(3),
715 precision: CountImplied,
722 fn format_align_fill() {
724 &[NextArgument(Argument {
725 position: ArgumentIs(3),
730 precision: CountImplied,
736 &[NextArgument(Argument {
737 position: ArgumentIs(3),
742 precision: CountImplied,
748 &[NextArgument(Argument {
749 position: ArgumentIs(3),
754 precision: CountImplied,
763 &[NextArgument(Argument {
764 position: ArgumentImplicitlyIs(0),
769 precision: CountImplied,
775 &[NextArgument(Argument {
776 position: ArgumentImplicitlyIs(0),
781 precision: CountIs(10),
782 width: CountIsParam(10),
787 &[NextArgument(Argument {
788 position: ArgumentImplicitlyIs(1),
793 precision: CountIsParam(0),
799 &[NextArgument(Argument {
800 position: ArgumentImplicitlyIs(0),
805 precision: CountIsParam(10),
811 &[NextArgument(Argument {
812 position: ArgumentImplicitlyIs(0),
817 precision: CountIsName("b"),
818 width: CountIsName("a"),
826 &[NextArgument(Argument {
827 position: ArgumentImplicitlyIs(0),
831 flags: (1 << FlagSignMinus as u32),
832 precision: CountImplied,
838 &[NextArgument(Argument {
839 position: ArgumentImplicitlyIs(0),
843 flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32),
844 precision: CountImplied,
851 fn format_mixture() {
852 same("abcd {3:a} efg",
854 NextArgument(Argument {
855 position: ArgumentIs(3),
860 precision: CountImplied,