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 implied to be located at an index
77 ArgumentImplicitlyIs(usize),
78 /// The argument is located at a specific index given in the format
80 /// The argument has a name.
81 ArgumentNamed(&'a str),
84 /// Enum of alignments which are supported.
85 #[derive(Copy, Clone, PartialEq)]
87 /// The value will be aligned to the left.
89 /// The value will be aligned to the right.
91 /// The value will be aligned in the center.
93 /// The value will take on a default alignment.
97 /// Various flags which can be applied to format strings. The meaning of these
98 /// flags is defined by the formatters themselves.
99 #[derive(Copy, Clone, PartialEq)]
101 /// A `+` will be used to denote positive numbers.
103 /// A `-` will be used to denote negative numbers. This is the default.
105 /// An alternate form will be used for the value. In the case of numbers,
106 /// this means that the number will be prefixed with the supplied string.
108 /// For numbers, this means that the number will be padded with zeroes,
109 /// and the sign (`+` or `-`) will precede them.
110 FlagSignAwareZeroPad,
113 /// A count is used for the precision and width parameters of an integer, and
114 /// can reference either an argument or a literal integer.
115 #[derive(Copy, Clone, PartialEq)]
117 /// The count is specified explicitly.
119 /// The count is specified by the argument with the given name.
120 CountIsName(&'a str),
121 /// The count is specified by the argument at the given index.
123 /// The count is implied and cannot be explicitly specified.
127 /// The parser structure for interpreting the input format string. This is
128 /// modeled as an iterator over `Piece` structures to form a stream of tokens
131 /// This is a recursive-descent parser for the sake of simplicity, and if
132 /// necessary there's probably lots of room for improvement performance-wise.
133 pub struct Parser<'a> {
135 cur: iter::Peekable<str::CharIndices<'a>>,
136 /// Error messages accumulated during parsing
137 pub errors: Vec<(string::String, Option<string::String>)>,
138 /// Current position of implicit positional argument pointer
142 impl<'a> Iterator for Parser<'a> {
143 type Item = Piece<'a>;
145 fn next(&mut self) -> Option<Piece<'a>> {
146 if let Some(&(pos, c)) = self.cur.peek() {
150 if self.consume('{') {
151 Some(String(self.string(pos + 1)))
153 let ret = Some(NextArgument(self.argument()));
154 self.must_consume('}');
160 if self.consume('}') {
161 Some(String(self.string(pos + 1)))
163 self.err_with_note("unmatched `}` found",
164 "if you intended to print `}`, \
165 you can escape it using `}}`");
169 _ => Some(String(self.string(pos))),
177 impl<'a> Parser<'a> {
178 /// Creates a new parser for the given format string
179 pub fn new(s: &'a str) -> Parser<'a> {
182 cur: s.char_indices().peekable(),
188 /// Notifies of an error. The message doesn't actually need to be of type
189 /// String, but I think it does when this eventually uses conditions so it
190 /// might as well start using it now.
191 fn err(&mut self, msg: &str) {
192 self.errors.push((msg.to_owned(), None));
195 /// Notifies of an error. The message doesn't actually need to be of type
196 /// String, but I think it does when this eventually uses conditions so it
197 /// might as well start using it now.
198 fn err_with_note(&mut self, msg: &str, note: &str) {
199 self.errors.push((msg.to_owned(), Some(note.to_owned())));
202 /// Optionally consumes the specified character. If the character is not at
203 /// the current position, then the current iterator isn't moved and false is
204 /// returned, otherwise the character is consumed and true is returned.
205 fn consume(&mut self, c: char) -> bool {
206 if let Some(&(_, maybe)) = self.cur.peek() {
218 /// Forces consumption of the specified character. If the character is not
219 /// found, an error is emitted.
220 fn must_consume(&mut self, c: char) {
222 if let Some(&(_, maybe)) = self.cur.peek() {
226 self.err(&format!("expected `{:?}`, found `{:?}`", c, maybe));
229 let msg = &format!("expected `{:?}` but string was terminated", c);
231 self.err_with_note(msg,
232 "if you intended to print `{`, you can escape it using `{{`");
239 /// Consumes all whitespace characters until the first non-whitespace
242 while let Some(&(_, c)) = self.cur.peek() {
243 if c.is_whitespace() {
251 /// Parses all of a string which is to be considered a "raw literal" in a
252 /// format string. This is everything outside of the braces.
253 fn string(&mut self, start: usize) -> &'a str {
254 // we may not consume the character, peek the iterator
255 while let Some(&(pos, c)) = self.cur.peek() {
258 return &self.input[start..pos];
265 &self.input[start..self.input.len()]
268 /// Parses an Argument structure, or what's contained within braces inside
269 /// the format string
270 fn argument(&mut self) -> Argument<'a> {
271 let pos = self.position();
272 let format = self.format();
274 // Resolve position after parsing format spec.
275 let pos = match pos {
276 Some(position) => position,
280 ArgumentImplicitlyIs(i)
290 /// Parses a positional argument for a format. This could either be an
291 /// integer index of an argument, a named argument, or a blank string.
292 /// Returns `Some(parsed_position)` if the position is not implicitly
293 /// consuming a macro argument, `None` if it's the case.
294 fn position(&mut self) -> Option<Position<'a>> {
295 if let Some(i) = self.integer() {
298 match self.cur.peek() {
299 Some(&(_, c)) if c.is_alphabetic() => Some(ArgumentNamed(self.word())),
301 // This is an `ArgumentNext`.
302 // Record the fact and do the resolution after parsing the
303 // format spec, to make things like `{:.*}` work.
309 /// Parses a format specifier at the current position, returning all of the
310 /// relevant information in the FormatSpec struct.
311 fn format(&mut self) -> FormatSpec<'a> {
312 let mut spec = FormatSpec {
316 precision: CountImplied,
318 ty: &self.input[..0],
320 if !self.consume(':') {
325 if let Some(&(_, c)) = self.cur.peek() {
326 match self.cur.clone().skip(1).next() {
327 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
335 if self.consume('<') {
336 spec.align = AlignLeft;
337 } else if self.consume('>') {
338 spec.align = AlignRight;
339 } else if self.consume('^') {
340 spec.align = AlignCenter;
343 if self.consume('+') {
344 spec.flags |= 1 << (FlagSignPlus as u32);
345 } else if self.consume('-') {
346 spec.flags |= 1 << (FlagSignMinus as u32);
349 if self.consume('#') {
350 spec.flags |= 1 << (FlagAlternate as u32);
352 // Width and precision
353 let mut havewidth = false;
354 if self.consume('0') {
355 // small ambiguity with '0$' as a format string. In theory this is a
356 // '0' flag and then an ill-formatted format string with just a '$'
357 // and no count, but this is better if we instead interpret this as
358 // no '0' flag and '0$' as the width instead.
359 if self.consume('$') {
360 spec.width = CountIsParam(0);
363 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
367 spec.width = self.count();
369 if self.consume('.') {
370 if self.consume('*') {
371 // Resolve `CountIsNextParam`.
372 // We can do this immediately as `position` is resolved later.
375 spec.precision = CountIsParam(i);
377 spec.precision = self.count();
380 // Finally the actual format specifier
381 if self.consume('?') {
384 spec.ty = self.word();
389 /// Parses a Count parameter at the current position. This does not check
390 /// for 'CountIsNextParam' because that is only used in precision, not
392 fn count(&mut self) -> Count<'a> {
393 if let Some(i) = self.integer() {
394 if self.consume('$') {
400 let tmp = self.cur.clone();
401 let word = self.word();
406 if self.consume('$') {
416 /// Parses a word starting at the current position. A word is considered to
417 /// be an alphabetic character followed by any number of alphanumeric
419 fn word(&mut self) -> &'a str {
420 let start = match self.cur.peek() {
421 Some(&(pos, c)) if c.is_xid_start() => {
426 return &self.input[..0];
429 while let Some(&(pos, c)) = self.cur.peek() {
430 if c.is_xid_continue() {
433 return &self.input[start..pos];
436 &self.input[start..self.input.len()]
439 /// Optionally parses an integer at the current position. This doesn't deal
440 /// with overflow at all, it's just accumulating digits.
441 fn integer(&mut self) -> Option<usize> {
443 let mut found = false;
444 while let Some(&(_, c)) = self.cur.peek() {
445 if let Some(i) = c.to_digit(10) {
446 cur = cur * 10 + i as usize;
465 fn same(fmt: &'static str, p: &[Piece<'static>]) {
466 let parser = Parser::new(fmt);
467 assert!(parser.collect::<Vec<Piece<'static>>>() == p);
470 fn fmtdflt() -> FormatSpec<'static> {
475 precision: CountImplied,
481 fn musterr(s: &str) {
482 let mut p = Parser::new(s);
484 assert!(!p.errors.is_empty());
489 same("asdf", &[String("asdf")]);
490 same("a{{b", &[String("a"), String("{b")]);
491 same("a}}b", &[String("a"), String("}b")]);
492 same("a}}", &[String("a"), String("}")]);
493 same("}}", &[String("}")]);
494 same("\\}}", &[String("\\"), String("}")]);
519 fn format_nothing() {
521 &[NextArgument(Argument {
522 position: ArgumentImplicitlyIs(0),
527 fn format_position() {
529 &[NextArgument(Argument {
530 position: ArgumentIs(3),
535 fn format_position_nothing_else() {
537 &[NextArgument(Argument {
538 position: ArgumentIs(3),
545 &[NextArgument(Argument {
546 position: ArgumentIs(3),
551 precision: CountImplied,
558 fn format_align_fill() {
560 &[NextArgument(Argument {
561 position: ArgumentIs(3),
566 precision: CountImplied,
572 &[NextArgument(Argument {
573 position: ArgumentIs(3),
578 precision: CountImplied,
584 &[NextArgument(Argument {
585 position: ArgumentIs(3),
590 precision: CountImplied,
599 &[NextArgument(Argument {
600 position: ArgumentImplicitlyIs(0),
605 precision: CountImplied,
611 &[NextArgument(Argument {
612 position: ArgumentImplicitlyIs(0),
617 precision: CountIs(10),
618 width: CountIsParam(10),
623 &[NextArgument(Argument {
624 position: ArgumentImplicitlyIs(1),
629 precision: CountIsParam(0),
635 &[NextArgument(Argument {
636 position: ArgumentImplicitlyIs(0),
641 precision: CountIsParam(10),
647 &[NextArgument(Argument {
648 position: ArgumentImplicitlyIs(0),
653 precision: CountIsName("b"),
654 width: CountIsName("a"),
662 &[NextArgument(Argument {
663 position: ArgumentImplicitlyIs(0),
667 flags: (1 << FlagSignMinus as u32),
668 precision: CountImplied,
674 &[NextArgument(Argument {
675 position: ArgumentImplicitlyIs(0),
679 flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32),
680 precision: CountImplied,
687 fn format_mixture() {
688 same("abcd {3:a} efg",
690 NextArgument(Argument {
691 position: ArgumentIs(3),
696 precision: CountImplied,