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::{InnerSpan, Symbol};
29 #[derive(Copy, Clone)]
30 struct InnerOffset(usize);
33 fn to(self, end: InnerOffset) -> InnerSpan {
34 InnerSpan::new(self.0, end.0)
38 /// A piece is a portion of the format string which represents the next part
39 /// to emit. These are emitted as a stream by the `Parser` class.
40 #[derive(Copy, Clone, PartialEq)]
42 /// A literal string which should directly be emitted
44 /// This describes that formatting should process the next argument (as
45 /// specified inside) for emission.
46 NextArgument(Argument<'a>),
49 /// Representation of an argument specification.
50 #[derive(Copy, Clone, PartialEq)]
51 pub struct Argument<'a> {
52 /// Where to find this argument
53 pub position: Position,
54 /// How to format the argument
55 pub format: FormatSpec<'a>,
58 /// Specification for the formatting of an argument in the format string.
59 #[derive(Copy, Clone, PartialEq)]
60 pub struct FormatSpec<'a> {
61 /// Optionally specified character to fill alignment with
62 pub fill: Option<char>,
63 /// Optionally specified alignment
65 /// Packed version of various flags provided
67 /// The integer precision to use
69 /// The string width requested for the resulting format
71 /// The descriptor string representing the name of the format desired for
72 /// this argument, this can be empty or any number of characters, although
73 /// it is required to be one word.
77 /// Enum describing where an argument for a format can be located.
78 #[derive(Copy, Clone, PartialEq)]
80 /// The argument is implied to be located at an index
81 ArgumentImplicitlyIs(usize),
82 /// The argument is located at a specific index given in the format
84 /// The argument has a name.
85 ArgumentNamed(Symbol),
89 pub fn index(&self) -> Option<usize> {
91 ArgumentIs(i) | ArgumentImplicitlyIs(i) => Some(*i),
97 /// Enum of alignments which are supported.
98 #[derive(Copy, Clone, PartialEq)]
100 /// The value will be aligned to the left.
102 /// The value will be aligned to the right.
104 /// The value will be aligned in the center.
106 /// The value will take on a default alignment.
110 /// Various flags which can be applied to format strings. The meaning of these
111 /// flags is defined by the formatters themselves.
112 #[derive(Copy, Clone, PartialEq)]
114 /// A `+` will be used to denote positive numbers.
116 /// A `-` will be used to denote negative numbers. This is the default.
118 /// An alternate form will be used for the value. In the case of numbers,
119 /// this means that the number will be prefixed with the supplied string.
121 /// For numbers, this means that the number will be padded with zeroes,
122 /// and the sign (`+` or `-`) will precede them.
123 FlagSignAwareZeroPad,
124 /// For Debug / `?`, format integers in lower-case hexadecimal.
126 /// For Debug / `?`, format integers in upper-case hexadecimal.
130 /// A count is used for the precision and width parameters of an integer, and
131 /// can reference either an argument or a literal integer.
132 #[derive(Copy, Clone, PartialEq)]
134 /// The count is specified explicitly.
136 /// The count is specified by the argument with the given name.
138 /// The count is specified by the argument at the given index.
140 /// The count is implied and cannot be explicitly specified.
144 pub struct ParseError {
145 pub description: string::String,
146 pub note: Option<string::String>,
147 pub label: string::String,
149 pub secondary_label: Option<(string::String, InnerSpan)>,
152 /// The parser structure for interpreting the input format string. This is
153 /// modeled as an iterator over `Piece` structures to form a stream of tokens
156 /// This is a recursive-descent parser for the sake of simplicity, and if
157 /// necessary there's probably lots of room for improvement performance-wise.
158 pub struct Parser<'a> {
160 cur: iter::Peekable<str::CharIndices<'a>>,
161 /// Error messages accumulated during parsing
162 pub errors: Vec<ParseError>,
163 /// Current position of implicit positional argument pointer
165 /// `Some(raw count)` when the string is "raw", used to position spans correctly
166 style: Option<usize>,
167 /// Start and end byte offset of every successfully parsed argument
168 pub arg_places: Vec<InnerSpan>,
169 /// Characters that need to be shifted
171 /// Span of the last opening brace seen, used for error reporting
172 last_opening_brace: Option<InnerSpan>,
173 /// Wether the source string is comes from `println!` as opposed to `format!` or `print!`
174 append_newline: bool,
177 impl<'a> Iterator for Parser<'a> {
178 type Item = Piece<'a>;
180 fn next(&mut self) -> Option<Piece<'a>> {
181 if let Some(&(pos, c)) = self.cur.peek() {
184 let curr_last_brace = self.last_opening_brace;
185 let byte_pos = self.to_span_index(pos);
186 self.last_opening_brace = Some(byte_pos.to(byte_pos));
188 if self.consume('{') {
189 self.last_opening_brace = curr_last_brace;
191 Some(String(self.string(pos + 1)))
193 let arg = self.argument();
194 if let Some(end) = self.must_consume('}') {
195 let start = self.to_span_index(pos);
196 let end = self.to_span_index(end + 1);
197 self.arg_places.push(start.to(end));
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 `}}`",
218 Some(String(self.string(pos)))
220 _ => Some(String(self.string(pos))),
228 impl<'a> Parser<'a> {
229 /// Creates a new parser for the given format string
232 style: Option<usize>,
234 append_newline: bool,
238 cur: s.char_indices().peekable(),
244 last_opening_brace: None,
249 /// Notifies of an error. The message doesn't actually need to be of type
250 /// String, but I think it does when this eventually uses conditions so it
251 /// might as well start using it now.
252 fn err<S1: Into<string::String>, S2: Into<string::String>>(
258 self.errors.push(ParseError {
259 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>>(
277 self.errors.push(ParseError {
278 description: description.into(),
279 note: Some(note.into()),
282 secondary_label: None,
286 /// Optionally consumes the specified character. If the character is not at
287 /// the current position, then the current iterator isn't moved and false is
288 /// returned, otherwise the character is consumed and true is returned.
289 fn consume(&mut self, c: char) -> bool {
290 if let Some(&(_, maybe)) = self.cur.peek() {
302 fn to_span_index(&self, pos: usize) -> InnerOffset {
304 let raw = self.style.map(|raw| raw + 1).unwrap_or(0);
305 for skip in &self.skips {
308 } else if pos == *skip && raw == 0 {
314 InnerOffset(raw + pos + 1)
317 /// Forces consumption of the specified character. If the character is not
318 /// found, an error is emitted.
319 fn must_consume(&mut self, c: char) -> Option<usize> {
322 if let Some(&(pos, maybe)) = self.cur.peek() {
327 let pos = self.to_span_index(pos);
328 let description = format!("expected `'}}'`, found `{:?}`", maybe);
329 let label = "expected `}`".to_owned();
330 let (note, secondary_label) = if c == '}' {
331 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
332 self.last_opening_brace.map(|sp| {
333 ("because of this opening brace".to_owned(), sp)
338 self.errors.push(ParseError {
348 let description = format!("expected `{:?}` but string was terminated", c);
349 // point at closing `"`
350 let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
351 let pos = self.to_span_index(pos);
353 let label = format!("expected `{:?}`", c);
354 let (note, secondary_label) = if c == '}' {
355 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
356 self.last_opening_brace.map(|sp| {
357 ("because of this opening brace".to_owned(), sp)
362 self.errors.push(ParseError {
370 self.err(description, format!("expected `{:?}`", c), pos.to(pos));
376 /// Consumes all whitespace characters until the first non-whitespace character
378 while let Some(&(_, c)) = self.cur.peek() {
379 if c.is_whitespace() {
387 /// Parses all of a string which is to be considered a "raw literal" in a
388 /// format string. This is everything outside of the braces.
389 fn string(&mut self, start: usize) -> &'a str {
390 // we may not consume the character, peek the iterator
391 while let Some(&(pos, c)) = self.cur.peek() {
394 return &self.input[start..pos];
401 &self.input[start..self.input.len()]
404 /// Parses an Argument structure, or what's contained within braces inside the format string
405 fn argument(&mut self) -> Argument<'a> {
406 let pos = self.position();
407 let format = self.format();
409 // Resolve position after parsing format spec.
410 let pos = match pos {
411 Some(position) => position,
415 ArgumentImplicitlyIs(i)
425 /// Parses a positional argument for a format. This could either be an
426 /// integer index of an argument, a named argument, or a blank string.
427 /// Returns `Some(parsed_position)` if the position is not implicitly
428 /// consuming a macro argument, `None` if it's the case.
429 fn position(&mut self) -> Option<Position> {
430 if let Some(i) = self.integer() {
433 match self.cur.peek() {
434 Some(&(_, c)) if c.is_alphabetic() => {
435 Some(ArgumentNamed(Symbol::intern(self.word())))
437 Some(&(pos, c)) if c == '_' => {
438 let invalid_name = self.string(pos);
439 self.err_with_note(format!("invalid argument name `{}`", invalid_name),
440 "invalid argument name",
441 "argument names cannot start with an underscore",
442 self.to_span_index(pos).to(
443 self.to_span_index(pos + invalid_name.len())
446 Some(ArgumentNamed(Symbol::intern(invalid_name)))
449 // This is an `ArgumentNext`.
450 // Record the fact and do the resolution after parsing the
451 // format spec, to make things like `{:.*}` work.
457 /// Parses a format specifier at the current position, returning all of the
458 /// relevant information in the FormatSpec struct.
459 fn format(&mut self) -> FormatSpec<'a> {
460 let mut spec = FormatSpec {
464 precision: CountImplied,
466 ty: &self.input[..0],
468 if !self.consume(':') {
473 if let Some(&(_, c)) = self.cur.peek() {
474 match self.cur.clone().nth(1) {
475 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
483 if self.consume('<') {
484 spec.align = AlignLeft;
485 } else if self.consume('>') {
486 spec.align = AlignRight;
487 } else if self.consume('^') {
488 spec.align = AlignCenter;
491 if self.consume('+') {
492 spec.flags |= 1 << (FlagSignPlus as u32);
493 } else if self.consume('-') {
494 spec.flags |= 1 << (FlagSignMinus as u32);
497 if self.consume('#') {
498 spec.flags |= 1 << (FlagAlternate as u32);
500 // Width and precision
501 let mut havewidth = false;
502 if self.consume('0') {
503 // small ambiguity with '0$' as a format string. In theory this is a
504 // '0' flag and then an ill-formatted format string with just a '$'
505 // and no count, but this is better if we instead interpret this as
506 // no '0' flag and '0$' as the width instead.
507 if self.consume('$') {
508 spec.width = CountIsParam(0);
511 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
515 spec.width = self.count();
517 if self.consume('.') {
518 if self.consume('*') {
519 // Resolve `CountIsNextParam`.
520 // We can do this immediately as `position` is resolved later.
523 spec.precision = CountIsParam(i);
525 spec.precision = self.count();
528 // Optional radix followed by the actual format specifier
529 if self.consume('x') {
530 if self.consume('?') {
531 spec.flags |= 1 << (FlagDebugLowerHex as u32);
536 } else if self.consume('X') {
537 if self.consume('?') {
538 spec.flags |= 1 << (FlagDebugUpperHex as u32);
543 } else if self.consume('?') {
546 spec.ty = self.word();
551 /// Parses a Count parameter at the current position. This does not check
552 /// for 'CountIsNextParam' because that is only used in precision, not
554 fn count(&mut self) -> Count {
555 if let Some(i) = self.integer() {
556 if self.consume('$') {
562 let tmp = self.cur.clone();
563 let word = self.word();
567 } else if self.consume('$') {
568 CountIsName(Symbol::intern(word))
576 /// Parses a word starting at the current position. A word is considered to
577 /// be an alphabetic character followed by any number of alphanumeric
579 fn word(&mut self) -> &'a str {
580 let start = match self.cur.peek() {
581 Some(&(pos, c)) if c.is_xid_start() => {
586 return &self.input[..0];
589 while let Some(&(pos, c)) = self.cur.peek() {
590 if c.is_xid_continue() {
593 return &self.input[start..pos];
596 &self.input[start..self.input.len()]
599 /// Optionally parses an integer at the current position. This doesn't deal
600 /// with overflow at all, it's just accumulating digits.
601 fn integer(&mut self) -> Option<usize> {
603 let mut found = false;
604 while let Some(&(_, c)) = self.cur.peek() {
605 if let Some(i) = c.to_digit(10) {
606 cur = cur * 10 + i as usize;
625 fn same(fmt: &'static str, p: &[Piece<'static>]) {
626 let parser = Parser::new(fmt, None, vec![], false);
627 assert!(parser.collect::<Vec<Piece<'static>>>() == p);
630 fn fmtdflt() -> FormatSpec<'static> {
635 precision: CountImplied,
641 fn musterr(s: &str) {
642 let mut p = Parser::new(s, None, vec![], false);
644 assert!(!p.errors.is_empty());
649 same("asdf", &[String("asdf")]);
650 same("a{{b", &[String("a"), String("{b")]);
651 same("a}}b", &[String("a"), String("}b")]);
652 same("a}}", &[String("a"), String("}")]);
653 same("}}", &[String("}")]);
654 same("\\}}", &[String("\\"), String("}")]);
679 fn format_nothing() {
681 &[NextArgument(Argument {
682 position: ArgumentImplicitlyIs(0),
687 fn format_position() {
689 &[NextArgument(Argument {
690 position: ArgumentIs(3),
695 fn format_position_nothing_else() {
697 &[NextArgument(Argument {
698 position: ArgumentIs(3),
705 &[NextArgument(Argument {
706 position: ArgumentIs(3),
711 precision: CountImplied,
718 fn format_align_fill() {
720 &[NextArgument(Argument {
721 position: ArgumentIs(3),
726 precision: CountImplied,
732 &[NextArgument(Argument {
733 position: ArgumentIs(3),
738 precision: CountImplied,
744 &[NextArgument(Argument {
745 position: ArgumentIs(3),
750 precision: CountImplied,
758 use syntax_pos::{GLOBALS, Globals, edition};
759 GLOBALS.set(&Globals::new(edition::DEFAULT_EDITION), || {
761 &[NextArgument(Argument {
762 position: ArgumentImplicitlyIs(0),
767 precision: CountImplied,
773 &[NextArgument(Argument {
774 position: ArgumentImplicitlyIs(0),
779 precision: CountIs(10),
780 width: CountIsParam(10),
785 &[NextArgument(Argument {
786 position: ArgumentImplicitlyIs(1),
791 precision: CountIsParam(0),
797 &[NextArgument(Argument {
798 position: ArgumentImplicitlyIs(0),
803 precision: CountIsParam(10),
809 &[NextArgument(Argument {
810 position: ArgumentImplicitlyIs(0),
815 precision: CountIsName(Symbol::intern("b")),
816 width: CountIsName(Symbol::intern("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,