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 #![crate_name = "fmt_macros"]
18 #![crate_type = "rlib"]
19 #![crate_type = "dylib"]
20 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
21 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
22 html_root_url = "https://doc.rust-lang.org/nightly/",
23 html_playground_url = "https://play.rust-lang.org/",
24 test(attr(deny(warnings))))]
27 pub use self::Piece::*;
28 pub use self::Position::*;
29 pub use self::Alignment::*;
30 pub use self::Flag::*;
31 pub use self::Count::*;
37 /// A piece is a portion of the format string which represents the next part
38 /// to emit. These are emitted as a stream by the `Parser` class.
39 #[derive(Copy, Clone, PartialEq)]
41 /// A literal string which should directly be emitted
43 /// This describes that formatting should process the next argument (as
44 /// specified inside) for emission.
45 NextArgument(Argument<'a>),
48 /// Representation of an argument specification.
49 #[derive(Copy, Clone, PartialEq)]
50 pub struct Argument<'a> {
51 /// Where to find this argument
52 pub position: Position<'a>,
53 /// How to format the argument
54 pub format: FormatSpec<'a>,
57 /// Specification for the formatting of an argument in the format string.
58 #[derive(Copy, Clone, PartialEq)]
59 pub struct FormatSpec<'a> {
60 /// Optionally specified character to fill alignment with
61 pub fill: Option<char>,
62 /// Optionally specified alignment
64 /// Packed version of various flags provided
66 /// The integer precision to use
67 pub precision: Count<'a>,
68 /// The string width requested for the resulting format
70 /// The descriptor string representing the name of the format desired for
71 /// this argument, this can be empty or any number of characters, although
72 /// it is required to be one word.
76 /// Enum describing where an argument for a format can be located.
77 #[derive(Copy, Clone, PartialEq)]
78 pub enum Position<'a> {
79 /// The argument is located at a specific index.
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,
114 /// A count is used for the precision and width parameters of an integer, and
115 /// can reference either an argument or a literal integer.
116 #[derive(Copy, Clone, PartialEq)]
118 /// The count is specified explicitly.
120 /// The count is specified by the argument with the given name.
121 CountIsName(&'a str),
122 /// The count is specified by the argument at the given index.
124 /// The count is implied and cannot be explicitly specified.
128 /// The parser structure for interpreting the input format string. This is
129 /// modeled as an iterator over `Piece` structures to form a stream of tokens
132 /// This is a recursive-descent parser for the sake of simplicity, and if
133 /// necessary there's probably lots of room for improvement performance-wise.
134 pub struct Parser<'a> {
136 cur: iter::Peekable<str::CharIndices<'a>>,
137 /// Error messages accumulated during parsing
138 pub errors: Vec<(string::String, Option<string::String>)>,
139 /// Current position of implicit positional argument pointer
143 impl<'a> Iterator for Parser<'a> {
144 type Item = Piece<'a>;
146 fn next(&mut self) -> Option<Piece<'a>> {
147 if let Some(&(pos, c)) = self.cur.peek() {
151 if self.consume('{') {
152 Some(String(self.string(pos + 1)))
154 let ret = Some(NextArgument(self.argument()));
155 self.must_consume('}');
161 if self.consume('}') {
162 Some(String(self.string(pos + 1)))
164 self.err_with_note("unmatched `}` found",
165 "if you intended to print `}`, \
166 you can escape it using `}}`");
170 _ => Some(String(self.string(pos))),
178 impl<'a> Parser<'a> {
179 /// Creates a new parser for the given format string
180 pub fn new(s: &'a str) -> Parser<'a> {
183 cur: s.char_indices().peekable(),
189 /// Notifies of an error. The message doesn't actually need to be of type
190 /// String, but I think it does when this eventually uses conditions so it
191 /// might as well start using it now.
192 fn err(&mut self, msg: &str) {
193 self.errors.push((msg.to_owned(), None));
196 /// Notifies of an error. The message doesn't actually need to be of type
197 /// String, but I think it does when this eventually uses conditions so it
198 /// might as well start using it now.
199 fn err_with_note(&mut self, msg: &str, note: &str) {
200 self.errors.push((msg.to_owned(), Some(note.to_owned())));
203 /// Optionally consumes the specified character. If the character is not at
204 /// the current position, then the current iterator isn't moved and false is
205 /// returned, otherwise the character is consumed and true is returned.
206 fn consume(&mut self, c: char) -> bool {
207 if let Some(&(_, maybe)) = self.cur.peek() {
219 /// Forces consumption of the specified character. If the character is not
220 /// found, an error is emitted.
221 fn must_consume(&mut self, c: char) {
223 if let Some(&(_, maybe)) = self.cur.peek() {
227 self.err(&format!("expected `{:?}`, found `{:?}`", c, maybe));
230 let msg = &format!("expected `{:?}` but string was terminated", c);
232 self.err_with_note(msg,
233 "if you intended to print `{`, you can escape it using `{{`");
240 /// Consumes all whitespace characters until the first non-whitespace
243 while let Some(&(_, c)) = self.cur.peek() {
244 if c.is_whitespace() {
252 /// Parses all of a string which is to be considered a "raw literal" in a
253 /// format string. This is everything outside of the braces.
254 fn string(&mut self, start: usize) -> &'a str {
255 // we may not consume the character, peek the iterator
256 while let Some(&(pos, c)) = self.cur.peek() {
259 return &self.input[start..pos];
266 &self.input[start..self.input.len()]
269 /// Parses an Argument structure, or what's contained within braces inside
270 /// the format string
271 fn argument(&mut self) -> Argument<'a> {
272 let pos = self.position();
273 let format = self.format();
275 // Resolve position after parsing format spec.
276 let pos = match pos {
277 Some(position) => position,
291 /// Parses a positional argument for a format. This could either be an
292 /// integer index of an argument, a named argument, or a blank string.
293 /// Returns `Some(parsed_position)` if the position is not implicitly
294 /// consuming a macro argument, `None` if it's the case.
295 fn position(&mut self) -> Option<Position<'a>> {
296 if let Some(i) = self.integer() {
299 match self.cur.peek() {
300 Some(&(_, c)) if c.is_alphabetic() => Some(ArgumentNamed(self.word())),
302 // This is an `ArgumentNext`.
303 // Record the fact and do the resolution after parsing the
304 // format spec, to make things like `{:.*}` work.
310 /// Parses a format specifier at the current position, returning all of the
311 /// relevant information in the FormatSpec struct.
312 fn format(&mut self) -> FormatSpec<'a> {
313 let mut spec = FormatSpec {
317 precision: CountImplied,
319 ty: &self.input[..0],
321 if !self.consume(':') {
326 if let Some(&(_, c)) = self.cur.peek() {
327 match self.cur.clone().skip(1).next() {
328 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
336 if self.consume('<') {
337 spec.align = AlignLeft;
338 } else if self.consume('>') {
339 spec.align = AlignRight;
340 } else if self.consume('^') {
341 spec.align = AlignCenter;
344 if self.consume('+') {
345 spec.flags |= 1 << (FlagSignPlus as u32);
346 } else if self.consume('-') {
347 spec.flags |= 1 << (FlagSignMinus as u32);
350 if self.consume('#') {
351 spec.flags |= 1 << (FlagAlternate as u32);
353 // Width and precision
354 let mut havewidth = false;
355 if self.consume('0') {
356 // small ambiguity with '0$' as a format string. In theory this is a
357 // '0' flag and then an ill-formatted format string with just a '$'
358 // and no count, but this is better if we instead interpret this as
359 // no '0' flag and '0$' as the width instead.
360 if self.consume('$') {
361 spec.width = CountIsParam(0);
364 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
368 spec.width = self.count();
370 if self.consume('.') {
371 if self.consume('*') {
372 // Resolve `CountIsNextParam`.
373 // We can do this immediately as `position` is resolved later.
376 spec.precision = CountIsParam(i);
378 spec.precision = self.count();
381 // Finally the actual format specifier
382 if self.consume('?') {
385 spec.ty = self.word();
390 /// Parses a Count parameter at the current position. This does not check
391 /// for 'CountIsNextParam' because that is only used in precision, not
393 fn count(&mut self) -> Count<'a> {
394 if let Some(i) = self.integer() {
395 if self.consume('$') {
401 let tmp = self.cur.clone();
402 let word = self.word();
407 if self.consume('$') {
417 /// Parses a word starting at the current position. A word is considered to
418 /// be an alphabetic character followed by any number of alphanumeric
420 fn word(&mut self) -> &'a str {
421 let start = match self.cur.peek() {
422 Some(&(pos, c)) if c.is_xid_start() => {
427 return &self.input[..0];
430 while let Some(&(pos, c)) = self.cur.peek() {
431 if c.is_xid_continue() {
434 return &self.input[start..pos];
437 &self.input[start..self.input.len()]
440 /// Optionally parses an integer at the current position. This doesn't deal
441 /// with overflow at all, it's just accumulating digits.
442 fn integer(&mut self) -> Option<usize> {
444 let mut found = false;
445 while let Some(&(_, c)) = self.cur.peek() {
446 if let Some(i) = c.to_digit(10) {
447 cur = cur * 10 + i as usize;
466 fn same(fmt: &'static str, p: &[Piece<'static>]) {
467 let parser = Parser::new(fmt);
468 assert!(parser.collect::<Vec<Piece<'static>>>() == p);
471 fn fmtdflt() -> FormatSpec<'static> {
476 precision: CountImplied,
482 fn musterr(s: &str) {
483 let mut p = Parser::new(s);
485 assert!(!p.errors.is_empty());
490 same("asdf", &[String("asdf")]);
491 same("a{{b", &[String("a"), String("{b")]);
492 same("a}}b", &[String("a"), String("}b")]);
493 same("a}}", &[String("a"), String("}")]);
494 same("}}", &[String("}")]);
495 same("\\}}", &[String("\\"), String("}")]);
520 fn format_nothing() {
522 &[NextArgument(Argument {
523 position: ArgumentIs(0),
528 fn format_position() {
530 &[NextArgument(Argument {
531 position: ArgumentIs(3),
536 fn format_position_nothing_else() {
538 &[NextArgument(Argument {
539 position: ArgumentIs(3),
546 &[NextArgument(Argument {
547 position: ArgumentIs(3),
552 precision: CountImplied,
559 fn format_align_fill() {
561 &[NextArgument(Argument {
562 position: ArgumentIs(3),
567 precision: CountImplied,
573 &[NextArgument(Argument {
574 position: ArgumentIs(3),
579 precision: CountImplied,
585 &[NextArgument(Argument {
586 position: ArgumentIs(3),
591 precision: CountImplied,
600 &[NextArgument(Argument {
601 position: ArgumentIs(0),
606 precision: CountImplied,
612 &[NextArgument(Argument {
613 position: ArgumentIs(0),
618 precision: CountIs(10),
619 width: CountIsParam(10),
624 &[NextArgument(Argument {
625 position: ArgumentIs(1),
630 precision: CountIsParam(0),
636 &[NextArgument(Argument {
637 position: ArgumentIs(0),
642 precision: CountIsParam(10),
648 &[NextArgument(Argument {
649 position: ArgumentIs(0),
654 precision: CountIsName("b"),
655 width: CountIsName("a"),
663 &[NextArgument(Argument {
664 position: ArgumentIs(0),
668 flags: (1 << FlagSignMinus as u32),
669 precision: CountImplied,
675 &[NextArgument(Argument {
676 position: ArgumentIs(0),
680 flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32),
681 precision: CountImplied,
688 fn format_mixture() {
689 same("abcd {3:a} efg",
691 NextArgument(Argument {
692 position: ArgumentIs(3),
697 precision: CountImplied,