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))))]
24 pub use self::Piece::*;
25 pub use self::Position::*;
26 pub use self::Alignment::*;
27 pub use self::Flag::*;
28 pub use self::Count::*;
34 /// A piece is a portion of the format string which represents the next part
35 /// to emit. These are emitted as a stream by the `Parser` class.
36 #[derive(Copy, Clone, PartialEq)]
38 /// A literal string which should directly be emitted
40 /// This describes that formatting should process the next argument (as
41 /// specified inside) for emission.
42 NextArgument(Argument<'a>),
45 /// Representation of an argument specification.
46 #[derive(Copy, Clone, PartialEq)]
47 pub struct Argument<'a> {
48 /// Where to find this argument
49 pub position: Position<'a>,
50 /// How to format the argument
51 pub format: FormatSpec<'a>,
54 /// Specification for the formatting of an argument in the format string.
55 #[derive(Copy, Clone, PartialEq)]
56 pub struct FormatSpec<'a> {
57 /// Optionally specified character to fill alignment with
58 pub fill: Option<char>,
59 /// Optionally specified alignment
61 /// Packed version of various flags provided
63 /// The integer precision to use
64 pub precision: Count<'a>,
65 /// The string width requested for the resulting format
67 /// The descriptor string representing the name of the format desired for
68 /// this argument, this can be empty or any number of characters, although
69 /// it is required to be one word.
73 /// Enum describing where an argument for a format can be located.
74 #[derive(Copy, Clone, PartialEq)]
75 pub enum Position<'a> {
76 /// The argument is located at a specific index.
78 /// The argument has a name.
79 ArgumentNamed(&'a str),
82 /// Enum of alignments which are supported.
83 #[derive(Copy, Clone, PartialEq)]
85 /// The value will be aligned to the left.
87 /// The value will be aligned to the right.
89 /// The value will be aligned in the center.
91 /// The value will take on a default alignment.
95 /// Various flags which can be applied to format strings. The meaning of these
96 /// flags is defined by the formatters themselves.
97 #[derive(Copy, Clone, PartialEq)]
99 /// A `+` will be used to denote positive numbers.
101 /// A `-` will be used to denote negative numbers. This is the default.
103 /// An alternate form will be used for the value. In the case of numbers,
104 /// this means that the number will be prefixed with the supplied string.
106 /// For numbers, this means that the number will be padded with zeroes,
107 /// and the sign (`+` or `-`) will precede them.
108 FlagSignAwareZeroPad,
111 /// A count is used for the precision and width parameters of an integer, and
112 /// can reference either an argument or a literal integer.
113 #[derive(Copy, Clone, PartialEq)]
115 /// The count is specified explicitly.
117 /// The count is specified by the argument with the given name.
118 CountIsName(&'a str),
119 /// The count is specified by the argument at the given index.
121 /// The count is implied and cannot be explicitly specified.
125 /// The parser structure for interpreting the input format string. This is
126 /// modeled as an iterator over `Piece` structures to form a stream of tokens
129 /// This is a recursive-descent parser for the sake of simplicity, and if
130 /// necessary there's probably lots of room for improvement performance-wise.
131 pub struct Parser<'a> {
133 cur: iter::Peekable<str::CharIndices<'a>>,
134 /// Error messages accumulated during parsing
135 pub errors: Vec<(string::String, Option<string::String>)>,
136 /// Current position of implicit positional argument pointer
140 impl<'a> Iterator for Parser<'a> {
141 type Item = Piece<'a>;
143 fn next(&mut self) -> Option<Piece<'a>> {
144 if let Some(&(pos, c)) = self.cur.peek() {
148 if self.consume('{') {
149 Some(String(self.string(pos + 1)))
151 let ret = Some(NextArgument(self.argument()));
152 self.must_consume('}');
158 if self.consume('}') {
159 Some(String(self.string(pos + 1)))
161 self.err_with_note("unmatched `}` found",
162 "if you intended to print `}`, \
163 you can escape it using `}}`");
167 _ => Some(String(self.string(pos))),
175 impl<'a> Parser<'a> {
176 /// Creates a new parser for the given format string
177 pub fn new(s: &'a str) -> Parser<'a> {
180 cur: s.char_indices().peekable(),
186 /// Notifies of an error. The message doesn't actually need to be of type
187 /// String, but I think it does when this eventually uses conditions so it
188 /// might as well start using it now.
189 fn err(&mut self, msg: &str) {
190 self.errors.push((msg.to_owned(), None));
193 /// Notifies of an error. The message doesn't actually need to be of type
194 /// String, but I think it does when this eventually uses conditions so it
195 /// might as well start using it now.
196 fn err_with_note(&mut self, msg: &str, note: &str) {
197 self.errors.push((msg.to_owned(), Some(note.to_owned())));
200 /// Optionally consumes the specified character. If the character is not at
201 /// the current position, then the current iterator isn't moved and false is
202 /// returned, otherwise the character is consumed and true is returned.
203 fn consume(&mut self, c: char) -> bool {
204 if let Some(&(_, maybe)) = self.cur.peek() {
216 /// Forces consumption of the specified character. If the character is not
217 /// found, an error is emitted.
218 fn must_consume(&mut self, c: char) {
220 if let Some(&(_, maybe)) = self.cur.peek() {
224 self.err(&format!("expected `{:?}`, found `{:?}`", c, maybe));
227 let msg = &format!("expected `{:?}` but string was terminated", c);
229 self.err_with_note(msg,
230 "if you intended to print `{`, you can escape it using `{{`");
237 /// Consumes all whitespace characters until the first non-whitespace
240 while let Some(&(_, c)) = self.cur.peek() {
241 if c.is_whitespace() {
249 /// Parses all of a string which is to be considered a "raw literal" in a
250 /// format string. This is everything outside of the braces.
251 fn string(&mut self, start: usize) -> &'a str {
252 // we may not consume the character, peek the iterator
253 while let Some(&(pos, c)) = self.cur.peek() {
256 return &self.input[start..pos];
263 &self.input[start..self.input.len()]
266 /// Parses an Argument structure, or what's contained within braces inside
267 /// the format string
268 fn argument(&mut self) -> Argument<'a> {
269 let pos = self.position();
270 let format = self.format();
272 // Resolve position after parsing format spec.
273 let pos = match pos {
274 Some(position) => position,
288 /// Parses a positional argument for a format. This could either be an
289 /// integer index of an argument, a named argument, or a blank string.
290 /// Returns `Some(parsed_position)` if the position is not implicitly
291 /// consuming a macro argument, `None` if it's the case.
292 fn position(&mut self) -> Option<Position<'a>> {
293 if let Some(i) = self.integer() {
296 match self.cur.peek() {
297 Some(&(_, c)) if c.is_alphabetic() => Some(ArgumentNamed(self.word())),
299 // This is an `ArgumentNext`.
300 // Record the fact and do the resolution after parsing the
301 // format spec, to make things like `{:.*}` work.
307 /// Parses a format specifier at the current position, returning all of the
308 /// relevant information in the FormatSpec struct.
309 fn format(&mut self) -> FormatSpec<'a> {
310 let mut spec = FormatSpec {
314 precision: CountImplied,
316 ty: &self.input[..0],
318 if !self.consume(':') {
323 if let Some(&(_, c)) = self.cur.peek() {
324 match self.cur.clone().skip(1).next() {
325 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
333 if self.consume('<') {
334 spec.align = AlignLeft;
335 } else if self.consume('>') {
336 spec.align = AlignRight;
337 } else if self.consume('^') {
338 spec.align = AlignCenter;
341 if self.consume('+') {
342 spec.flags |= 1 << (FlagSignPlus as u32);
343 } else if self.consume('-') {
344 spec.flags |= 1 << (FlagSignMinus as u32);
347 if self.consume('#') {
348 spec.flags |= 1 << (FlagAlternate as u32);
350 // Width and precision
351 let mut havewidth = false;
352 if self.consume('0') {
353 // small ambiguity with '0$' as a format string. In theory this is a
354 // '0' flag and then an ill-formatted format string with just a '$'
355 // and no count, but this is better if we instead interpret this as
356 // no '0' flag and '0$' as the width instead.
357 if self.consume('$') {
358 spec.width = CountIsParam(0);
361 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
365 spec.width = self.count();
367 if self.consume('.') {
368 if self.consume('*') {
369 // Resolve `CountIsNextParam`.
370 // We can do this immediately as `position` is resolved later.
373 spec.precision = CountIsParam(i);
375 spec.precision = self.count();
378 // Finally the actual format specifier
379 if self.consume('?') {
382 spec.ty = self.word();
387 /// Parses a Count parameter at the current position. This does not check
388 /// for 'CountIsNextParam' because that is only used in precision, not
390 fn count(&mut self) -> Count<'a> {
391 if let Some(i) = self.integer() {
392 if self.consume('$') {
398 let tmp = self.cur.clone();
399 let word = self.word();
404 if self.consume('$') {
414 /// Parses a word starting at the current position. A word is considered to
415 /// be an alphabetic character followed by any number of alphanumeric
417 fn word(&mut self) -> &'a str {
418 let start = match self.cur.peek() {
419 Some(&(pos, c)) if c.is_xid_start() => {
424 return &self.input[..0];
427 while let Some(&(pos, c)) = self.cur.peek() {
428 if c.is_xid_continue() {
431 return &self.input[start..pos];
434 &self.input[start..self.input.len()]
437 /// Optionally parses an integer at the current position. This doesn't deal
438 /// with overflow at all, it's just accumulating digits.
439 fn integer(&mut self) -> Option<usize> {
441 let mut found = false;
442 while let Some(&(_, c)) = self.cur.peek() {
443 if let Some(i) = c.to_digit(10) {
444 cur = cur * 10 + i as usize;
463 fn same(fmt: &'static str, p: &[Piece<'static>]) {
464 let parser = Parser::new(fmt);
465 assert!(parser.collect::<Vec<Piece<'static>>>() == p);
468 fn fmtdflt() -> FormatSpec<'static> {
473 precision: CountImplied,
479 fn musterr(s: &str) {
480 let mut p = Parser::new(s);
482 assert!(!p.errors.is_empty());
487 same("asdf", &[String("asdf")]);
488 same("a{{b", &[String("a"), String("{b")]);
489 same("a}}b", &[String("a"), String("}b")]);
490 same("a}}", &[String("a"), String("}")]);
491 same("}}", &[String("}")]);
492 same("\\}}", &[String("\\"), String("}")]);
517 fn format_nothing() {
519 &[NextArgument(Argument {
520 position: ArgumentIs(0),
525 fn format_position() {
527 &[NextArgument(Argument {
528 position: ArgumentIs(3),
533 fn format_position_nothing_else() {
535 &[NextArgument(Argument {
536 position: ArgumentIs(3),
543 &[NextArgument(Argument {
544 position: ArgumentIs(3),
549 precision: CountImplied,
556 fn format_align_fill() {
558 &[NextArgument(Argument {
559 position: ArgumentIs(3),
564 precision: CountImplied,
570 &[NextArgument(Argument {
571 position: ArgumentIs(3),
576 precision: CountImplied,
582 &[NextArgument(Argument {
583 position: ArgumentIs(3),
588 precision: CountImplied,
597 &[NextArgument(Argument {
598 position: ArgumentIs(0),
603 precision: CountImplied,
609 &[NextArgument(Argument {
610 position: ArgumentIs(0),
615 precision: CountIs(10),
616 width: CountIsParam(10),
621 &[NextArgument(Argument {
622 position: ArgumentIs(1),
627 precision: CountIsParam(0),
633 &[NextArgument(Argument {
634 position: ArgumentIs(0),
639 precision: CountIsParam(10),
645 &[NextArgument(Argument {
646 position: ArgumentIs(0),
651 precision: CountIsName("b"),
652 width: CountIsName("a"),
660 &[NextArgument(Argument {
661 position: ArgumentIs(0),
665 flags: (1 << FlagSignMinus as u32),
666 precision: CountImplied,
672 &[NextArgument(Argument {
673 position: ArgumentIs(0),
677 flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32),
678 precision: CountImplied,
685 fn format_mixture() {
686 same("abcd {3:a} efg",
688 NextArgument(Argument {
689 position: ArgumentIs(3),
694 precision: CountImplied,