]> git.lizzy.rs Git - rust.git/blob - src/libfmt_macros/lib.rs
auto merge of #15417 : pfalabella/rust/rational-signed, r=alexcrichton
[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_id = "fmt_macros#0.11.0"] // NOTE: remove after stage0c
18 #![crate_name = "fmt_macros"]
19 #![experimental]
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
25
26 use std::char;
27 use std::str;
28
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)]
32 pub enum Piece<'a> {
33     /// A literal string which should directly be emitted
34     String(&'a str),
35     /// This describes that formatting should process the next argument (as
36     /// specified inside) for emission.
37     Argument(Argument<'a>),
38 }
39
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>,
47 }
48
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
55     pub align: Alignment,
56     /// Packed version of various flags provided
57     pub flags: uint,
58     /// The integer precision to use
59     pub precision: Count<'a>,
60     /// The string width requested for the resulting format
61     pub width: Count<'a>,
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.
65     pub ty: &'a str
66 }
67
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.
72     ArgumentNext,
73     /// The argument is located at a specific index.
74     ArgumentIs(uint),
75     /// The argument has a name.
76     ArgumentNamed(&'a str),
77 }
78
79 /// Enum of alignments which are supported.
80 #[deriving(PartialEq)]
81 pub enum Alignment {
82     /// The value will be aligned to the left.
83     AlignLeft,
84     /// The value will be aligned to the right.
85     AlignRight,
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 `{}` but 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((_, '<')) => {
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         }
299         // Sign flags
300         if self.consume('+') {
301             spec.flags |= 1 << (FlagSignPlus as uint);
302         } else if self.consume('-') {
303             spec.flags |= 1 << (FlagSignMinus as uint);
304         }
305         // Alternate marker
306         if self.consume('#') {
307             spec.flags |= 1 << (FlagAlternate as uint);
308         }
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);
318                 havewidth = true;
319             } else {
320                 spec.flags |= 1 << (FlagSignAwareZeroPad as uint);
321             }
322         }
323         if !havewidth {
324             spec.width = self.count();
325         }
326         if self.consume('.') {
327             if self.consume('*') {
328                 spec.precision = CountIsNextParam;
329             } else {
330                 spec.precision = self.count();
331             }
332         }
333         // Finally the actual format specifier
334         if self.consume('?') {
335             spec.ty = "?";
336         } else {
337             spec.ty = self.word();
338         }
339         return spec;
340     }
341
342     /// Parses a Count parameter at the current position. This does not check
343     /// for 'CountIsNextParam' because that is only used in precision, not
344     /// width.
345     fn count(&mut self) -> Count<'a> {
346         match self.integer() {
347             Some(i) => {
348                 if self.consume('$') {
349                     CountIsParam(i)
350                 } else {
351                     CountIs(i)
352                 }
353             }
354             None => {
355                 let tmp = self.cur.clone();
356                 match self.word() {
357                     word if word.len() > 0 && self.consume('$') => {
358                         CountIsName(word)
359                     }
360                     _ => {
361                         self.cur = tmp;
362                         CountImplied
363                     }
364                 }
365             }
366         }
367     }
368
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
371     /// characters.
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) => {
375                 self.cur.next();
376                 pos
377             }
378             Some(..) | None => { return self.input.slice(0, 0); }
379         };
380         let mut end;
381         loop {
382             match self.cur.clone().next() {
383                 Some((_, c)) if char::is_XID_continue(c) => {
384                     self.cur.next();
385                 }
386                 Some((pos, _)) => { end = pos; break }
387                 None => { end = self.input.len(); break }
388             }
389         }
390         self.input.slice(start, end)
391     }
392
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> {
396         let mut cur = 0;
397         let mut found = false;
398         loop {
399             match self.cur.clone().next() {
400                 Some((_, c)) => {
401                     match char::to_digit(c, 10) {
402                         Some(i) => {
403                             cur = cur * 10 + i;
404                             found = true;
405                             self.cur.next();
406                         }
407                         None => { break }
408                     }
409                 }
410                 None => { break }
411             }
412         }
413         if found {
414             return Some(cur);
415         } else {
416             return None;
417         }
418     }
419 }
420
421 #[cfg(test)]
422 mod tests {
423     use super::*;
424
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());
428     }
429
430     fn fmtdflt() -> FormatSpec<'static> {
431         return FormatSpec {
432             fill: None,
433             align: AlignUnknown,
434             flags: 0,
435             precision: CountImplied,
436             width: CountImplied,
437             ty: "",
438         }
439     }
440
441     fn musterr(s: &str) {
442         let mut p = Parser::new(s);
443         p.next();
444         assert!(p.errors.len() != 0);
445     }
446
447     #[test]
448     fn simple() {
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("}")]);
455     }
456
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("{:>>>}") }
462
463     #[test]
464     fn format_nothing() {
465         same("{}", [Argument(Argument {
466             position: ArgumentNext,
467             format: fmtdflt(),
468         })]);
469     }
470     #[test]
471     fn format_position() {
472         same("{3}", [Argument(Argument {
473             position: ArgumentIs(3),
474             format: fmtdflt(),
475         })]);
476     }
477     #[test]
478     fn format_position_nothing_else() {
479         same("{3:}", [Argument(Argument {
480             position: ArgumentIs(3),
481             format: fmtdflt(),
482         })]);
483     }
484     #[test]
485     fn format_type() {
486         same("{3:a}", [Argument(Argument {
487             position: ArgumentIs(3),
488             format: FormatSpec {
489                 fill: None,
490                 align: AlignUnknown,
491                 flags: 0,
492                 precision: CountImplied,
493                 width: CountImplied,
494                 ty: "a",
495             },
496         })]);
497     }
498     #[test]
499     fn format_align_fill() {
500         same("{3:>}", [Argument(Argument {
501             position: ArgumentIs(3),
502             format: FormatSpec {
503                 fill: None,
504                 align: AlignRight,
505                 flags: 0,
506                 precision: CountImplied,
507                 width: CountImplied,
508                 ty: "",
509             },
510         })]);
511         same("{3:0<}", [Argument(Argument {
512             position: ArgumentIs(3),
513             format: FormatSpec {
514                 fill: Some('0'),
515                 align: AlignLeft,
516                 flags: 0,
517                 precision: CountImplied,
518                 width: CountImplied,
519                 ty: "",
520             },
521         })]);
522         same("{3:*<abcd}", [Argument(Argument {
523             position: ArgumentIs(3),
524             format: FormatSpec {
525                 fill: Some('*'),
526                 align: AlignLeft,
527                 flags: 0,
528                 precision: CountImplied,
529                 width: CountImplied,
530                 ty: "abcd",
531             },
532         })]);
533     }
534     #[test]
535     fn format_counts() {
536         same("{:10s}", [Argument(Argument {
537             position: ArgumentNext,
538             format: FormatSpec {
539                 fill: None,
540                 align: AlignUnknown,
541                 flags: 0,
542                 precision: CountImplied,
543                 width: CountIs(10),
544                 ty: "s",
545             },
546         })]);
547         same("{:10$.10s}", [Argument(Argument {
548             position: ArgumentNext,
549             format: FormatSpec {
550                 fill: None,
551                 align: AlignUnknown,
552                 flags: 0,
553                 precision: CountIs(10),
554                 width: CountIsParam(10),
555                 ty: "s",
556             },
557         })]);
558         same("{:.*s}", [Argument(Argument {
559             position: ArgumentNext,
560             format: FormatSpec {
561                 fill: None,
562                 align: AlignUnknown,
563                 flags: 0,
564                 precision: CountIsNextParam,
565                 width: CountImplied,
566                 ty: "s",
567             },
568         })]);
569         same("{:.10$s}", [Argument(Argument {
570             position: ArgumentNext,
571             format: FormatSpec {
572                 fill: None,
573                 align: AlignUnknown,
574                 flags: 0,
575                 precision: CountIsParam(10),
576                 width: CountImplied,
577                 ty: "s",
578             },
579         })]);
580         same("{:a$.b$s}", [Argument(Argument {
581             position: ArgumentNext,
582             format: FormatSpec {
583                 fill: None,
584                 align: AlignUnknown,
585                 flags: 0,
586                 precision: CountIsName("b"),
587                 width: CountIsName("a"),
588                 ty: "s",
589             },
590         })]);
591     }
592     #[test]
593     fn format_flags() {
594         same("{:-}", [Argument(Argument {
595             position: ArgumentNext,
596             format: FormatSpec {
597                 fill: None,
598                 align: AlignUnknown,
599                 flags: (1 << FlagSignMinus as uint),
600                 precision: CountImplied,
601                 width: CountImplied,
602                 ty: "",
603             },
604         })]);
605         same("{:+#}", [Argument(Argument {
606             position: ArgumentNext,
607             format: FormatSpec {
608                 fill: None,
609                 align: AlignUnknown,
610                 flags: (1 << FlagSignPlus as uint) | (1 << FlagAlternate as uint),
611                 precision: CountImplied,
612                 width: CountImplied,
613                 ty: "",
614             },
615         })]);
616     }
617     #[test]
618     fn format_mixture() {
619         same("abcd {3:a} efg", [String("abcd "), Argument(Argument {
620             position: ArgumentIs(3),
621             format: FormatSpec {
622                 fill: None,
623                 align: AlignUnknown,
624                 flags: 0,
625                 precision: CountImplied,
626                 width: CountImplied,
627                 ty: "a",
628             },
629         }), String(" efg")]);
630     }
631 }