1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Macro support for format strings
13 //! These structures are used when parsing format strings for the compiler.
14 //! Parsing does not happen at runtime: structures of `std::fmt::rt` are
15 //! generated instead.
17 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
18 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
19 html_root_url = "https://doc.rust-lang.org/nightly/",
20 html_playground_url = "https://play.rust-lang.org/",
21 test(attr(deny(warnings))))]
25 pub use self::Piece::*;
26 pub use self::Position::*;
27 pub use self::Alignment::*;
28 pub use self::Flag::*;
29 pub use self::Count::*;
35 /// A piece is a portion of the format string which represents the next part
36 /// to emit. These are emitted as a stream by the `Parser` class.
37 #[derive(Copy, Clone, PartialEq)]
39 /// A literal string which should directly be emitted
41 /// This describes that formatting should process the next argument (as
42 /// specified inside) for emission.
43 NextArgument(Argument<'a>),
46 /// Representation of an argument specification.
47 #[derive(Copy, Clone, PartialEq)]
48 pub struct Argument<'a> {
49 /// Where to find this argument
50 pub position: Position<'a>,
51 /// How to format the argument
52 pub format: FormatSpec<'a>,
55 /// Specification for the formatting of an argument in the format string.
56 #[derive(Copy, Clone, PartialEq)]
57 pub struct FormatSpec<'a> {
58 /// Optionally specified character to fill alignment with
59 pub fill: Option<char>,
60 /// Optionally specified alignment
62 /// Packed version of various flags provided
64 /// The integer precision to use
65 pub precision: Count<'a>,
66 /// The string width requested for the resulting format
68 /// The descriptor string representing the name of the format desired for
69 /// this argument, this can be empty or any number of characters, although
70 /// it is required to be one word.
74 /// Enum describing where an argument for a format can be located.
75 #[derive(Copy, Clone, PartialEq)]
76 pub enum Position<'a> {
77 /// The argument is implied to be located at an index
78 ArgumentImplicitlyIs(usize),
79 /// The argument is located at a specific index given in the format
81 /// The argument has a name.
82 ArgumentNamed(&'a str),
85 /// Enum of alignments which are supported.
86 #[derive(Copy, Clone, PartialEq)]
88 /// The value will be aligned to the left.
90 /// The value will be aligned to the right.
92 /// The value will be aligned in the center.
94 /// The value will take on a default alignment.
98 /// Various flags which can be applied to format strings. The meaning of these
99 /// flags is defined by the formatters themselves.
100 #[derive(Copy, Clone, PartialEq)]
102 /// A `+` will be used to denote positive numbers.
104 /// A `-` will be used to denote negative numbers. This is the default.
106 /// An alternate form will be used for the value. In the case of numbers,
107 /// this means that the number will be prefixed with the supplied string.
109 /// For numbers, this means that the number will be padded with zeroes,
110 /// and the sign (`+` or `-`) will precede them.
111 FlagSignAwareZeroPad,
112 /// For Debug / `?`, format integers in lower-case hexadecimal.
114 /// For Debug / `?`, format integers in upper-case hexadecimal.
118 /// A count is used for the precision and width parameters of an integer, and
119 /// can reference either an argument or a literal integer.
120 #[derive(Copy, Clone, PartialEq)]
122 /// The count is specified explicitly.
124 /// The count is specified by the argument with the given name.
125 CountIsName(&'a str),
126 /// The count is specified by the argument at the given index.
128 /// The count is implied and cannot be explicitly specified.
132 pub struct ParseError {
133 pub description: string::String,
134 pub note: Option<string::String>,
135 pub label: string::String,
140 /// The parser structure for interpreting the input format string. This is
141 /// modeled as an iterator over `Piece` structures to form a stream of tokens
144 /// This is a recursive-descent parser for the sake of simplicity, and if
145 /// necessary there's probably lots of room for improvement performance-wise.
146 pub struct Parser<'a> {
148 cur: iter::Peekable<str::CharIndices<'a>>,
149 /// Error messages accumulated during parsing
150 pub errors: Vec<ParseError>,
151 /// Current position of implicit positional argument pointer
153 /// `Some(raw count)` when the string is "raw", used to position spans correctly
154 style: Option<usize>,
155 /// How many newlines have been seen in the string so far, to adjust the error spans
156 seen_newlines: usize,
157 /// Start and end byte offset of every successfully parsed argument
158 pub arg_places: Vec<(usize, usize)>,
161 impl<'a> Iterator for Parser<'a> {
162 type Item = Piece<'a>;
164 fn next(&mut self) -> Option<Piece<'a>> {
165 let raw = self.style.map(|raw| raw + self.seen_newlines).unwrap_or(0);
166 if let Some(&(pos, c)) = self.cur.peek() {
170 if self.consume('{') {
171 Some(String(self.string(pos + 1)))
173 let arg = self.argument();
174 if let Some(arg_pos) = self.must_consume('}').map(|end| {
175 (pos + raw + 1, end + raw + 2)
177 self.arg_places.push(arg_pos);
179 Some(NextArgument(arg))
184 if self.consume('}') {
185 Some(String(self.string(pos + 1)))
187 let err_pos = pos + raw + 1;
189 "unmatched `}` found",
191 "if you intended to print `}`, you can escape it using `}}`",
199 self.seen_newlines += 1;
200 Some(String(self.string(pos)))
202 _ => Some(String(self.string(pos))),
210 impl<'a> Parser<'a> {
211 /// Creates a new parser for the given format string
212 pub fn new(s: &'a str, style: Option<usize>) -> Parser<'a> {
215 cur: s.char_indices().peekable(),
224 /// Notifies of an error. The message doesn't actually need to be of type
225 /// String, but I think it does when this eventually uses conditions so it
226 /// might as well start using it now.
227 fn err<S1: Into<string::String>, S2: Into<string::String>>(
234 self.errors.push(ParseError {
235 description: description.into(),
243 /// Notifies of an error. The message doesn't actually need to be of type
244 /// String, but I think it does when this eventually uses conditions so it
245 /// might as well start using it now.
246 fn err_with_note<S1: Into<string::String>, S2: Into<string::String>, S3: Into<string::String>>(
254 self.errors.push(ParseError {
255 description: description.into(),
256 note: Some(note.into()),
263 /// Optionally consumes the specified character. If the character is not at
264 /// the current position, then the current iterator isn't moved and false is
265 /// returned, otherwise the character is consumed and true is returned.
266 fn consume(&mut self, c: char) -> bool {
267 if let Some(&(_, maybe)) = self.cur.peek() {
279 /// Forces consumption of the specified character. If the character is not
280 /// found, an error is emitted.
281 fn must_consume(&mut self, c: char) -> Option<usize> {
283 let raw = self.style.unwrap_or(0);
285 let padding = raw + self.seen_newlines;
286 if let Some(&(pos, maybe)) = self.cur.peek() {
291 let pos = pos + padding + 1;
292 self.err(format!("expected `{:?}`, found `{:?}`", c, maybe),
293 format!("expected `{}`", c),
299 let msg = format!("expected `{:?}` but string was terminated", c);
300 // point at closing `"`, unless the last char is `\n` to account for `println`
301 let pos = match self.input.chars().last() {
302 Some('\n') => self.input.len(),
303 _ => self.input.len() + 1,
306 self.err_with_note(msg,
307 format!("expected `{:?}`", c),
308 "if you intended to print `{`, you can escape it using `{{`",
312 self.err(msg, format!("expected `{:?}`", c), pos, pos);
318 /// Consumes all whitespace characters until the first non-whitespace
321 while let Some(&(_, c)) = self.cur.peek() {
322 if c.is_whitespace() {
330 /// Parses all of a string which is to be considered a "raw literal" in a
331 /// format string. This is everything outside of the braces.
332 fn string(&mut self, start: usize) -> &'a str {
333 // we may not consume the character, peek the iterator
334 while let Some(&(pos, c)) = self.cur.peek() {
337 return &self.input[start..pos];
344 &self.input[start..self.input.len()]
347 /// Parses an Argument structure, or what's contained within braces inside
348 /// the format string
349 fn argument(&mut self) -> Argument<'a> {
350 let pos = self.position();
351 let format = self.format();
353 // Resolve position after parsing format spec.
354 let pos = match pos {
355 Some(position) => position,
359 ArgumentImplicitlyIs(i)
369 /// Parses a positional argument for a format. This could either be an
370 /// integer index of an argument, a named argument, or a blank string.
371 /// Returns `Some(parsed_position)` if the position is not implicitly
372 /// consuming a macro argument, `None` if it's the case.
373 fn position(&mut self) -> Option<Position<'a>> {
374 if let Some(i) = self.integer() {
377 match self.cur.peek() {
378 Some(&(_, c)) if c.is_alphabetic() => Some(ArgumentNamed(self.word())),
379 Some(&(pos, c)) if c == '_' => {
380 let invalid_name = self.string(pos);
381 self.err_with_note(format!("invalid argument name `{}`", invalid_name),
382 "invalid argument name",
383 "argument names cannot start with an underscore",
384 pos + 1, // add 1 to account for leading `{`
385 pos + 1 + invalid_name.len());
386 Some(ArgumentNamed(invalid_name))
389 // This is an `ArgumentNext`.
390 // Record the fact and do the resolution after parsing the
391 // format spec, to make things like `{:.*}` work.
397 /// Parses a format specifier at the current position, returning all of the
398 /// relevant information in the FormatSpec struct.
399 fn format(&mut self) -> FormatSpec<'a> {
400 let mut spec = FormatSpec {
404 precision: CountImplied,
406 ty: &self.input[..0],
408 if !self.consume(':') {
413 if let Some(&(_, c)) = self.cur.peek() {
414 match self.cur.clone().nth(1) {
415 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
423 if self.consume('<') {
424 spec.align = AlignLeft;
425 } else if self.consume('>') {
426 spec.align = AlignRight;
427 } else if self.consume('^') {
428 spec.align = AlignCenter;
431 if self.consume('+') {
432 spec.flags |= 1 << (FlagSignPlus as u32);
433 } else if self.consume('-') {
434 spec.flags |= 1 << (FlagSignMinus as u32);
437 if self.consume('#') {
438 spec.flags |= 1 << (FlagAlternate as u32);
440 // Width and precision
441 let mut havewidth = false;
442 if self.consume('0') {
443 // small ambiguity with '0$' as a format string. In theory this is a
444 // '0' flag and then an ill-formatted format string with just a '$'
445 // and no count, but this is better if we instead interpret this as
446 // no '0' flag and '0$' as the width instead.
447 if self.consume('$') {
448 spec.width = CountIsParam(0);
451 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
455 spec.width = self.count();
457 if self.consume('.') {
458 if self.consume('*') {
459 // Resolve `CountIsNextParam`.
460 // We can do this immediately as `position` is resolved later.
463 spec.precision = CountIsParam(i);
465 spec.precision = self.count();
468 // Optional radix followed by the actual format specifier
469 if self.consume('x') {
470 if self.consume('?') {
471 spec.flags |= 1 << (FlagDebugLowerHex as u32);
476 } else if self.consume('X') {
477 if self.consume('?') {
478 spec.flags |= 1 << (FlagDebugUpperHex as u32);
483 } else if self.consume('?') {
486 spec.ty = self.word();
491 /// Parses a Count parameter at the current position. This does not check
492 /// for 'CountIsNextParam' because that is only used in precision, not
494 fn count(&mut self) -> Count<'a> {
495 if let Some(i) = self.integer() {
496 if self.consume('$') {
502 let tmp = self.cur.clone();
503 let word = self.word();
507 } else if self.consume('$') {
516 /// Parses a word starting at the current position. A word is considered to
517 /// be an alphabetic character followed by any number of alphanumeric
519 fn word(&mut self) -> &'a str {
520 let start = match self.cur.peek() {
521 Some(&(pos, c)) if c.is_xid_start() => {
526 return &self.input[..0];
529 while let Some(&(pos, c)) = self.cur.peek() {
530 if c.is_xid_continue() {
533 return &self.input[start..pos];
536 &self.input[start..self.input.len()]
539 /// Optionally parses an integer at the current position. This doesn't deal
540 /// with overflow at all, it's just accumulating digits.
541 fn integer(&mut self) -> Option<usize> {
543 let mut found = false;
544 while let Some(&(_, c)) = self.cur.peek() {
545 if let Some(i) = c.to_digit(10) {
546 cur = cur * 10 + i as usize;
565 fn same(fmt: &'static str, p: &[Piece<'static>]) {
566 let parser = Parser::new(fmt, None);
567 assert!(parser.collect::<Vec<Piece<'static>>>() == p);
570 fn fmtdflt() -> FormatSpec<'static> {
575 precision: CountImplied,
581 fn musterr(s: &str) {
582 let mut p = Parser::new(s, None);
584 assert!(!p.errors.is_empty());
589 same("asdf", &[String("asdf")]);
590 same("a{{b", &[String("a"), String("{b")]);
591 same("a}}b", &[String("a"), String("}b")]);
592 same("a}}", &[String("a"), String("}")]);
593 same("}}", &[String("}")]);
594 same("\\}}", &[String("\\"), String("}")]);
619 fn format_nothing() {
621 &[NextArgument(Argument {
622 position: ArgumentImplicitlyIs(0),
627 fn format_position() {
629 &[NextArgument(Argument {
630 position: ArgumentIs(3),
635 fn format_position_nothing_else() {
637 &[NextArgument(Argument {
638 position: ArgumentIs(3),
645 &[NextArgument(Argument {
646 position: ArgumentIs(3),
651 precision: CountImplied,
658 fn format_align_fill() {
660 &[NextArgument(Argument {
661 position: ArgumentIs(3),
666 precision: CountImplied,
672 &[NextArgument(Argument {
673 position: ArgumentIs(3),
678 precision: CountImplied,
684 &[NextArgument(Argument {
685 position: ArgumentIs(3),
690 precision: CountImplied,
699 &[NextArgument(Argument {
700 position: ArgumentImplicitlyIs(0),
705 precision: CountImplied,
711 &[NextArgument(Argument {
712 position: ArgumentImplicitlyIs(0),
717 precision: CountIs(10),
718 width: CountIsParam(10),
723 &[NextArgument(Argument {
724 position: ArgumentImplicitlyIs(1),
729 precision: CountIsParam(0),
735 &[NextArgument(Argument {
736 position: ArgumentImplicitlyIs(0),
741 precision: CountIsParam(10),
747 &[NextArgument(Argument {
748 position: ArgumentImplicitlyIs(0),
753 precision: CountIsName("b"),
754 width: CountIsName("a"),
762 &[NextArgument(Argument {
763 position: ArgumentImplicitlyIs(0),
767 flags: (1 << FlagSignMinus as u32),
768 precision: CountImplied,
774 &[NextArgument(Argument {
775 position: ArgumentImplicitlyIs(0),
779 flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32),
780 precision: CountImplied,
787 fn format_mixture() {
788 same("abcd {3:a} efg",
790 NextArgument(Argument {
791 position: ArgumentIs(3),
796 precision: CountImplied,