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_id = "fmt_macros#0.11.0-pre"]
18 #![license = "MIT/ASL2"]
19 #![crate_type = "rlib"]
20 #![crate_type = "dylib"]
21 #![feature(macro_rules, globs)]
27 /// A piece is a portion of the format string which represents the next part
28 /// to emit. These are emitted as a stream by the `Parser` class.
29 #[deriving(PartialEq)]
31 /// A literal string which should directly be emitted
33 /// This describes that formatting should process the next argument (as
34 /// specified inside) for emission.
35 Argument(Argument<'a>),
38 /// Representation of an argument specification.
39 #[deriving(PartialEq)]
40 pub struct Argument<'a> {
41 /// Where to find this argument
42 pub position: Position<'a>,
43 /// How to format the argument
44 pub format: FormatSpec<'a>,
47 /// Specification for the formatting of an argument in the format string.
48 #[deriving(PartialEq)]
49 pub struct FormatSpec<'a> {
50 /// Optionally specified character to fill alignment with
51 pub fill: Option<char>,
52 /// Optionally specified alignment
54 /// Packed version of various flags provided
56 /// The integer precision to use
57 pub precision: Count<'a>,
58 /// The string width requested for the resulting format
60 /// The descriptor string representing the name of the format desired for
61 /// this argument, this can be empty or any number of characters, although
62 /// it is required to be one word.
66 /// Enum describing where an argument for a format can be located.
67 #[deriving(PartialEq)]
68 pub enum Position<'a> {
69 /// The argument will be in the next position. This is the default.
71 /// The argument is located at a specific index.
73 /// The argument has a name.
74 ArgumentNamed(&'a str),
77 /// Enum of alignments which are supported.
78 #[deriving(PartialEq)]
80 /// The value will be aligned to the left.
82 /// The value will be aligned to the right.
84 /// The value will take on a default alignment.
88 /// Various flags which can be applied to format strings. The meaning of these
89 /// flags is defined by the formatters themselves.
90 #[deriving(PartialEq)]
92 /// A `+` will be used to denote positive numbers.
94 /// A `-` will be used to denote negative numbers. This is the default.
96 /// An alternate form will be used for the value. In the case of numbers,
97 /// this means that the number will be prefixed with the supplied string.
99 /// For numbers, this means that the number will be padded with zeroes,
100 /// and the sign (`+` or `-`) will precede them.
101 FlagSignAwareZeroPad,
104 /// A count is used for the precision and width parameters of an integer, and
105 /// can reference either an argument or a literal integer.
106 #[deriving(PartialEq)]
108 /// The count is specified explicitly.
110 /// The count is specified by the argument with the given name.
111 CountIsName(&'a str),
112 /// The count is specified by the argument at the given index.
114 /// The count is specified by the next parameter.
116 /// The count is implied and cannot be explicitly specified.
120 /// The parser structure for interpreting the input format string. This is
121 /// modelled as an iterator over `Piece` structures to form a stream of tokens
124 /// This is a recursive-descent parser for the sake of simplicity, and if
125 /// necessary there's probably lots of room for improvement performance-wise.
126 pub struct Parser<'a> {
128 cur: str::CharOffsets<'a>,
129 /// Error messages accumulated during parsing
130 pub errors: Vec<String>,
133 impl<'a> Iterator<Piece<'a>> for Parser<'a> {
134 fn next(&mut self) -> Option<Piece<'a>> {
135 match self.cur.clone().next() {
136 Some((pos, '{')) => {
138 if self.consume('{') {
139 Some(String(self.string(pos + 1)))
141 let ret = Some(Argument(self.argument()));
142 self.must_consume('}');
146 Some((pos, '}')) => {
148 if self.consume('}') {
149 Some(String(self.string(pos + 1)))
151 self.err("unmatched `}` found");
155 Some((pos, _)) => { Some(String(self.string(pos))) }
161 impl<'a> Parser<'a> {
162 /// Creates a new parser for the given format string
163 pub fn new<'a>(s: &'a str) -> Parser<'a> {
166 cur: s.char_indices(),
171 /// Notifies of an error. The message doesn't actually need to be of type
172 /// String, but I think it does when this eventually uses conditions so it
173 /// might as well start using it now.
174 fn err(&mut self, msg: &str) {
175 self.errors.push(msg.to_string());
178 /// Optionally consumes the specified character. If the character is not at
179 /// the current position, then the current iterator isn't moved and false is
180 /// returned, otherwise the character is consumed and true is returned.
181 fn consume(&mut self, c: char) -> bool {
182 match self.cur.clone().next() {
183 Some((_, maybe)) if c == maybe => {
187 Some(..) | None => false,
191 /// Forces consumption of the specified character. If the character is not
192 /// found, an error is emitted.
193 fn must_consume(&mut self, c: char) {
195 match self.cur.clone().next() {
196 Some((_, maybe)) if c == maybe => {
199 Some((_, other)) => {
200 self.err(format!("expected `{}` but found `{}`",
205 self.err(format!("expected `{}` but string was terminated",
211 /// Consumes all whitespace characters until the first non-whitespace
215 match self.cur.clone().next() {
216 Some((_, c)) if char::is_whitespace(c) => { self.cur.next(); }
217 Some(..) | None => { return }
222 /// Parses all of a string which is to be considered a "raw literal" in a
223 /// format string. This is everything outside of the braces.
224 fn string(&mut self, start: uint) -> &'a str {
226 // we may not consume the character, so clone the iterator
227 match self.cur.clone().next() {
228 Some((pos, '}')) | Some((pos, '{')) => {
229 return self.input.slice(start, pos);
231 Some(..) => { self.cur.next(); }
234 return self.input.slice(start, self.input.len());
240 /// Parses an Argument structure, or what's contained within braces inside
241 /// the format string
242 fn argument(&mut self) -> Argument<'a> {
244 position: self.position(),
245 format: self.format(),
249 /// Parses a positional argument for a format. This could either be an
250 /// integer index of an argument, a named argument, or a blank string.
251 fn position(&mut self) -> Position<'a> {
252 match self.integer() {
253 Some(i) => { ArgumentIs(i) }
255 match self.cur.clone().next() {
256 Some((_, c)) if char::is_alphabetic(c) => {
257 ArgumentNamed(self.word())
265 /// Parses a format specifier at the current position, returning all of the
266 /// relevant information in the FormatSpec struct.
267 fn format(&mut self) -> FormatSpec<'a> {
268 let mut spec = FormatSpec {
272 precision: CountImplied,
274 ty: self.input.slice(0, 0),
276 if !self.consume(':') { return spec }
279 match self.cur.clone().next() {
281 match self.cur.clone().skip(1).next() {
282 Some((_, '>')) | Some((_, '<')) => {
286 Some(..) | None => {}
292 if self.consume('<') {
293 spec.align = AlignLeft;
294 } else if self.consume('>') {
295 spec.align = AlignRight;
298 if self.consume('+') {
299 spec.flags |= 1 << (FlagSignPlus as uint);
300 } else if self.consume('-') {
301 spec.flags |= 1 << (FlagSignMinus as uint);
304 if self.consume('#') {
305 spec.flags |= 1 << (FlagAlternate as uint);
307 // Width and precision
308 let mut havewidth = false;
309 if self.consume('0') {
310 // small ambiguity with '0$' as a format string. In theory this is a
311 // '0' flag and then an ill-formatted format string with just a '$'
312 // and no count, but this is better if we instead interpret this as
313 // no '0' flag and '0$' as the width instead.
314 if self.consume('$') {
315 spec.width = CountIsParam(0);
318 spec.flags |= 1 << (FlagSignAwareZeroPad as uint);
322 spec.width = self.count();
324 if self.consume('.') {
325 if self.consume('*') {
326 spec.precision = CountIsNextParam;
328 spec.precision = self.count();
331 // Finally the actual format specifier
332 if self.consume('?') {
335 spec.ty = self.word();
340 /// Parses a Count parameter at the current position. This does not check
341 /// for 'CountIsNextParam' because that is only used in precision, not
343 fn count(&mut self) -> Count<'a> {
344 match self.integer() {
346 if self.consume('$') {
353 let tmp = self.cur.clone();
355 word if word.len() > 0 && self.consume('$') => {
367 /// Parses a word starting at the current position. A word is considered to
368 /// be an alphabetic character followed by any number of alphanumeric
370 fn word(&mut self) -> &'a str {
371 let start = match self.cur.clone().next() {
372 Some((pos, c)) if char::is_XID_start(c) => {
376 Some(..) | None => { return self.input.slice(0, 0); }
380 match self.cur.clone().next() {
381 Some((_, c)) if char::is_XID_continue(c) => {
384 Some((pos, _)) => { end = pos; break }
385 None => { end = self.input.len(); break }
388 self.input.slice(start, end)
391 /// Optionally parses an integer at the current position. This doesn't deal
392 /// with overflow at all, it's just accumulating digits.
393 fn integer(&mut self) -> Option<uint> {
395 let mut found = false;
397 match self.cur.clone().next() {
399 match char::to_digit(c, 10) {
423 fn same(fmt: &'static str, p: &[Piece<'static>]) {
424 let mut parser = Parser::new(fmt);
425 assert!(p == parser.collect::<Vec<Piece<'static>>>().as_slice());
428 fn fmtdflt() -> FormatSpec<'static> {
433 precision: CountImplied,
439 fn musterr(s: &str) {
440 let mut p = Parser::new(s);
442 assert!(p.errors.len() != 0);
447 same("asdf", [String("asdf")]);
448 same("a{{b", [String("a"), String("{b")]);
449 same("a}}b", [String("a"), String("}b")]);
450 same("a}}", [String("a"), String("}")]);
451 same("}}", [String("}")]);
452 same("\\}}", [String("\\"), String("}")]);
455 #[test] fn invalid01() { musterr("{") }
456 #[test] fn invalid02() { musterr("}") }
457 #[test] fn invalid04() { musterr("{3a}") }
458 #[test] fn invalid05() { musterr("{:|}") }
459 #[test] fn invalid06() { musterr("{:>>>}") }
462 fn format_nothing() {
463 same("{}", [Argument(Argument {
464 position: ArgumentNext,
469 fn format_position() {
470 same("{3}", [Argument(Argument {
471 position: ArgumentIs(3),
476 fn format_position_nothing_else() {
477 same("{3:}", [Argument(Argument {
478 position: ArgumentIs(3),
484 same("{3:a}", [Argument(Argument {
485 position: ArgumentIs(3),
490 precision: CountImplied,
497 fn format_align_fill() {
498 same("{3:>}", [Argument(Argument {
499 position: ArgumentIs(3),
504 precision: CountImplied,
509 same("{3:0<}", [Argument(Argument {
510 position: ArgumentIs(3),
515 precision: CountImplied,
520 same("{3:*<abcd}", [Argument(Argument {
521 position: ArgumentIs(3),
526 precision: CountImplied,
534 same("{:10s}", [Argument(Argument {
535 position: ArgumentNext,
540 precision: CountImplied,
545 same("{:10$.10s}", [Argument(Argument {
546 position: ArgumentNext,
551 precision: CountIs(10),
552 width: CountIsParam(10),
556 same("{:.*s}", [Argument(Argument {
557 position: ArgumentNext,
562 precision: CountIsNextParam,
567 same("{:.10$s}", [Argument(Argument {
568 position: ArgumentNext,
573 precision: CountIsParam(10),
578 same("{:a$.b$s}", [Argument(Argument {
579 position: ArgumentNext,
584 precision: CountIsName("b"),
585 width: CountIsName("a"),
592 same("{:-}", [Argument(Argument {
593 position: ArgumentNext,
597 flags: (1 << FlagSignMinus as uint),
598 precision: CountImplied,
603 same("{:+#}", [Argument(Argument {
604 position: ArgumentNext,
608 flags: (1 << FlagSignPlus as uint) | (1 << FlagAlternate as uint),
609 precision: CountImplied,
616 fn format_mixture() {
617 same("abcd {3:a} efg", [String("abcd "), Argument(Argument {
618 position: ArgumentIs(3),
623 precision: CountImplied,
627 }), String(" efg")]);