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 #![license = "MIT/ASL2"]
20 #![crate_type = "rlib"]
21 #![crate_type = "dylib"]
22 #![feature(macro_rules, globs, import_shadowing)]
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 be aligned in the center.
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 `{}`, 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((_, '<')) | Some((_, '^')) => {
288 Some(..) | None => {}
294 if self.consume('<') {
295 spec.align = AlignLeft;
296 } else if self.consume('>') {
297 spec.align = AlignRight;
298 } else if self.consume('^') {
299 spec.align = AlignCenter;
302 if self.consume('+') {
303 spec.flags |= 1 << (FlagSignPlus as uint);
304 } else if self.consume('-') {
305 spec.flags |= 1 << (FlagSignMinus as uint);
308 if self.consume('#') {
309 spec.flags |= 1 << (FlagAlternate as uint);
311 // Width and precision
312 let mut havewidth = false;
313 if self.consume('0') {
314 // small ambiguity with '0$' as a format string. In theory this is a
315 // '0' flag and then an ill-formatted format string with just a '$'
316 // and no count, but this is better if we instead interpret this as
317 // no '0' flag and '0$' as the width instead.
318 if self.consume('$') {
319 spec.width = CountIsParam(0);
322 spec.flags |= 1 << (FlagSignAwareZeroPad as uint);
326 spec.width = self.count();
328 if self.consume('.') {
329 if self.consume('*') {
330 spec.precision = CountIsNextParam;
332 spec.precision = self.count();
335 // Finally the actual format specifier
336 if self.consume('?') {
339 spec.ty = self.word();
344 /// Parses a Count parameter at the current position. This does not check
345 /// for 'CountIsNextParam' because that is only used in precision, not
347 fn count(&mut self) -> Count<'a> {
348 match self.integer() {
350 if self.consume('$') {
357 let tmp = self.cur.clone();
359 word if word.len() > 0 => {
360 if self.consume('$') {
376 /// Parses a word starting at the current position. A word is considered to
377 /// be an alphabetic character followed by any number of alphanumeric
379 fn word(&mut self) -> &'a str {
380 let start = match self.cur.clone().next() {
381 Some((pos, c)) if char::is_XID_start(c) => {
385 Some(..) | None => { return self.input.slice(0, 0); }
389 match self.cur.clone().next() {
390 Some((_, c)) if char::is_XID_continue(c) => {
393 Some((pos, _)) => { end = pos; break }
394 None => { end = self.input.len(); break }
397 self.input.slice(start, end)
400 /// Optionally parses an integer at the current position. This doesn't deal
401 /// with overflow at all, it's just accumulating digits.
402 fn integer(&mut self) -> Option<uint> {
404 let mut found = false;
406 match self.cur.clone().next() {
408 match char::to_digit(c, 10) {
432 fn same(fmt: &'static str, p: &[Piece<'static>]) {
433 let mut parser = Parser::new(fmt);
434 assert!(p == parser.collect::<Vec<Piece<'static>>>().as_slice());
437 fn fmtdflt() -> FormatSpec<'static> {
442 precision: CountImplied,
448 fn musterr(s: &str) {
449 let mut p = Parser::new(s);
451 assert!(p.errors.len() != 0);
456 same("asdf", [String("asdf")]);
457 same("a{{b", [String("a"), String("{b")]);
458 same("a}}b", [String("a"), String("}b")]);
459 same("a}}", [String("a"), String("}")]);
460 same("}}", [String("}")]);
461 same("\\}}", [String("\\"), String("}")]);
464 #[test] fn invalid01() { musterr("{") }
465 #[test] fn invalid02() { musterr("}") }
466 #[test] fn invalid04() { musterr("{3a}") }
467 #[test] fn invalid05() { musterr("{:|}") }
468 #[test] fn invalid06() { musterr("{:>>>}") }
471 fn format_nothing() {
472 same("{}", [Argument(Argument {
473 position: ArgumentNext,
478 fn format_position() {
479 same("{3}", [Argument(Argument {
480 position: ArgumentIs(3),
485 fn format_position_nothing_else() {
486 same("{3:}", [Argument(Argument {
487 position: ArgumentIs(3),
493 same("{3:a}", [Argument(Argument {
494 position: ArgumentIs(3),
499 precision: CountImplied,
506 fn format_align_fill() {
507 same("{3:>}", [Argument(Argument {
508 position: ArgumentIs(3),
513 precision: CountImplied,
518 same("{3:0<}", [Argument(Argument {
519 position: ArgumentIs(3),
524 precision: CountImplied,
529 same("{3:*<abcd}", [Argument(Argument {
530 position: ArgumentIs(3),
535 precision: CountImplied,
543 same("{:10s}", [Argument(Argument {
544 position: ArgumentNext,
549 precision: CountImplied,
554 same("{:10$.10s}", [Argument(Argument {
555 position: ArgumentNext,
560 precision: CountIs(10),
561 width: CountIsParam(10),
565 same("{:.*s}", [Argument(Argument {
566 position: ArgumentNext,
571 precision: CountIsNextParam,
576 same("{:.10$s}", [Argument(Argument {
577 position: ArgumentNext,
582 precision: CountIsParam(10),
587 same("{:a$.b$s}", [Argument(Argument {
588 position: ArgumentNext,
593 precision: CountIsName("b"),
594 width: CountIsName("a"),
601 same("{:-}", [Argument(Argument {
602 position: ArgumentNext,
606 flags: (1 << FlagSignMinus as uint),
607 precision: CountImplied,
612 same("{:+#}", [Argument(Argument {
613 position: ArgumentNext,
617 flags: (1 << FlagSignPlus as uint) | (1 << FlagAlternate as uint),
618 precision: CountImplied,
625 fn format_mixture() {
626 same("abcd {3:a} efg", [String("abcd "), Argument(Argument {
627 position: ArgumentIs(3),
632 precision: CountImplied,
636 }), String(" efg")]);