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)]
13 #![deny(unused_lifetimes)]
16 #![feature(rustc_private)]
28 use syntax_pos::{InnerSpan, Symbol};
30 #[derive(Copy, Clone)]
31 struct InnerOffset(usize);
34 fn to(self, end: InnerOffset) -> InnerSpan {
35 InnerSpan::new(self.0, end.0)
39 /// A piece is a portion of the format string which represents the next part
40 /// to emit. These are emitted as a stream by the `Parser` class.
41 #[derive(Copy, Clone, PartialEq)]
43 /// A literal string which should directly be emitted
45 /// This describes that formatting should process the next argument (as
46 /// specified inside) for emission.
47 NextArgument(Argument<'a>),
50 /// Representation of an argument specification.
51 #[derive(Copy, Clone, PartialEq)]
52 pub struct Argument<'a> {
53 /// Where to find this argument
54 pub position: Position,
55 /// How to format the argument
56 pub format: FormatSpec<'a>,
59 /// Specification for the formatting of an argument in the format string.
60 #[derive(Copy, Clone, PartialEq)]
61 pub struct FormatSpec<'a> {
62 /// Optionally specified character to fill alignment with
63 pub fill: Option<char>,
64 /// Optionally specified alignment
66 /// Packed version of various flags provided
68 /// The integer precision to use
70 /// The string width requested for the resulting format
72 /// The descriptor string representing the name of the format desired for
73 /// this argument, this can be empty or any number of characters, although
74 /// it is required to be one word.
78 /// Enum describing where an argument for a format can be located.
79 #[derive(Copy, Clone, PartialEq)]
81 /// The argument is implied to be located at an index
82 ArgumentImplicitlyIs(usize),
83 /// The argument is located at a specific index given in the format
85 /// The argument has a name.
86 ArgumentNamed(Symbol),
90 pub fn index(&self) -> Option<usize> {
92 ArgumentIs(i) | ArgumentImplicitlyIs(i) => Some(*i),
98 /// Enum of alignments which are supported.
99 #[derive(Copy, Clone, PartialEq)]
101 /// The value will be aligned to the left.
103 /// The value will be aligned to the right.
105 /// The value will be aligned in the center.
107 /// The value will take on a default alignment.
111 /// Various flags which can be applied to format strings. The meaning of these
112 /// flags is defined by the formatters themselves.
113 #[derive(Copy, Clone, PartialEq)]
115 /// A `+` will be used to denote positive numbers.
117 /// A `-` will be used to denote negative numbers. This is the default.
119 /// An alternate form will be used for the value. In the case of numbers,
120 /// this means that the number will be prefixed with the supplied string.
122 /// For numbers, this means that the number will be padded with zeroes,
123 /// and the sign (`+` or `-`) will precede them.
124 FlagSignAwareZeroPad,
125 /// For Debug / `?`, format integers in lower-case hexadecimal.
127 /// For Debug / `?`, format integers in upper-case hexadecimal.
131 /// A count is used for the precision and width parameters of an integer, and
132 /// can reference either an argument or a literal integer.
133 #[derive(Copy, Clone, PartialEq)]
135 /// The count is specified explicitly.
137 /// The count is specified by the argument with the given name.
139 /// The count is specified by the argument at the given index.
141 /// The count is implied and cannot be explicitly specified.
145 pub struct ParseError {
146 pub description: string::String,
147 pub note: Option<string::String>,
148 pub label: string::String,
150 pub secondary_label: Option<(string::String, InnerSpan)>,
153 /// The parser structure for interpreting the input format string. This is
154 /// modeled as an iterator over `Piece` structures to form a stream of tokens
157 /// This is a recursive-descent parser for the sake of simplicity, and if
158 /// necessary there's probably lots of room for improvement performance-wise.
159 pub struct Parser<'a> {
161 cur: iter::Peekable<str::CharIndices<'a>>,
162 /// Error messages accumulated during parsing
163 pub errors: Vec<ParseError>,
164 /// Current position of implicit positional argument pointer
166 /// `Some(raw count)` when the string is "raw", used to position spans correctly
167 style: Option<usize>,
168 /// Start and end byte offset of every successfully parsed argument
169 pub arg_places: Vec<InnerSpan>,
170 /// Characters that need to be shifted
172 /// Span of the last opening brace seen, used for error reporting
173 last_opening_brace: Option<InnerSpan>,
174 /// Wether the source string is comes from `println!` as opposed to `format!` or `print!`
175 append_newline: bool,
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;
186 let byte_pos = self.to_span_index(pos);
187 self.last_opening_brace = Some(byte_pos.to(InnerOffset(byte_pos.0 + 1)));
189 if self.consume('{') {
190 self.last_opening_brace = curr_last_brace;
192 Some(String(self.string(pos + 1)))
194 let arg = self.argument();
195 if let Some(end) = self.must_consume('}') {
196 let start = self.to_span_index(pos);
197 let end = self.to_span_index(end + 1);
198 self.arg_places.push(start.to(end));
200 Some(NextArgument(arg))
205 if self.consume('}') {
206 Some(String(self.string(pos + 1)))
208 let err_pos = self.to_span_index(pos);
210 "unmatched `}` found",
212 "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: 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>>(
259 self.errors.push(ParseError {
260 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>>(
278 self.errors.push(ParseError {
279 description: description.into(),
280 note: Some(note.into()),
283 secondary_label: None,
287 /// Optionally consumes the specified character. If the character is not at
288 /// the current position, then the current iterator isn't moved and false is
289 /// returned, otherwise the character is consumed and true is returned.
290 fn consume(&mut self, c: char) -> bool {
291 if let Some(&(_, maybe)) = self.cur.peek() {
303 fn to_span_index(&self, pos: usize) -> InnerOffset {
305 // This handles the raw string case, the raw argument is the number of #
306 // in r###"..."### (we need to add one because of the `r`).
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 InnerOffset(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.map(|sp| {
336 ("because of this opening brace".to_owned(), sp)
341 self.errors.push(ParseError {
351 let description = format!("expected `{:?}` but string was terminated", c);
352 // point at closing `"`
353 let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
354 let pos = self.to_span_index(pos);
356 let label = format!("expected `{:?}`", c);
357 let (note, secondary_label) = if c == '}' {
358 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
359 self.last_opening_brace.map(|sp| {
360 ("because of this opening brace".to_owned(), sp)
365 self.errors.push(ParseError {
373 self.err(description, format!("expected `{:?}`", c), pos.to(pos));
379 /// Consumes all whitespace characters until the first non-whitespace character
381 while let Some(&(_, c)) = self.cur.peek() {
382 if c.is_whitespace() {
390 /// Parses all of a string which is to be considered a "raw literal" in a
391 /// format string. This is everything outside of the braces.
392 fn string(&mut self, start: usize) -> &'a str {
393 // we may not consume the character, peek the iterator
394 while let Some(&(pos, c)) = self.cur.peek() {
397 return &self.input[start..pos];
404 &self.input[start..self.input.len()]
407 /// Parses an Argument structure, or what's contained within braces inside the format string
408 fn argument(&mut self) -> Argument<'a> {
409 let pos = self.position();
410 let format = self.format();
412 // Resolve position after parsing format spec.
413 let pos = match pos {
414 Some(position) => position,
418 ArgumentImplicitlyIs(i)
428 /// Parses a positional argument for a format. This could either be an
429 /// integer index of an argument, a named argument, or a blank string.
430 /// Returns `Some(parsed_position)` if the position is not implicitly
431 /// consuming a macro argument, `None` if it's the case.
432 fn position(&mut self) -> Option<Position> {
433 if let Some(i) = self.integer() {
436 match self.cur.peek() {
437 Some(&(_, c)) if c.is_alphabetic() => {
438 Some(ArgumentNamed(Symbol::intern(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).to(
446 self.to_span_index(pos + invalid_name.len())
449 Some(ArgumentNamed(Symbol::intern(invalid_name)))
452 // This is an `ArgumentNext`.
453 // Record the fact and do the resolution after parsing the
454 // format spec, to make things like `{:.*}` work.
460 /// Parses a format specifier at the current position, returning all of the
461 /// relevant information in the FormatSpec struct.
462 fn format(&mut self) -> FormatSpec<'a> {
463 let mut spec = FormatSpec {
467 precision: CountImplied,
469 ty: &self.input[..0],
471 if !self.consume(':') {
476 if let Some(&(_, c)) = self.cur.peek() {
477 match self.cur.clone().nth(1) {
478 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
486 if self.consume('<') {
487 spec.align = AlignLeft;
488 } else if self.consume('>') {
489 spec.align = AlignRight;
490 } else if self.consume('^') {
491 spec.align = AlignCenter;
494 if self.consume('+') {
495 spec.flags |= 1 << (FlagSignPlus as u32);
496 } else if self.consume('-') {
497 spec.flags |= 1 << (FlagSignMinus as u32);
500 if self.consume('#') {
501 spec.flags |= 1 << (FlagAlternate as u32);
503 // Width and precision
504 let mut havewidth = false;
505 if self.consume('0') {
506 // small ambiguity with '0$' as a format string. In theory this is a
507 // '0' flag and then an ill-formatted format string with just a '$'
508 // and no count, but this is better if we instead interpret this as
509 // no '0' flag and '0$' as the width instead.
510 if self.consume('$') {
511 spec.width = CountIsParam(0);
514 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
518 spec.width = self.count();
520 if self.consume('.') {
521 if self.consume('*') {
522 // Resolve `CountIsNextParam`.
523 // We can do this immediately as `position` is resolved later.
526 spec.precision = CountIsParam(i);
528 spec.precision = self.count();
531 // Optional radix followed by the actual format specifier
532 if self.consume('x') {
533 if self.consume('?') {
534 spec.flags |= 1 << (FlagDebugLowerHex as u32);
539 } else if self.consume('X') {
540 if self.consume('?') {
541 spec.flags |= 1 << (FlagDebugUpperHex as u32);
546 } else if self.consume('?') {
549 spec.ty = self.word();
554 /// Parses a Count parameter at the current position. This does not check
555 /// for 'CountIsNextParam' because that is only used in precision, not
557 fn count(&mut self) -> Count {
558 if let Some(i) = self.integer() {
559 if self.consume('$') {
565 let tmp = self.cur.clone();
566 let word = self.word();
570 } else if self.consume('$') {
571 CountIsName(Symbol::intern(word))
579 /// Parses a word starting at the current position. A word is considered to
580 /// be an alphabetic character followed by any number of alphanumeric
582 fn word(&mut self) -> &'a str {
583 let start = match self.cur.peek() {
584 Some(&(pos, c)) if c.is_xid_start() => {
589 return &self.input[..0];
592 while let Some(&(pos, c)) = self.cur.peek() {
593 if c.is_xid_continue() {
596 return &self.input[start..pos];
599 &self.input[start..self.input.len()]
602 /// Optionally parses an integer at the current position. This doesn't deal
603 /// with overflow at all, it's just accumulating digits.
604 fn integer(&mut self) -> Option<usize> {
606 let mut found = false;
607 while let Some(&(_, c)) = self.cur.peek() {
608 if let Some(i) = c.to_digit(10) {
609 cur = cur * 10 + i as usize;
628 fn same(fmt: &'static str, p: &[Piece<'static>]) {
629 let parser = Parser::new(fmt, None, vec![], false);
630 assert!(parser.collect::<Vec<Piece<'static>>>() == p);
633 fn fmtdflt() -> FormatSpec<'static> {
638 precision: CountImplied,
644 fn musterr(s: &str) {
645 let mut p = Parser::new(s, None, vec![], false);
647 assert!(!p.errors.is_empty());
652 same("asdf", &[String("asdf")]);
653 same("a{{b", &[String("a"), String("{b")]);
654 same("a}}b", &[String("a"), String("}b")]);
655 same("a}}", &[String("a"), String("}")]);
656 same("}}", &[String("}")]);
657 same("\\}}", &[String("\\"), String("}")]);
682 fn format_nothing() {
684 &[NextArgument(Argument {
685 position: ArgumentImplicitlyIs(0),
690 fn format_position() {
692 &[NextArgument(Argument {
693 position: ArgumentIs(3),
698 fn format_position_nothing_else() {
700 &[NextArgument(Argument {
701 position: ArgumentIs(3),
708 &[NextArgument(Argument {
709 position: ArgumentIs(3),
714 precision: CountImplied,
721 fn format_align_fill() {
723 &[NextArgument(Argument {
724 position: ArgumentIs(3),
729 precision: CountImplied,
735 &[NextArgument(Argument {
736 position: ArgumentIs(3),
741 precision: CountImplied,
747 &[NextArgument(Argument {
748 position: ArgumentIs(3),
753 precision: CountImplied,
761 use syntax_pos::{GLOBALS, Globals, edition};
762 GLOBALS.set(&Globals::new(edition::DEFAULT_EDITION), || {
764 &[NextArgument(Argument {
765 position: ArgumentImplicitlyIs(0),
770 precision: CountImplied,
776 &[NextArgument(Argument {
777 position: ArgumentImplicitlyIs(0),
782 precision: CountIs(10),
783 width: CountIsParam(10),
788 &[NextArgument(Argument {
789 position: ArgumentImplicitlyIs(1),
794 precision: CountIsParam(0),
800 &[NextArgument(Argument {
801 position: ArgumentImplicitlyIs(0),
806 precision: CountIsParam(10),
812 &[NextArgument(Argument {
813 position: ArgumentImplicitlyIs(0),
818 precision: CountIsName(Symbol::intern("b")),
819 width: CountIsName(Symbol::intern("a")),
828 &[NextArgument(Argument {
829 position: ArgumentImplicitlyIs(0),
833 flags: (1 << FlagSignMinus as u32),
834 precision: CountImplied,
840 &[NextArgument(Argument {
841 position: ArgumentImplicitlyIs(0),
845 flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32),
846 precision: CountImplied,
853 fn format_mixture() {
854 same("abcd {3:a} efg",
856 NextArgument(Argument {
857 position: ArgumentIs(3),
862 precision: CountImplied,