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"]
19 #![crate_type = "rlib"]
20 #![crate_type = "dylib"]
21 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
22 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
23 html_root_url = "http://doc.rust-lang.org/nightly/",
24 html_playground_url = "http://play.rust-lang.org/")]
26 #![feature(macro_rules, globs, slicing_syntax)]
27 #![feature(associated_types)]
29 pub use self::Piece::*;
30 pub use self::Position::*;
31 pub use self::Alignment::*;
32 pub use self::Flag::*;
33 pub use self::Count::*;
38 /// A piece is a portion of the format string which represents the next part
39 /// to emit. These are emitted as a stream by the `Parser` class.
40 #[derive(Copy, PartialEq)]
42 /// A literal string which should directly be emitted
44 /// This describes that formatting should process the next argument (as
45 /// specified inside) for emission.
46 NextArgument(Argument<'a>),
49 /// Representation of an argument specification.
50 #[derive(Copy, PartialEq)]
51 pub struct Argument<'a> {
52 /// Where to find this argument
53 pub position: Position<'a>,
54 /// How to format the argument
55 pub format: FormatSpec<'a>,
58 /// Specification for the formatting of an argument in the format string.
59 #[derive(Copy, PartialEq)]
60 pub struct FormatSpec<'a> {
61 /// Optionally specified character to fill alignment with
62 pub fill: Option<char>,
63 /// Optionally specified alignment
65 /// Packed version of various flags provided
67 /// The integer precision to use
68 pub precision: Count<'a>,
69 /// The string width requested for the resulting format
71 /// The descriptor string representing the name of the format desired for
72 /// this argument, this can be empty or any number of characters, although
73 /// it is required to be one word.
77 /// Enum describing where an argument for a format can be located.
78 #[derive(Copy, PartialEq)]
79 pub enum Position<'a> {
80 /// The argument will be in the next position. This is the default.
82 /// The argument is located at a specific index.
84 /// The argument has a name.
85 ArgumentNamed(&'a str),
88 /// Enum of alignments which are supported.
89 #[derive(Copy, PartialEq)]
91 /// The value will be aligned to the left.
93 /// The value will be aligned to the right.
95 /// The value will be aligned in the center.
97 /// The value will take on a default alignment.
101 /// Various flags which can be applied to format strings. The meaning of these
102 /// flags is defined by the formatters themselves.
103 #[derive(Copy, PartialEq)]
105 /// A `+` will be used to denote positive numbers.
107 /// A `-` will be used to denote negative numbers. This is the default.
109 /// An alternate form will be used for the value. In the case of numbers,
110 /// this means that the number will be prefixed with the supplied string.
112 /// For numbers, this means that the number will be padded with zeroes,
113 /// and the sign (`+` or `-`) will precede them.
114 FlagSignAwareZeroPad,
117 /// A count is used for the precision and width parameters of an integer, and
118 /// can reference either an argument or a literal integer.
119 #[derive(Copy, PartialEq)]
121 /// The count is specified explicitly.
123 /// The count is specified by the argument with the given name.
124 CountIsName(&'a str),
125 /// The count is specified by the argument at the given index.
127 /// The count is specified by the next parameter.
129 /// The count is implied and cannot be explicitly specified.
133 /// The parser structure for interpreting the input format string. This is
134 /// modelled as an iterator over `Piece` structures to form a stream of tokens
137 /// This is a recursive-descent parser for the sake of simplicity, and if
138 /// necessary there's probably lots of room for improvement performance-wise.
139 pub struct Parser<'a> {
141 cur: str::CharIndices<'a>,
142 /// Error messages accumulated during parsing
143 pub errors: Vec<string::String>,
146 impl<'a> Iterator for Parser<'a> {
147 type Item = Piece<'a>;
149 fn next(&mut self) -> Option<Piece<'a>> {
150 match self.cur.clone().next() {
151 Some((pos, '{')) => {
153 if self.consume('{') {
154 Some(String(self.string(pos + 1)))
156 let ret = Some(NextArgument(self.argument()));
157 self.must_consume('}');
161 Some((pos, '}')) => {
163 if self.consume('}') {
164 Some(String(self.string(pos + 1)))
166 self.err("unmatched `}` found");
170 Some((pos, _)) => { Some(String(self.string(pos))) }
176 impl<'a> Parser<'a> {
177 /// Creates a new parser for the given format string
178 pub fn new(s: &'a str) -> Parser<'a> {
181 cur: s.char_indices(),
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_string());
193 /// Optionally consumes the specified character. If the character is not at
194 /// the current position, then the current iterator isn't moved and false is
195 /// returned, otherwise the character is consumed and true is returned.
196 fn consume(&mut self, c: char) -> bool {
197 match self.cur.clone().next() {
198 Some((_, maybe)) if c == maybe => {
202 Some(..) | None => false,
206 /// Forces consumption of the specified character. If the character is not
207 /// found, an error is emitted.
208 fn must_consume(&mut self, c: char) {
210 match self.cur.clone().next() {
211 Some((_, maybe)) if c == maybe => {
214 Some((_, other)) => {
215 self.err(format!("expected `{}`, found `{}`", c, other)[]);
218 self.err(format!("expected `{}` but string was terminated",
224 /// Consumes all whitespace characters until the first non-whitespace
228 match self.cur.clone().next() {
229 Some((_, c)) if c.is_whitespace() => { self.cur.next(); }
230 Some(..) | None => { return }
235 /// Parses all of a string which is to be considered a "raw literal" in a
236 /// format string. This is everything outside of the braces.
237 fn string(&mut self, start: uint) -> &'a str {
239 // we may not consume the character, so clone the iterator
240 match self.cur.clone().next() {
241 Some((pos, '}')) | Some((pos, '{')) => {
242 return self.input[start..pos];
244 Some(..) => { self.cur.next(); }
247 return self.input[start..self.input.len()];
253 /// Parses an Argument structure, or what's contained within braces inside
254 /// the format string
255 fn argument(&mut self) -> Argument<'a> {
257 position: self.position(),
258 format: self.format(),
262 /// Parses a positional argument for a format. This could either be an
263 /// integer index of an argument, a named argument, or a blank string.
264 fn position(&mut self) -> Position<'a> {
265 match self.integer() {
266 Some(i) => { ArgumentIs(i) }
268 match self.cur.clone().next() {
269 Some((_, c)) if c.is_alphabetic() => {
270 ArgumentNamed(self.word())
278 /// Parses a format specifier at the current position, returning all of the
279 /// relevant information in the FormatSpec struct.
280 fn format(&mut self) -> FormatSpec<'a> {
281 let mut spec = FormatSpec {
285 precision: CountImplied,
287 ty: self.input[0..0],
289 if !self.consume(':') { return spec }
292 match self.cur.clone().next() {
294 match self.cur.clone().skip(1).next() {
295 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
299 Some(..) | None => {}
305 if self.consume('<') {
306 spec.align = AlignLeft;
307 } else if self.consume('>') {
308 spec.align = AlignRight;
309 } else if self.consume('^') {
310 spec.align = AlignCenter;
313 if self.consume('+') {
314 spec.flags |= 1 << (FlagSignPlus as uint);
315 } else if self.consume('-') {
316 spec.flags |= 1 << (FlagSignMinus as uint);
319 if self.consume('#') {
320 spec.flags |= 1 << (FlagAlternate as uint);
322 // Width and precision
323 let mut havewidth = false;
324 if self.consume('0') {
325 // small ambiguity with '0$' as a format string. In theory this is a
326 // '0' flag and then an ill-formatted format string with just a '$'
327 // and no count, but this is better if we instead interpret this as
328 // no '0' flag and '0$' as the width instead.
329 if self.consume('$') {
330 spec.width = CountIsParam(0);
333 spec.flags |= 1 << (FlagSignAwareZeroPad as uint);
337 spec.width = self.count();
339 if self.consume('.') {
340 if self.consume('*') {
341 spec.precision = CountIsNextParam;
343 spec.precision = self.count();
346 // Finally the actual format specifier
347 if self.consume('?') {
350 spec.ty = self.word();
355 /// Parses a Count parameter at the current position. This does not check
356 /// for 'CountIsNextParam' because that is only used in precision, not
358 fn count(&mut self) -> Count<'a> {
359 match self.integer() {
361 if self.consume('$') {
368 let tmp = self.cur.clone();
370 word if word.len() > 0 => {
371 if self.consume('$') {
387 /// Parses a word starting at the current position. A word is considered to
388 /// be an alphabetic character followed by any number of alphanumeric
390 fn word(&mut self) -> &'a str {
391 let start = match self.cur.clone().next() {
392 Some((pos, c)) if c.is_xid_start() => {
396 Some(..) | None => { return self.input[0..0]; }
400 match self.cur.clone().next() {
401 Some((_, c)) if c.is_xid_continue() => {
404 Some((pos, _)) => { end = pos; break }
405 None => { end = self.input.len(); break }
408 self.input[start..end]
411 /// Optionally parses an integer at the current position. This doesn't deal
412 /// with overflow at all, it's just accumulating digits.
413 fn integer(&mut self) -> Option<uint> {
415 let mut found = false;
417 match self.cur.clone().next() {
419 match c.to_digit(10) {
443 fn same(fmt: &'static str, p: &[Piece<'static>]) {
444 let mut parser = Parser::new(fmt);
445 assert!(p == parser.collect::<Vec<Piece<'static>>>());
448 fn fmtdflt() -> FormatSpec<'static> {
453 precision: CountImplied,
459 fn musterr(s: &str) {
460 let mut p = Parser::new(s);
462 assert!(p.errors.len() != 0);
467 same("asdf", &[String("asdf")]);
468 same("a{{b", &[String("a"), String("{b")]);
469 same("a}}b", &[String("a"), String("}b")]);
470 same("a}}", &[String("a"), String("}")]);
471 same("}}", &[String("}")]);
472 same("\\}}", &[String("\\"), String("}")]);
475 #[test] fn invalid01() { musterr("{") }
476 #[test] fn invalid02() { musterr("}") }
477 #[test] fn invalid04() { musterr("{3a}") }
478 #[test] fn invalid05() { musterr("{:|}") }
479 #[test] fn invalid06() { musterr("{:>>>}") }
482 fn format_nothing() {
483 same("{}", &[NextArgument(Argument {
484 position: ArgumentNext,
489 fn format_position() {
490 same("{3}", &[NextArgument(Argument {
491 position: ArgumentIs(3),
496 fn format_position_nothing_else() {
497 same("{3:}", &[NextArgument(Argument {
498 position: ArgumentIs(3),
504 same("{3:a}", &[NextArgument(Argument {
505 position: ArgumentIs(3),
510 precision: CountImplied,
517 fn format_align_fill() {
518 same("{3:>}", &[NextArgument(Argument {
519 position: ArgumentIs(3),
524 precision: CountImplied,
529 same("{3:0<}", &[NextArgument(Argument {
530 position: ArgumentIs(3),
535 precision: CountImplied,
540 same("{3:*<abcd}", &[NextArgument(Argument {
541 position: ArgumentIs(3),
546 precision: CountImplied,
554 same("{:10s}", &[NextArgument(Argument {
555 position: ArgumentNext,
560 precision: CountImplied,
565 same("{:10$.10s}", &[NextArgument(Argument {
566 position: ArgumentNext,
571 precision: CountIs(10),
572 width: CountIsParam(10),
576 same("{:.*s}", &[NextArgument(Argument {
577 position: ArgumentNext,
582 precision: CountIsNextParam,
587 same("{:.10$s}", &[NextArgument(Argument {
588 position: ArgumentNext,
593 precision: CountIsParam(10),
598 same("{:a$.b$s}", &[NextArgument(Argument {
599 position: ArgumentNext,
604 precision: CountIsName("b"),
605 width: CountIsName("a"),
612 same("{:-}", &[NextArgument(Argument {
613 position: ArgumentNext,
617 flags: (1 << FlagSignMinus as uint),
618 precision: CountImplied,
623 same("{:+#}", &[NextArgument(Argument {
624 position: ArgumentNext,
628 flags: (1 << FlagSignPlus as uint) | (1 << FlagAlternate as uint),
629 precision: CountImplied,
636 fn format_mixture() {
637 same("abcd {3:a} efg", &[String("abcd "), NextArgument(Argument {
638 position: ArgumentIs(3),
643 precision: CountImplied,
647 }), String(" efg")]);