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 #![unstable(feature = "rustc_private")]
20 #![crate_type = "rlib"]
21 #![crate_type = "dylib"]
22 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
23 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
24 html_root_url = "http://doc.rust-lang.org/nightly/",
25 html_playground_url = "http://play.rust-lang.org/")]
28 #![feature(staged_api)]
31 pub use self::Piece::*;
32 pub use self::Position::*;
33 pub use self::Alignment::*;
34 pub use self::Flag::*;
35 pub use self::Count::*;
40 /// A piece is a portion of the format string which represents the next part
41 /// to emit. These are emitted as a stream by the `Parser` class.
42 #[derive(Copy, PartialEq)]
44 /// A literal string which should directly be emitted
46 /// This describes that formatting should process the next argument (as
47 /// specified inside) for emission.
48 NextArgument(Argument<'a>),
51 /// Representation of an argument specification.
52 #[derive(Copy, PartialEq)]
53 pub struct Argument<'a> {
54 /// Where to find this argument
55 pub position: Position<'a>,
56 /// How to format the argument
57 pub format: FormatSpec<'a>,
60 /// Specification for the formatting of an argument in the format string.
61 #[derive(Copy, PartialEq)]
62 pub struct FormatSpec<'a> {
63 /// Optionally specified character to fill alignment with
64 pub fill: Option<char>,
65 /// Optionally specified alignment
67 /// Packed version of various flags provided
69 /// The integer precision to use
70 pub precision: Count<'a>,
71 /// The string width requested for the resulting format
73 /// The descriptor string representing the name of the format desired for
74 /// this argument, this can be empty or any number of characters, although
75 /// it is required to be one word.
79 /// Enum describing where an argument for a format can be located.
80 #[derive(Copy, PartialEq)]
81 pub enum Position<'a> {
82 /// The argument will be in the next position. This is the default.
84 /// The argument is located at a specific index.
86 /// The argument has a name.
87 ArgumentNamed(&'a str),
90 /// Enum of alignments which are supported.
91 #[derive(Copy, PartialEq)]
93 /// The value will be aligned to the left.
95 /// The value will be aligned to the right.
97 /// The value will be aligned in the center.
99 /// The value will take on a default alignment.
103 /// Various flags which can be applied to format strings. The meaning of these
104 /// flags is defined by the formatters themselves.
105 #[derive(Copy, PartialEq)]
107 /// A `+` will be used to denote positive numbers.
109 /// A `-` will be used to denote negative numbers. This is the default.
111 /// An alternate form will be used for the value. In the case of numbers,
112 /// this means that the number will be prefixed with the supplied string.
114 /// For numbers, this means that the number will be padded with zeroes,
115 /// and the sign (`+` or `-`) will precede them.
116 FlagSignAwareZeroPad,
119 /// A count is used for the precision and width parameters of an integer, and
120 /// can reference either an argument or a literal integer.
121 #[derive(Copy, PartialEq)]
123 /// The count is specified explicitly.
125 /// The count is specified by the argument with the given name.
126 CountIsName(&'a str),
127 /// The count is specified by the argument at the given index.
129 /// The count is specified by the next parameter.
131 /// The count is implied and cannot be explicitly specified.
135 /// The parser structure for interpreting the input format string. This is
136 /// modelled as an iterator over `Piece` structures to form a stream of tokens
139 /// This is a recursive-descent parser for the sake of simplicity, and if
140 /// necessary there's probably lots of room for improvement performance-wise.
141 pub struct Parser<'a> {
143 cur: str::CharIndices<'a>,
144 /// Error messages accumulated during parsing
145 pub errors: Vec<string::String>,
148 impl<'a> Iterator for Parser<'a> {
149 type Item = Piece<'a>;
151 fn next(&mut self) -> Option<Piece<'a>> {
152 match self.cur.clone().next() {
153 Some((pos, '{')) => {
155 if self.consume('{') {
156 Some(String(self.string(pos + 1)))
158 let ret = Some(NextArgument(self.argument()));
159 self.must_consume('}');
163 Some((pos, '}')) => {
165 if self.consume('}') {
166 Some(String(self.string(pos + 1)))
168 self.err("unmatched `}` found");
172 Some((pos, _)) => { 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(),
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_string());
195 /// Optionally consumes the specified character. If the character is not at
196 /// the current position, then the current iterator isn't moved and false is
197 /// returned, otherwise the character is consumed and true is returned.
198 fn consume(&mut self, c: char) -> bool {
199 match self.cur.clone().next() {
200 Some((_, maybe)) if c == maybe => {
204 Some(..) | None => false,
208 /// Forces consumption of the specified character. If the character is not
209 /// found, an error is emitted.
210 fn must_consume(&mut self, c: char) {
212 match self.cur.clone().next() {
213 Some((_, maybe)) if c == maybe => {
216 Some((_, other)) => {
217 self.err(&format!("expected `{:?}`, found `{:?}`", c,
221 self.err(&format!("expected `{:?}` but string was terminated",
227 /// Consumes all whitespace characters until the first non-whitespace
231 match self.cur.clone().next() {
232 Some((_, c)) if c.is_whitespace() => { self.cur.next(); }
233 Some(..) | None => { return }
238 /// Parses all of a string which is to be considered a "raw literal" in a
239 /// format string. This is everything outside of the braces.
240 fn string(&mut self, start: uint) -> &'a str {
242 // we may not consume the character, so clone the iterator
243 match self.cur.clone().next() {
244 Some((pos, '}')) | Some((pos, '{')) => {
245 return &self.input[start..pos];
247 Some(..) => { self.cur.next(); }
250 return &self.input[start..self.input.len()];
256 /// Parses an Argument structure, or what's contained within braces inside
257 /// the format string
258 fn argument(&mut self) -> Argument<'a> {
260 position: self.position(),
261 format: self.format(),
265 /// Parses a positional argument for a format. This could either be an
266 /// integer index of an argument, a named argument, or a blank string.
267 fn position(&mut self) -> Position<'a> {
268 match self.integer() {
269 Some(i) => { ArgumentIs(i) }
271 match self.cur.clone().next() {
272 Some((_, c)) if c.is_alphabetic() => {
273 ArgumentNamed(self.word())
281 /// Parses a format specifier at the current position, returning all of the
282 /// relevant information in the FormatSpec struct.
283 fn format(&mut self) -> FormatSpec<'a> {
284 let mut spec = FormatSpec {
288 precision: CountImplied,
290 ty: &self.input[..0],
292 if !self.consume(':') { return spec }
295 match self.cur.clone().next() {
297 match self.cur.clone().skip(1).next() {
298 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
302 Some(..) | None => {}
308 if self.consume('<') {
309 spec.align = AlignLeft;
310 } else if self.consume('>') {
311 spec.align = AlignRight;
312 } else if self.consume('^') {
313 spec.align = AlignCenter;
316 if self.consume('+') {
317 spec.flags |= 1 << (FlagSignPlus as uint);
318 } else if self.consume('-') {
319 spec.flags |= 1 << (FlagSignMinus as uint);
322 if self.consume('#') {
323 spec.flags |= 1 << (FlagAlternate as uint);
325 // Width and precision
326 let mut havewidth = false;
327 if self.consume('0') {
328 // small ambiguity with '0$' as a format string. In theory this is a
329 // '0' flag and then an ill-formatted format string with just a '$'
330 // and no count, but this is better if we instead interpret this as
331 // no '0' flag and '0$' as the width instead.
332 if self.consume('$') {
333 spec.width = CountIsParam(0);
336 spec.flags |= 1 << (FlagSignAwareZeroPad as uint);
340 spec.width = self.count();
342 if self.consume('.') {
343 if self.consume('*') {
344 spec.precision = CountIsNextParam;
346 spec.precision = self.count();
349 // Finally the actual format specifier
350 if self.consume('?') {
353 spec.ty = self.word();
358 /// Parses a Count parameter at the current position. This does not check
359 /// for 'CountIsNextParam' because that is only used in precision, not
361 fn count(&mut self) -> Count<'a> {
362 match self.integer() {
364 if self.consume('$') {
371 let tmp = self.cur.clone();
373 word if word.len() > 0 => {
374 if self.consume('$') {
390 /// Parses a word starting at the current position. A word is considered to
391 /// be an alphabetic character followed by any number of alphanumeric
393 fn word(&mut self) -> &'a str {
394 let start = match self.cur.clone().next() {
395 Some((pos, c)) if c.is_xid_start() => {
399 Some(..) | None => { return &self.input[..0]; }
403 match self.cur.clone().next() {
404 Some((_, c)) if c.is_xid_continue() => {
407 Some((pos, _)) => { end = pos; break }
408 None => { end = self.input.len(); break }
411 &self.input[start..end]
414 /// Optionally parses an integer at the current position. This doesn't deal
415 /// with overflow at all, it's just accumulating digits.
416 fn integer(&mut self) -> Option<uint> {
418 let mut found = false;
420 match self.cur.clone().next() {
422 match c.to_digit(10) {
424 cur = cur * 10 + i as usize;
446 fn same(fmt: &'static str, p: &[Piece<'static>]) {
447 let parser = Parser::new(fmt);
448 assert!(p == parser.collect::<Vec<Piece<'static>>>());
451 fn fmtdflt() -> FormatSpec<'static> {
456 precision: CountImplied,
462 fn musterr(s: &str) {
463 let mut p = Parser::new(s);
465 assert!(p.errors.len() != 0);
470 same("asdf", &[String("asdf")]);
471 same("a{{b", &[String("a"), String("{b")]);
472 same("a}}b", &[String("a"), String("}b")]);
473 same("a}}", &[String("a"), String("}")]);
474 same("}}", &[String("}")]);
475 same("\\}}", &[String("\\"), String("}")]);
478 #[test] fn invalid01() { musterr("{") }
479 #[test] fn invalid02() { musterr("}") }
480 #[test] fn invalid04() { musterr("{3a}") }
481 #[test] fn invalid05() { musterr("{:|}") }
482 #[test] fn invalid06() { musterr("{:>>>}") }
485 fn format_nothing() {
486 same("{}", &[NextArgument(Argument {
487 position: ArgumentNext,
492 fn format_position() {
493 same("{3}", &[NextArgument(Argument {
494 position: ArgumentIs(3),
499 fn format_position_nothing_else() {
500 same("{3:}", &[NextArgument(Argument {
501 position: ArgumentIs(3),
507 same("{3:a}", &[NextArgument(Argument {
508 position: ArgumentIs(3),
513 precision: CountImplied,
520 fn format_align_fill() {
521 same("{3:>}", &[NextArgument(Argument {
522 position: ArgumentIs(3),
527 precision: CountImplied,
532 same("{3:0<}", &[NextArgument(Argument {
533 position: ArgumentIs(3),
538 precision: CountImplied,
543 same("{3:*<abcd}", &[NextArgument(Argument {
544 position: ArgumentIs(3),
549 precision: CountImplied,
557 same("{:10s}", &[NextArgument(Argument {
558 position: ArgumentNext,
563 precision: CountImplied,
568 same("{:10$.10s}", &[NextArgument(Argument {
569 position: ArgumentNext,
574 precision: CountIs(10),
575 width: CountIsParam(10),
579 same("{:.*s}", &[NextArgument(Argument {
580 position: ArgumentNext,
585 precision: CountIsNextParam,
590 same("{:.10$s}", &[NextArgument(Argument {
591 position: ArgumentNext,
596 precision: CountIsParam(10),
601 same("{:a$.b$s}", &[NextArgument(Argument {
602 position: ArgumentNext,
607 precision: CountIsName("b"),
608 width: CountIsName("a"),
615 same("{:-}", &[NextArgument(Argument {
616 position: ArgumentNext,
620 flags: (1 << FlagSignMinus as uint),
621 precision: CountImplied,
626 same("{:+#}", &[NextArgument(Argument {
627 position: ArgumentNext,
631 flags: (1 << FlagSignPlus as uint) | (1 << FlagAlternate as uint),
632 precision: CountImplied,
639 fn format_mixture() {
640 same("abcd {3:a} efg", &[String("abcd "), NextArgument(Argument {
641 position: ArgumentIs(3),
646 precision: CountImplied,
650 }), String(" efg")]);