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"] // NOTE: remove after stage0c
18 #![crate_name = "fmt_macros"]
20 #![license = "MIT/ASL2"]
21 #![crate_type = "rlib"]
22 #![crate_type = "dylib"]
23 #![feature(macro_rules, globs)]
24 #![allow(unused_attribute)] // NOTE: remove after stage0
29 /// A piece is a portion of the format string which represents the next part
30 /// to emit. These are emitted as a stream by the `Parser` class.
31 #[deriving(PartialEq)]
33 /// A literal string which should directly be emitted
35 /// This describes that formatting should process the next argument (as
36 /// specified inside) for emission.
37 Argument(Argument<'a>),
40 /// Representation of an argument specification.
41 #[deriving(PartialEq)]
42 pub struct Argument<'a> {
43 /// Where to find this argument
44 pub position: Position<'a>,
45 /// How to format the argument
46 pub format: FormatSpec<'a>,
49 /// Specification for the formatting of an argument in the format string.
50 #[deriving(PartialEq)]
51 pub struct FormatSpec<'a> {
52 /// Optionally specified character to fill alignment with
53 pub fill: Option<char>,
54 /// Optionally specified alignment
56 /// Packed version of various flags provided
58 /// The integer precision to use
59 pub precision: Count<'a>,
60 /// The string width requested for the resulting format
62 /// The descriptor string representing the name of the format desired for
63 /// this argument, this can be empty or any number of characters, although
64 /// it is required to be one word.
68 /// Enum describing where an argument for a format can be located.
69 #[deriving(PartialEq)]
70 pub enum Position<'a> {
71 /// The argument will be in the next position. This is the default.
73 /// The argument is located at a specific index.
75 /// The argument has a name.
76 ArgumentNamed(&'a str),
79 /// Enum of alignments which are supported.
80 #[deriving(PartialEq)]
82 /// The value will be aligned to the left.
84 /// The value will be aligned to the right.
86 /// The value will take on a default alignment.
90 /// Various flags which can be applied to format strings. The meaning of these
91 /// flags is defined by the formatters themselves.
92 #[deriving(PartialEq)]
94 /// A `+` will be used to denote positive numbers.
96 /// A `-` will be used to denote negative numbers. This is the default.
98 /// An alternate form will be used for the value. In the case of numbers,
99 /// this means that the number will be prefixed with the supplied string.
101 /// For numbers, this means that the number will be padded with zeroes,
102 /// and the sign (`+` or `-`) will precede them.
103 FlagSignAwareZeroPad,
106 /// A count is used for the precision and width parameters of an integer, and
107 /// can reference either an argument or a literal integer.
108 #[deriving(PartialEq)]
110 /// The count is specified explicitly.
112 /// The count is specified by the argument with the given name.
113 CountIsName(&'a str),
114 /// The count is specified by the argument at the given index.
116 /// The count is specified by the next parameter.
118 /// The count is implied and cannot be explicitly specified.
122 /// The parser structure for interpreting the input format string. This is
123 /// modelled as an iterator over `Piece` structures to form a stream of tokens
126 /// This is a recursive-descent parser for the sake of simplicity, and if
127 /// necessary there's probably lots of room for improvement performance-wise.
128 pub struct Parser<'a> {
130 cur: str::CharOffsets<'a>,
131 /// Error messages accumulated during parsing
132 pub errors: Vec<String>,
135 impl<'a> Iterator<Piece<'a>> for Parser<'a> {
136 fn next(&mut self) -> Option<Piece<'a>> {
137 match self.cur.clone().next() {
138 Some((pos, '{')) => {
140 if self.consume('{') {
141 Some(String(self.string(pos + 1)))
143 let ret = Some(Argument(self.argument()));
144 self.must_consume('}');
148 Some((pos, '}')) => {
150 if self.consume('}') {
151 Some(String(self.string(pos + 1)))
153 self.err("unmatched `}` found");
157 Some((pos, _)) => { Some(String(self.string(pos))) }
163 impl<'a> Parser<'a> {
164 /// Creates a new parser for the given format string
165 pub fn new<'a>(s: &'a str) -> Parser<'a> {
168 cur: s.char_indices(),
173 /// Notifies of an error. The message doesn't actually need to be of type
174 /// String, but I think it does when this eventually uses conditions so it
175 /// might as well start using it now.
176 fn err(&mut self, msg: &str) {
177 self.errors.push(msg.to_string());
180 /// Optionally consumes the specified character. If the character is not at
181 /// the current position, then the current iterator isn't moved and false is
182 /// returned, otherwise the character is consumed and true is returned.
183 fn consume(&mut self, c: char) -> bool {
184 match self.cur.clone().next() {
185 Some((_, maybe)) if c == maybe => {
189 Some(..) | None => false,
193 /// Forces consumption of the specified character. If the character is not
194 /// found, an error is emitted.
195 fn must_consume(&mut self, c: char) {
197 match self.cur.clone().next() {
198 Some((_, maybe)) if c == maybe => {
201 Some((_, other)) => {
202 self.err(format!("expected `{}` but found `{}`",
207 self.err(format!("expected `{}` but string was terminated",
213 /// Consumes all whitespace characters until the first non-whitespace
217 match self.cur.clone().next() {
218 Some((_, c)) if char::is_whitespace(c) => { self.cur.next(); }
219 Some(..) | None => { return }
224 /// Parses all of a string which is to be considered a "raw literal" in a
225 /// format string. This is everything outside of the braces.
226 fn string(&mut self, start: uint) -> &'a str {
228 // we may not consume the character, so clone the iterator
229 match self.cur.clone().next() {
230 Some((pos, '}')) | Some((pos, '{')) => {
231 return self.input.slice(start, pos);
233 Some(..) => { self.cur.next(); }
236 return self.input.slice(start, self.input.len());
242 /// Parses an Argument structure, or what's contained within braces inside
243 /// the format string
244 fn argument(&mut self) -> Argument<'a> {
246 position: self.position(),
247 format: self.format(),
251 /// Parses a positional argument for a format. This could either be an
252 /// integer index of an argument, a named argument, or a blank string.
253 fn position(&mut self) -> Position<'a> {
254 match self.integer() {
255 Some(i) => { ArgumentIs(i) }
257 match self.cur.clone().next() {
258 Some((_, c)) if char::is_alphabetic(c) => {
259 ArgumentNamed(self.word())
267 /// Parses a format specifier at the current position, returning all of the
268 /// relevant information in the FormatSpec struct.
269 fn format(&mut self) -> FormatSpec<'a> {
270 let mut spec = FormatSpec {
274 precision: CountImplied,
276 ty: self.input.slice(0, 0),
278 if !self.consume(':') { return spec }
281 match self.cur.clone().next() {
283 match self.cur.clone().skip(1).next() {
284 Some((_, '>')) | Some((_, '<')) => {
288 Some(..) | None => {}
294 if self.consume('<') {
295 spec.align = AlignLeft;
296 } else if self.consume('>') {
297 spec.align = AlignRight;
300 if self.consume('+') {
301 spec.flags |= 1 << (FlagSignPlus as uint);
302 } else if self.consume('-') {
303 spec.flags |= 1 << (FlagSignMinus as uint);
306 if self.consume('#') {
307 spec.flags |= 1 << (FlagAlternate as uint);
309 // Width and precision
310 let mut havewidth = false;
311 if self.consume('0') {
312 // small ambiguity with '0$' as a format string. In theory this is a
313 // '0' flag and then an ill-formatted format string with just a '$'
314 // and no count, but this is better if we instead interpret this as
315 // no '0' flag and '0$' as the width instead.
316 if self.consume('$') {
317 spec.width = CountIsParam(0);
320 spec.flags |= 1 << (FlagSignAwareZeroPad as uint);
324 spec.width = self.count();
326 if self.consume('.') {
327 if self.consume('*') {
328 spec.precision = CountIsNextParam;
330 spec.precision = self.count();
333 // Finally the actual format specifier
334 if self.consume('?') {
337 spec.ty = self.word();
342 /// Parses a Count parameter at the current position. This does not check
343 /// for 'CountIsNextParam' because that is only used in precision, not
345 fn count(&mut self) -> Count<'a> {
346 match self.integer() {
348 if self.consume('$') {
355 let tmp = self.cur.clone();
357 word if word.len() > 0 && self.consume('$') => {
369 /// Parses a word starting at the current position. A word is considered to
370 /// be an alphabetic character followed by any number of alphanumeric
372 fn word(&mut self) -> &'a str {
373 let start = match self.cur.clone().next() {
374 Some((pos, c)) if char::is_XID_start(c) => {
378 Some(..) | None => { return self.input.slice(0, 0); }
382 match self.cur.clone().next() {
383 Some((_, c)) if char::is_XID_continue(c) => {
386 Some((pos, _)) => { end = pos; break }
387 None => { end = self.input.len(); break }
390 self.input.slice(start, end)
393 /// Optionally parses an integer at the current position. This doesn't deal
394 /// with overflow at all, it's just accumulating digits.
395 fn integer(&mut self) -> Option<uint> {
397 let mut found = false;
399 match self.cur.clone().next() {
401 match char::to_digit(c, 10) {
425 fn same(fmt: &'static str, p: &[Piece<'static>]) {
426 let mut parser = Parser::new(fmt);
427 assert!(p == parser.collect::<Vec<Piece<'static>>>().as_slice());
430 fn fmtdflt() -> FormatSpec<'static> {
435 precision: CountImplied,
441 fn musterr(s: &str) {
442 let mut p = Parser::new(s);
444 assert!(p.errors.len() != 0);
449 same("asdf", [String("asdf")]);
450 same("a{{b", [String("a"), String("{b")]);
451 same("a}}b", [String("a"), String("}b")]);
452 same("a}}", [String("a"), String("}")]);
453 same("}}", [String("}")]);
454 same("\\}}", [String("\\"), String("}")]);
457 #[test] fn invalid01() { musterr("{") }
458 #[test] fn invalid02() { musterr("}") }
459 #[test] fn invalid04() { musterr("{3a}") }
460 #[test] fn invalid05() { musterr("{:|}") }
461 #[test] fn invalid06() { musterr("{:>>>}") }
464 fn format_nothing() {
465 same("{}", [Argument(Argument {
466 position: ArgumentNext,
471 fn format_position() {
472 same("{3}", [Argument(Argument {
473 position: ArgumentIs(3),
478 fn format_position_nothing_else() {
479 same("{3:}", [Argument(Argument {
480 position: ArgumentIs(3),
486 same("{3:a}", [Argument(Argument {
487 position: ArgumentIs(3),
492 precision: CountImplied,
499 fn format_align_fill() {
500 same("{3:>}", [Argument(Argument {
501 position: ArgumentIs(3),
506 precision: CountImplied,
511 same("{3:0<}", [Argument(Argument {
512 position: ArgumentIs(3),
517 precision: CountImplied,
522 same("{3:*<abcd}", [Argument(Argument {
523 position: ArgumentIs(3),
528 precision: CountImplied,
536 same("{:10s}", [Argument(Argument {
537 position: ArgumentNext,
542 precision: CountImplied,
547 same("{:10$.10s}", [Argument(Argument {
548 position: ArgumentNext,
553 precision: CountIs(10),
554 width: CountIsParam(10),
558 same("{:.*s}", [Argument(Argument {
559 position: ArgumentNext,
564 precision: CountIsNextParam,
569 same("{:.10$s}", [Argument(Argument {
570 position: ArgumentNext,
575 precision: CountIsParam(10),
580 same("{:a$.b$s}", [Argument(Argument {
581 position: ArgumentNext,
586 precision: CountIsName("b"),
587 width: CountIsName("a"),
594 same("{:-}", [Argument(Argument {
595 position: ArgumentNext,
599 flags: (1 << FlagSignMinus as uint),
600 precision: CountImplied,
605 same("{:+#}", [Argument(Argument {
606 position: ArgumentNext,
610 flags: (1 << FlagSignPlus as uint) | (1 << FlagAlternate as uint),
611 precision: CountImplied,
618 fn format_mixture() {
619 same("abcd {3:a} efg", [String("abcd "), Argument(Argument {
620 position: ArgumentIs(3),
625 precision: CountImplied,
629 }), String(" efg")]);