]> git.lizzy.rs Git - rust.git/blob - src/libfmt_macros/lib.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[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 #![unstable(feature = "rustc_private")]
19 #![staged_api]
20 #![crate_type = "rlib"]
21 #![crate_type = "dylib"]
22 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
23        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
24        html_root_url = "http://doc.rust-lang.org/nightly/",
25        html_playground_url = "http://play.rust-lang.org/")]
26
27 #![feature(int_uint)]
28 #![feature(staged_api)]
29 #![feature(unicode)]
30
31 pub use self::Piece::*;
32 pub use self::Position::*;
33 pub use self::Alignment::*;
34 pub use self::Flag::*;
35 pub use self::Count::*;
36
37 use std::str;
38 use std::string;
39
40 /// A piece is a portion of the format string which represents the next part
41 /// to emit. These are emitted as a stream by the `Parser` class.
42 #[derive(Copy, PartialEq)]
43 pub enum Piece<'a> {
44     /// A literal string which should directly be emitted
45     String(&'a str),
46     /// This describes that formatting should process the next argument (as
47     /// specified inside) for emission.
48     NextArgument(Argument<'a>),
49 }
50
51 /// Representation of an argument specification.
52 #[derive(Copy, PartialEq)]
53 pub struct Argument<'a> {
54     /// Where to find this argument
55     pub position: Position<'a>,
56     /// How to format the argument
57     pub format: FormatSpec<'a>,
58 }
59
60 /// Specification for the formatting of an argument in the format string.
61 #[derive(Copy, PartialEq)]
62 pub struct FormatSpec<'a> {
63     /// Optionally specified character to fill alignment with
64     pub fill: Option<char>,
65     /// Optionally specified alignment
66     pub align: Alignment,
67     /// Packed version of various flags provided
68     pub flags: uint,
69     /// The integer precision to use
70     pub precision: Count<'a>,
71     /// The string width requested for the resulting format
72     pub width: Count<'a>,
73     /// The descriptor string representing the name of the format desired for
74     /// this argument, this can be empty or any number of characters, although
75     /// it is required to be one word.
76     pub ty: &'a str
77 }
78
79 /// Enum describing where an argument for a format can be located.
80 #[derive(Copy, PartialEq)]
81 pub enum Position<'a> {
82     /// The argument will be in the next position. This is the default.
83     ArgumentNext,
84     /// The argument is located at a specific index.
85     ArgumentIs(uint),
86     /// The argument has a name.
87     ArgumentNamed(&'a str),
88 }
89
90 /// Enum of alignments which are supported.
91 #[derive(Copy, PartialEq)]
92 pub enum Alignment {
93     /// The value will be aligned to the left.
94     AlignLeft,
95     /// The value will be aligned to the right.
96     AlignRight,
97     /// The value will be aligned in the center.
98     AlignCenter,
99     /// The value will take on a default alignment.
100     AlignUnknown,
101 }
102
103 /// Various flags which can be applied to format strings. The meaning of these
104 /// flags is defined by the formatters themselves.
105 #[derive(Copy, PartialEq)]
106 pub enum Flag {
107     /// A `+` will be used to denote positive numbers.
108     FlagSignPlus,
109     /// A `-` will be used to denote negative numbers. This is the default.
110     FlagSignMinus,
111     /// An alternate form will be used for the value. In the case of numbers,
112     /// this means that the number will be prefixed with the supplied string.
113     FlagAlternate,
114     /// For numbers, this means that the number will be padded with zeroes,
115     /// and the sign (`+` or `-`) will precede them.
116     FlagSignAwareZeroPad,
117 }
118
119 /// A count is used for the precision and width parameters of an integer, and
120 /// can reference either an argument or a literal integer.
121 #[derive(Copy, PartialEq)]
122 pub enum Count<'a> {
123     /// The count is specified explicitly.
124     CountIs(uint),
125     /// The count is specified by the argument with the given name.
126     CountIsName(&'a str),
127     /// The count is specified by the argument at the given index.
128     CountIsParam(uint),
129     /// The count is specified by the next parameter.
130     CountIsNextParam,
131     /// The count is implied and cannot be explicitly specified.
132     CountImplied,
133 }
134
135 /// The parser structure for interpreting the input format string. This is
136 /// modelled as an iterator over `Piece` structures to form a stream of tokens
137 /// being output.
138 ///
139 /// This is a recursive-descent parser for the sake of simplicity, and if
140 /// necessary there's probably lots of room for improvement performance-wise.
141 pub struct Parser<'a> {
142     input: &'a str,
143     cur: str::CharIndices<'a>,
144     /// Error messages accumulated during parsing
145     pub errors: Vec<string::String>,
146 }
147
148 impl<'a> Iterator for Parser<'a> {
149     type Item = Piece<'a>;
150
151     fn next(&mut self) -> Option<Piece<'a>> {
152         match self.cur.clone().next() {
153             Some((pos, '{')) => {
154                 self.cur.next();
155                 if self.consume('{') {
156                     Some(String(self.string(pos + 1)))
157                 } else {
158                     let ret = Some(NextArgument(self.argument()));
159                     self.must_consume('}');
160                     ret
161                 }
162             }
163             Some((pos, '}')) => {
164                 self.cur.next();
165                 if self.consume('}') {
166                     Some(String(self.string(pos + 1)))
167                 } else {
168                     self.err("unmatched `}` found");
169                     None
170                 }
171             }
172             Some((pos, _)) => { Some(String(self.string(pos))) }
173             None => None
174         }
175     }
176 }
177
178 impl<'a> Parser<'a> {
179     /// Creates a new parser for the given format string
180     pub fn new(s: &'a str) -> Parser<'a> {
181         Parser {
182             input: s,
183             cur: s.char_indices(),
184             errors: vec!(),
185         }
186     }
187
188     /// Notifies of an error. The message doesn't actually need to be of type
189     /// String, but I think it does when this eventually uses conditions so it
190     /// might as well start using it now.
191     fn err(&mut self, msg: &str) {
192         self.errors.push(msg.to_string());
193     }
194
195     /// Optionally consumes the specified character. If the character is not at
196     /// the current position, then the current iterator isn't moved and false is
197     /// returned, otherwise the character is consumed and true is returned.
198     fn consume(&mut self, c: char) -> bool {
199         match self.cur.clone().next() {
200             Some((_, maybe)) if c == maybe => {
201                 self.cur.next();
202                 true
203             }
204             Some(..) | None => false,
205         }
206     }
207
208     /// Forces consumption of the specified character. If the character is not
209     /// found, an error is emitted.
210     fn must_consume(&mut self, c: char) {
211         self.ws();
212         match self.cur.clone().next() {
213             Some((_, maybe)) if c == maybe => {
214                 self.cur.next();
215             }
216             Some((_, other)) => {
217                 self.err(&format!("expected `{:?}`, found `{:?}`", c,
218                                   other)[]);
219             }
220             None => {
221                 self.err(&format!("expected `{:?}` but string was terminated",
222                                   c)[]);
223             }
224         }
225     }
226
227     /// Consumes all whitespace characters until the first non-whitespace
228     /// character
229     fn ws(&mut self) {
230         loop {
231             match self.cur.clone().next() {
232                 Some((_, c)) if c.is_whitespace() => { self.cur.next(); }
233                 Some(..) | None => { return }
234             }
235         }
236     }
237
238     /// Parses all of a string which is to be considered a "raw literal" in a
239     /// format string. This is everything outside of the braces.
240     fn string(&mut self, start: uint) -> &'a str {
241         loop {
242             // we may not consume the character, so clone the iterator
243             match self.cur.clone().next() {
244                 Some((pos, '}')) | Some((pos, '{')) => {
245                     return &self.input[start..pos];
246                 }
247                 Some(..) => { self.cur.next(); }
248                 None => {
249                     self.cur.next();
250                     return &self.input[start..self.input.len()];
251                 }
252             }
253         }
254     }
255
256     /// Parses an Argument structure, or what's contained within braces inside
257     /// the format string
258     fn argument(&mut self) -> Argument<'a> {
259         Argument {
260             position: self.position(),
261             format: self.format(),
262         }
263     }
264
265     /// Parses a positional argument for a format. This could either be an
266     /// integer index of an argument, a named argument, or a blank string.
267     fn position(&mut self) -> Position<'a> {
268         match self.integer() {
269             Some(i) => { ArgumentIs(i) }
270             None => {
271                 match self.cur.clone().next() {
272                     Some((_, c)) if c.is_alphabetic() => {
273                         ArgumentNamed(self.word())
274                     }
275                     _ => ArgumentNext
276                 }
277             }
278         }
279     }
280
281     /// Parses a format specifier at the current position, returning all of the
282     /// relevant information in the FormatSpec struct.
283     fn format(&mut self) -> FormatSpec<'a> {
284         let mut spec = FormatSpec {
285             fill: None,
286             align: AlignUnknown,
287             flags: 0,
288             precision: CountImplied,
289             width: CountImplied,
290             ty: &self.input[..0],
291         };
292         if !self.consume(':') { return spec }
293
294         // fill character
295         match self.cur.clone().next() {
296             Some((_, c)) => {
297                 match self.cur.clone().skip(1).next() {
298                     Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
299                         spec.fill = Some(c);
300                         self.cur.next();
301                     }
302                     Some(..) | None => {}
303                 }
304             }
305             None => {}
306         }
307         // Alignment
308         if self.consume('<') {
309             spec.align = AlignLeft;
310         } else if self.consume('>') {
311             spec.align = AlignRight;
312         } else if self.consume('^') {
313             spec.align = AlignCenter;
314         }
315         // Sign flags
316         if self.consume('+') {
317             spec.flags |= 1 << (FlagSignPlus as uint);
318         } else if self.consume('-') {
319             spec.flags |= 1 << (FlagSignMinus as uint);
320         }
321         // Alternate marker
322         if self.consume('#') {
323             spec.flags |= 1 << (FlagAlternate as uint);
324         }
325         // Width and precision
326         let mut havewidth = false;
327         if self.consume('0') {
328             // small ambiguity with '0$' as a format string. In theory this is a
329             // '0' flag and then an ill-formatted format string with just a '$'
330             // and no count, but this is better if we instead interpret this as
331             // no '0' flag and '0$' as the width instead.
332             if self.consume('$') {
333                 spec.width = CountIsParam(0);
334                 havewidth = true;
335             } else {
336                 spec.flags |= 1 << (FlagSignAwareZeroPad as uint);
337             }
338         }
339         if !havewidth {
340             spec.width = self.count();
341         }
342         if self.consume('.') {
343             if self.consume('*') {
344                 spec.precision = CountIsNextParam;
345             } else {
346                 spec.precision = self.count();
347             }
348         }
349         // Finally the actual format specifier
350         if self.consume('?') {
351             spec.ty = "?";
352         } else {
353             spec.ty = self.word();
354         }
355         return spec;
356     }
357
358     /// Parses a Count parameter at the current position. This does not check
359     /// for 'CountIsNextParam' because that is only used in precision, not
360     /// width.
361     fn count(&mut self) -> Count<'a> {
362         match self.integer() {
363             Some(i) => {
364                 if self.consume('$') {
365                     CountIsParam(i)
366                 } else {
367                     CountIs(i)
368                 }
369             }
370             None => {
371                 let tmp = self.cur.clone();
372                 match self.word() {
373                     word if word.len() > 0 => {
374                         if self.consume('$') {
375                             CountIsName(word)
376                         } else {
377                             self.cur = tmp;
378                             CountImplied
379                         }
380                     }
381                     _ => {
382                         self.cur = tmp;
383                         CountImplied
384                     }
385                 }
386             }
387         }
388     }
389
390     /// Parses a word starting at the current position. A word is considered to
391     /// be an alphabetic character followed by any number of alphanumeric
392     /// characters.
393     fn word(&mut self) -> &'a str {
394         let start = match self.cur.clone().next() {
395             Some((pos, c)) if c.is_xid_start() => {
396                 self.cur.next();
397                 pos
398             }
399             Some(..) | None => { return &self.input[..0]; }
400         };
401         let mut end;
402         loop {
403             match self.cur.clone().next() {
404                 Some((_, c)) if c.is_xid_continue() => {
405                     self.cur.next();
406                 }
407                 Some((pos, _)) => { end = pos; break }
408                 None => { end = self.input.len(); break }
409             }
410         }
411         &self.input[start..end]
412     }
413
414     /// Optionally parses an integer at the current position. This doesn't deal
415     /// with overflow at all, it's just accumulating digits.
416     fn integer(&mut self) -> Option<uint> {
417         let mut cur = 0;
418         let mut found = false;
419         loop {
420             match self.cur.clone().next() {
421                 Some((_, c)) => {
422                     match c.to_digit(10) {
423                         Some(i) => {
424                             cur = cur * 10 + i as usize;
425                             found = true;
426                             self.cur.next();
427                         }
428                         None => { break }
429                     }
430                 }
431                 None => { break }
432             }
433         }
434         if found {
435             return Some(cur);
436         } else {
437             return None;
438         }
439     }
440 }
441
442 #[cfg(test)]
443 mod tests {
444     use super::*;
445
446     fn same(fmt: &'static str, p: &[Piece<'static>]) {
447         let parser = Parser::new(fmt);
448         assert!(p == parser.collect::<Vec<Piece<'static>>>());
449     }
450
451     fn fmtdflt() -> FormatSpec<'static> {
452         return FormatSpec {
453             fill: None,
454             align: AlignUnknown,
455             flags: 0,
456             precision: CountImplied,
457             width: CountImplied,
458             ty: "",
459         }
460     }
461
462     fn musterr(s: &str) {
463         let mut p = Parser::new(s);
464         p.next();
465         assert!(p.errors.len() != 0);
466     }
467
468     #[test]
469     fn simple() {
470         same("asdf", &[String("asdf")]);
471         same("a{{b", &[String("a"), String("{b")]);
472         same("a}}b", &[String("a"), String("}b")]);
473         same("a}}", &[String("a"), String("}")]);
474         same("}}", &[String("}")]);
475         same("\\}}", &[String("\\"), String("}")]);
476     }
477
478     #[test] fn invalid01() { musterr("{") }
479     #[test] fn invalid02() { musterr("}") }
480     #[test] fn invalid04() { musterr("{3a}") }
481     #[test] fn invalid05() { musterr("{:|}") }
482     #[test] fn invalid06() { musterr("{:>>>}") }
483
484     #[test]
485     fn format_nothing() {
486         same("{}", &[NextArgument(Argument {
487             position: ArgumentNext,
488             format: fmtdflt(),
489         })]);
490     }
491     #[test]
492     fn format_position() {
493         same("{3}", &[NextArgument(Argument {
494             position: ArgumentIs(3),
495             format: fmtdflt(),
496         })]);
497     }
498     #[test]
499     fn format_position_nothing_else() {
500         same("{3:}", &[NextArgument(Argument {
501             position: ArgumentIs(3),
502             format: fmtdflt(),
503         })]);
504     }
505     #[test]
506     fn format_type() {
507         same("{3:a}", &[NextArgument(Argument {
508             position: ArgumentIs(3),
509             format: FormatSpec {
510                 fill: None,
511                 align: AlignUnknown,
512                 flags: 0,
513                 precision: CountImplied,
514                 width: CountImplied,
515                 ty: "a",
516             },
517         })]);
518     }
519     #[test]
520     fn format_align_fill() {
521         same("{3:>}", &[NextArgument(Argument {
522             position: ArgumentIs(3),
523             format: FormatSpec {
524                 fill: None,
525                 align: AlignRight,
526                 flags: 0,
527                 precision: CountImplied,
528                 width: CountImplied,
529                 ty: "",
530             },
531         })]);
532         same("{3:0<}", &[NextArgument(Argument {
533             position: ArgumentIs(3),
534             format: FormatSpec {
535                 fill: Some('0'),
536                 align: AlignLeft,
537                 flags: 0,
538                 precision: CountImplied,
539                 width: CountImplied,
540                 ty: "",
541             },
542         })]);
543         same("{3:*<abcd}", &[NextArgument(Argument {
544             position: ArgumentIs(3),
545             format: FormatSpec {
546                 fill: Some('*'),
547                 align: AlignLeft,
548                 flags: 0,
549                 precision: CountImplied,
550                 width: CountImplied,
551                 ty: "abcd",
552             },
553         })]);
554     }
555     #[test]
556     fn format_counts() {
557         same("{:10s}", &[NextArgument(Argument {
558             position: ArgumentNext,
559             format: FormatSpec {
560                 fill: None,
561                 align: AlignUnknown,
562                 flags: 0,
563                 precision: CountImplied,
564                 width: CountIs(10),
565                 ty: "s",
566             },
567         })]);
568         same("{:10$.10s}", &[NextArgument(Argument {
569             position: ArgumentNext,
570             format: FormatSpec {
571                 fill: None,
572                 align: AlignUnknown,
573                 flags: 0,
574                 precision: CountIs(10),
575                 width: CountIsParam(10),
576                 ty: "s",
577             },
578         })]);
579         same("{:.*s}", &[NextArgument(Argument {
580             position: ArgumentNext,
581             format: FormatSpec {
582                 fill: None,
583                 align: AlignUnknown,
584                 flags: 0,
585                 precision: CountIsNextParam,
586                 width: CountImplied,
587                 ty: "s",
588             },
589         })]);
590         same("{:.10$s}", &[NextArgument(Argument {
591             position: ArgumentNext,
592             format: FormatSpec {
593                 fill: None,
594                 align: AlignUnknown,
595                 flags: 0,
596                 precision: CountIsParam(10),
597                 width: CountImplied,
598                 ty: "s",
599             },
600         })]);
601         same("{:a$.b$s}", &[NextArgument(Argument {
602             position: ArgumentNext,
603             format: FormatSpec {
604                 fill: None,
605                 align: AlignUnknown,
606                 flags: 0,
607                 precision: CountIsName("b"),
608                 width: CountIsName("a"),
609                 ty: "s",
610             },
611         })]);
612     }
613     #[test]
614     fn format_flags() {
615         same("{:-}", &[NextArgument(Argument {
616             position: ArgumentNext,
617             format: FormatSpec {
618                 fill: None,
619                 align: AlignUnknown,
620                 flags: (1 << FlagSignMinus as uint),
621                 precision: CountImplied,
622                 width: CountImplied,
623                 ty: "",
624             },
625         })]);
626         same("{:+#}", &[NextArgument(Argument {
627             position: ArgumentNext,
628             format: FormatSpec {
629                 fill: None,
630                 align: AlignUnknown,
631                 flags: (1 << FlagSignPlus as uint) | (1 << FlagAlternate as uint),
632                 precision: CountImplied,
633                 width: CountImplied,
634                 ty: "",
635             },
636         })]);
637     }
638     #[test]
639     fn format_mixture() {
640         same("abcd {3:a} efg", &[String("abcd "), NextArgument(Argument {
641             position: ArgumentIs(3),
642             format: FormatSpec {
643                 fill: None,
644                 align: AlignUnknown,
645                 flags: 0,
646                 precision: CountImplied,
647                 width: CountImplied,
648                 ty: "a",
649             },
650         }), String(" efg")]);
651     }
652 }