]> git.lizzy.rs Git - rust.git/blob - src/libfmt_macros/lib.rs
Doc says to avoid mixing allocator instead of forbiding it
[rust.git] / src / libfmt_macros / lib.rs
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.
4 //
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.
10
11 //! Macro support for format strings
12 //!
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.
16
17 #![crate_name = "fmt_macros"]
18 #![experimental]
19 #![license = "MIT/ASL2"]
20 #![crate_type = "rlib"]
21 #![crate_type = "dylib"]
22 #![feature(macro_rules, globs, import_shadowing)]
23
24 use std::char;
25 use std::str;
26
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)]
30 pub enum Piece<'a> {
31     /// A literal string which should directly be emitted
32     String(&'a str),
33     /// This describes that formatting should process the next argument (as
34     /// specified inside) for emission.
35     Argument(Argument<'a>),
36 }
37
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>,
45 }
46
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
53     pub align: Alignment,
54     /// Packed version of various flags provided
55     pub flags: uint,
56     /// The integer precision to use
57     pub precision: Count<'a>,
58     /// The string width requested for the resulting format
59     pub width: Count<'a>,
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.
63     pub ty: &'a str
64 }
65
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.
70     ArgumentNext,
71     /// The argument is located at a specific index.
72     ArgumentIs(uint),
73     /// The argument has a name.
74     ArgumentNamed(&'a str),
75 }
76
77 /// Enum of alignments which are supported.
78 #[deriving(PartialEq)]
79 pub enum Alignment {
80     /// The value will be aligned to the left.
81     AlignLeft,
82     /// The value will be aligned to the right.
83     AlignRight,
84     /// The value will be aligned in the center.
85     AlignCenter,
86     /// The value will take on a default alignment.
87     AlignUnknown,
88 }
89
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)]
93 pub enum Flag {
94     /// A `+` will be used to denote positive numbers.
95     FlagSignPlus,
96     /// A `-` will be used to denote negative numbers. This is the default.
97     FlagSignMinus,
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.
100     FlagAlternate,
101     /// For numbers, this means that the number will be padded with zeroes,
102     /// and the sign (`+` or `-`) will precede them.
103     FlagSignAwareZeroPad,
104 }
105
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)]
109 pub enum Count<'a> {
110     /// The count is specified explicitly.
111     CountIs(uint),
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.
115     CountIsParam(uint),
116     /// The count is specified by the next parameter.
117     CountIsNextParam,
118     /// The count is implied and cannot be explicitly specified.
119     CountImplied,
120 }
121
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
124 /// being output.
125 ///
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> {
129     input: &'a str,
130     cur: str::CharOffsets<'a>,
131     /// Error messages accumulated during parsing
132     pub errors: Vec<String>,
133 }
134
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, '{')) => {
139                 self.cur.next();
140                 if self.consume('{') {
141                     Some(String(self.string(pos + 1)))
142                 } else {
143                     let ret = Some(Argument(self.argument()));
144                     self.must_consume('}');
145                     ret
146                 }
147             }
148             Some((pos, '}')) => {
149                 self.cur.next();
150                 if self.consume('}') {
151                     Some(String(self.string(pos + 1)))
152                 } else {
153                     self.err("unmatched `}` found");
154                     None
155                 }
156             }
157             Some((pos, _)) => { Some(String(self.string(pos))) }
158             None => None
159         }
160     }
161 }
162
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> {
166         Parser {
167             input: s,
168             cur: s.char_indices(),
169             errors: vec!(),
170         }
171     }
172
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());
178     }
179
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 => {
186                 self.cur.next();
187                 true
188             }
189             Some(..) | None => false,
190         }
191     }
192
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) {
196         self.ws();
197         match self.cur.clone().next() {
198             Some((_, maybe)) if c == maybe => {
199                 self.cur.next();
200             }
201             Some((_, other)) => {
202                 self.err(format!("expected `{}`, found `{}`",
203                                  c,
204                                  other).as_slice());
205             }
206             None => {
207                 self.err(format!("expected `{}` but string was terminated",
208                                  c).as_slice());
209             }
210         }
211     }
212
213     /// Consumes all whitespace characters until the first non-whitespace
214     /// character
215     fn ws(&mut self) {
216         loop {
217             match self.cur.clone().next() {
218                 Some((_, c)) if char::is_whitespace(c) => { self.cur.next(); }
219                 Some(..) | None => { return }
220             }
221         }
222     }
223
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 {
227         loop {
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);
232                 }
233                 Some(..) => { self.cur.next(); }
234                 None => {
235                     self.cur.next();
236                     return self.input.slice(start, self.input.len());
237                 }
238             }
239         }
240     }
241
242     /// Parses an Argument structure, or what's contained within braces inside
243     /// the format string
244     fn argument(&mut self) -> Argument<'a> {
245         Argument {
246             position: self.position(),
247             format: self.format(),
248         }
249     }
250
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) }
256             None => {
257                 match self.cur.clone().next() {
258                     Some((_, c)) if char::is_alphabetic(c) => {
259                         ArgumentNamed(self.word())
260                     }
261                     _ => ArgumentNext
262                 }
263             }
264         }
265     }
266
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 {
271             fill: None,
272             align: AlignUnknown,
273             flags: 0,
274             precision: CountImplied,
275             width: CountImplied,
276             ty: self.input.slice(0, 0),
277         };
278         if !self.consume(':') { return spec }
279
280         // fill character
281         match self.cur.clone().next() {
282             Some((_, c)) => {
283                 match self.cur.clone().skip(1).next() {
284                     Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
285                         spec.fill = Some(c);
286                         self.cur.next();
287                     }
288                     Some(..) | None => {}
289                 }
290             }
291             None => {}
292         }
293         // Alignment
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;
300         }
301         // Sign flags
302         if self.consume('+') {
303             spec.flags |= 1 << (FlagSignPlus as uint);
304         } else if self.consume('-') {
305             spec.flags |= 1 << (FlagSignMinus as uint);
306         }
307         // Alternate marker
308         if self.consume('#') {
309             spec.flags |= 1 << (FlagAlternate as uint);
310         }
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);
320                 havewidth = true;
321             } else {
322                 spec.flags |= 1 << (FlagSignAwareZeroPad as uint);
323             }
324         }
325         if !havewidth {
326             spec.width = self.count();
327         }
328         if self.consume('.') {
329             if self.consume('*') {
330                 spec.precision = CountIsNextParam;
331             } else {
332                 spec.precision = self.count();
333             }
334         }
335         // Finally the actual format specifier
336         if self.consume('?') {
337             spec.ty = "?";
338         } else {
339             spec.ty = self.word();
340         }
341         return spec;
342     }
343
344     /// Parses a Count parameter at the current position. This does not check
345     /// for 'CountIsNextParam' because that is only used in precision, not
346     /// width.
347     fn count(&mut self) -> Count<'a> {
348         match self.integer() {
349             Some(i) => {
350                 if self.consume('$') {
351                     CountIsParam(i)
352                 } else {
353                     CountIs(i)
354                 }
355             }
356             None => {
357                 let tmp = self.cur.clone();
358                 match self.word() {
359                     word if word.len() > 0 => {
360                         if self.consume('$') {
361                             CountIsName(word)
362                         } else {
363                             self.cur = tmp;
364                             CountImplied
365                         }
366                     }
367                     _ => {
368                         self.cur = tmp;
369                         CountImplied
370                     }
371                 }
372             }
373         }
374     }
375
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
378     /// characters.
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) => {
382                 self.cur.next();
383                 pos
384             }
385             Some(..) | None => { return self.input.slice(0, 0); }
386         };
387         let mut end;
388         loop {
389             match self.cur.clone().next() {
390                 Some((_, c)) if char::is_XID_continue(c) => {
391                     self.cur.next();
392                 }
393                 Some((pos, _)) => { end = pos; break }
394                 None => { end = self.input.len(); break }
395             }
396         }
397         self.input.slice(start, end)
398     }
399
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> {
403         let mut cur = 0;
404         let mut found = false;
405         loop {
406             match self.cur.clone().next() {
407                 Some((_, c)) => {
408                     match char::to_digit(c, 10) {
409                         Some(i) => {
410                             cur = cur * 10 + i;
411                             found = true;
412                             self.cur.next();
413                         }
414                         None => { break }
415                     }
416                 }
417                 None => { break }
418             }
419         }
420         if found {
421             return Some(cur);
422         } else {
423             return None;
424         }
425     }
426 }
427
428 #[cfg(test)]
429 mod tests {
430     use super::*;
431
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());
435     }
436
437     fn fmtdflt() -> FormatSpec<'static> {
438         return FormatSpec {
439             fill: None,
440             align: AlignUnknown,
441             flags: 0,
442             precision: CountImplied,
443             width: CountImplied,
444             ty: "",
445         }
446     }
447
448     fn musterr(s: &str) {
449         let mut p = Parser::new(s);
450         p.next();
451         assert!(p.errors.len() != 0);
452     }
453
454     #[test]
455     fn simple() {
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("}")]);
462     }
463
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("{:>>>}") }
469
470     #[test]
471     fn format_nothing() {
472         same("{}", [Argument(Argument {
473             position: ArgumentNext,
474             format: fmtdflt(),
475         })]);
476     }
477     #[test]
478     fn format_position() {
479         same("{3}", [Argument(Argument {
480             position: ArgumentIs(3),
481             format: fmtdflt(),
482         })]);
483     }
484     #[test]
485     fn format_position_nothing_else() {
486         same("{3:}", [Argument(Argument {
487             position: ArgumentIs(3),
488             format: fmtdflt(),
489         })]);
490     }
491     #[test]
492     fn format_type() {
493         same("{3:a}", [Argument(Argument {
494             position: ArgumentIs(3),
495             format: FormatSpec {
496                 fill: None,
497                 align: AlignUnknown,
498                 flags: 0,
499                 precision: CountImplied,
500                 width: CountImplied,
501                 ty: "a",
502             },
503         })]);
504     }
505     #[test]
506     fn format_align_fill() {
507         same("{3:>}", [Argument(Argument {
508             position: ArgumentIs(3),
509             format: FormatSpec {
510                 fill: None,
511                 align: AlignRight,
512                 flags: 0,
513                 precision: CountImplied,
514                 width: CountImplied,
515                 ty: "",
516             },
517         })]);
518         same("{3:0<}", [Argument(Argument {
519             position: ArgumentIs(3),
520             format: FormatSpec {
521                 fill: Some('0'),
522                 align: AlignLeft,
523                 flags: 0,
524                 precision: CountImplied,
525                 width: CountImplied,
526                 ty: "",
527             },
528         })]);
529         same("{3:*<abcd}", [Argument(Argument {
530             position: ArgumentIs(3),
531             format: FormatSpec {
532                 fill: Some('*'),
533                 align: AlignLeft,
534                 flags: 0,
535                 precision: CountImplied,
536                 width: CountImplied,
537                 ty: "abcd",
538             },
539         })]);
540     }
541     #[test]
542     fn format_counts() {
543         same("{:10s}", [Argument(Argument {
544             position: ArgumentNext,
545             format: FormatSpec {
546                 fill: None,
547                 align: AlignUnknown,
548                 flags: 0,
549                 precision: CountImplied,
550                 width: CountIs(10),
551                 ty: "s",
552             },
553         })]);
554         same("{:10$.10s}", [Argument(Argument {
555             position: ArgumentNext,
556             format: FormatSpec {
557                 fill: None,
558                 align: AlignUnknown,
559                 flags: 0,
560                 precision: CountIs(10),
561                 width: CountIsParam(10),
562                 ty: "s",
563             },
564         })]);
565         same("{:.*s}", [Argument(Argument {
566             position: ArgumentNext,
567             format: FormatSpec {
568                 fill: None,
569                 align: AlignUnknown,
570                 flags: 0,
571                 precision: CountIsNextParam,
572                 width: CountImplied,
573                 ty: "s",
574             },
575         })]);
576         same("{:.10$s}", [Argument(Argument {
577             position: ArgumentNext,
578             format: FormatSpec {
579                 fill: None,
580                 align: AlignUnknown,
581                 flags: 0,
582                 precision: CountIsParam(10),
583                 width: CountImplied,
584                 ty: "s",
585             },
586         })]);
587         same("{:a$.b$s}", [Argument(Argument {
588             position: ArgumentNext,
589             format: FormatSpec {
590                 fill: None,
591                 align: AlignUnknown,
592                 flags: 0,
593                 precision: CountIsName("b"),
594                 width: CountIsName("a"),
595                 ty: "s",
596             },
597         })]);
598     }
599     #[test]
600     fn format_flags() {
601         same("{:-}", [Argument(Argument {
602             position: ArgumentNext,
603             format: FormatSpec {
604                 fill: None,
605                 align: AlignUnknown,
606                 flags: (1 << FlagSignMinus as uint),
607                 precision: CountImplied,
608                 width: CountImplied,
609                 ty: "",
610             },
611         })]);
612         same("{:+#}", [Argument(Argument {
613             position: ArgumentNext,
614             format: FormatSpec {
615                 fill: None,
616                 align: AlignUnknown,
617                 flags: (1 << FlagSignPlus as uint) | (1 << FlagAlternate as uint),
618                 precision: CountImplied,
619                 width: CountImplied,
620                 ty: "",
621             },
622         })]);
623     }
624     #[test]
625     fn format_mixture() {
626         same("abcd {3:a} efg", [String("abcd "), Argument(Argument {
627             position: ArgumentIs(3),
628             format: FormatSpec {
629                 fill: None,
630                 align: AlignUnknown,
631                 flags: 0,
632                 precision: CountImplied,
633                 width: CountImplied,
634                 ty: "a",
635             },
636         }), String(" efg")]);
637     }
638 }