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"]
18 #![unstable(feature = "rustc_private", issue = "27812")]
19 #![crate_type = "rlib"]
20 #![crate_type = "dylib"]
21 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
22 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
23 html_root_url = "https://doc.rust-lang.org/nightly/",
24 html_playground_url = "https://play.rust-lang.org/",
25 test(attr(deny(warnings))))]
28 #![feature(staged_api)]
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::*;
41 /// A piece is a portion of the format string which represents the next part
42 /// to emit. These are emitted as a stream by the `Parser` class.
43 #[derive(Copy, Clone, PartialEq)]
45 /// A literal string which should directly be emitted
47 /// This describes that formatting should process the next argument (as
48 /// specified inside) for emission.
49 NextArgument(Argument<'a>),
52 /// Representation of an argument specification.
53 #[derive(Copy, Clone, PartialEq)]
54 pub struct Argument<'a> {
55 /// Where to find this argument
56 pub position: Position<'a>,
57 /// How to format the argument
58 pub format: FormatSpec<'a>,
61 /// Specification for the formatting of an argument in the format string.
62 #[derive(Copy, Clone, PartialEq)]
63 pub struct FormatSpec<'a> {
64 /// Optionally specified character to fill alignment with
65 pub fill: Option<char>,
66 /// Optionally specified alignment
68 /// Packed version of various flags provided
70 /// The integer precision to use
71 pub precision: Count<'a>,
72 /// The string width requested for the resulting format
74 /// The descriptor string representing the name of the format desired for
75 /// this argument, this can be empty or any number of characters, although
76 /// it is required to be one word.
80 /// Enum describing where an argument for a format can be located.
81 #[derive(Copy, Clone, PartialEq)]
82 pub enum Position<'a> {
83 /// The argument is located at a specific index.
85 /// The argument has a name.
86 ArgumentNamed(&'a str),
89 /// Enum of alignments which are supported.
90 #[derive(Copy, Clone, PartialEq)]
92 /// The value will be aligned to the left.
94 /// The value will be aligned to the right.
96 /// The value will be aligned in the center.
98 /// The value will take on a default alignment.
102 /// Various flags which can be applied to format strings. The meaning of these
103 /// flags is defined by the formatters themselves.
104 #[derive(Copy, Clone, PartialEq)]
106 /// A `+` will be used to denote positive numbers.
108 /// A `-` will be used to denote negative numbers. This is the default.
110 /// An alternate form will be used for the value. In the case of numbers,
111 /// this means that the number will be prefixed with the supplied string.
113 /// For numbers, this means that the number will be padded with zeroes,
114 /// and the sign (`+` or `-`) will precede them.
115 FlagSignAwareZeroPad,
118 /// A count is used for the precision and width parameters of an integer, and
119 /// can reference either an argument or a literal integer.
120 #[derive(Copy, Clone, PartialEq)]
122 /// The count is specified explicitly.
124 /// The count is specified by the argument with the given name.
125 CountIsName(&'a str),
126 /// The count is specified by the argument at the given index.
128 /// The count is implied and cannot be explicitly specified.
132 /// The parser structure for interpreting the input format string. This is
133 /// modeled as an iterator over `Piece` structures to form a stream of tokens
136 /// This is a recursive-descent parser for the sake of simplicity, and if
137 /// necessary there's probably lots of room for improvement performance-wise.
138 pub struct Parser<'a> {
140 cur: iter::Peekable<str::CharIndices<'a>>,
141 /// Error messages accumulated during parsing
142 pub errors: Vec<(string::String, Option<string::String>)>,
143 /// Current position of implicit positional argument pointer
147 impl<'a> Iterator for Parser<'a> {
148 type Item = Piece<'a>;
150 fn next(&mut self) -> Option<Piece<'a>> {
151 if let Some(&(pos, c)) = self.cur.peek() {
155 if self.consume('{') {
156 Some(String(self.string(pos + 1)))
158 let ret = Some(NextArgument(self.argument()));
159 self.must_consume('}');
165 if self.consume('}') {
166 Some(String(self.string(pos + 1)))
168 self.err_with_note("unmatched `}` found",
169 "if you intended to print `}`, \
170 you can escape it using `}}`");
174 _ => Some(String(self.string(pos))),
182 impl<'a> Parser<'a> {
183 /// Creates a new parser for the given format string
184 pub fn new(s: &'a str) -> Parser<'a> {
187 cur: s.char_indices().peekable(),
193 /// Notifies of an error. The message doesn't actually need to be of type
194 /// String, but I think it does when this eventually uses conditions so it
195 /// might as well start using it now.
196 fn err(&mut self, msg: &str) {
197 self.errors.push((msg.to_owned(), None));
200 /// Notifies of an error. The message doesn't actually need to be of type
201 /// String, but I think it does when this eventually uses conditions so it
202 /// might as well start using it now.
203 fn err_with_note(&mut self, msg: &str, note: &str) {
204 self.errors.push((msg.to_owned(), Some(note.to_owned())));
207 /// Optionally consumes the specified character. If the character is not at
208 /// the current position, then the current iterator isn't moved and false is
209 /// returned, otherwise the character is consumed and true is returned.
210 fn consume(&mut self, c: char) -> bool {
211 if let Some(&(_, maybe)) = self.cur.peek() {
223 /// Forces consumption of the specified character. If the character is not
224 /// found, an error is emitted.
225 fn must_consume(&mut self, c: char) {
227 if let Some(&(_, maybe)) = self.cur.peek() {
231 self.err(&format!("expected `{:?}`, found `{:?}`", c, maybe));
234 let msg = &format!("expected `{:?}` but string was terminated", c);
236 self.err_with_note(msg,
237 "if you intended to print `{`, you can escape it using `{{`");
244 /// Consumes all whitespace characters until the first non-whitespace
247 while let Some(&(_, c)) = self.cur.peek() {
248 if c.is_whitespace() {
256 /// Parses all of a string which is to be considered a "raw literal" in a
257 /// format string. This is everything outside of the braces.
258 fn string(&mut self, start: usize) -> &'a str {
259 // we may not consume the character, peek the iterator
260 while let Some(&(pos, c)) = self.cur.peek() {
263 return &self.input[start..pos];
270 &self.input[start..self.input.len()]
273 /// Parses an Argument structure, or what's contained within braces inside
274 /// the format string
275 fn argument(&mut self) -> Argument<'a> {
276 let pos = self.position();
277 let format = self.format();
279 // Resolve position after parsing format spec.
280 let pos = match pos {
281 Some(position) => position,
295 /// Parses a positional argument for a format. This could either be an
296 /// integer index of an argument, a named argument, or a blank string.
297 /// Returns `Some(parsed_position)` if the position is not implicitly
298 /// consuming a macro argument, `None` if it's the case.
299 fn position(&mut self) -> Option<Position<'a>> {
300 if let Some(i) = self.integer() {
303 match self.cur.peek() {
304 Some(&(_, c)) if c.is_alphabetic() => Some(ArgumentNamed(self.word())),
306 // This is an `ArgumentNext`.
307 // Record the fact and do the resolution after parsing the
308 // format spec, to make things like `{:.*}` work.
314 /// Parses a format specifier at the current position, returning all of the
315 /// relevant information in the FormatSpec struct.
316 fn format(&mut self) -> FormatSpec<'a> {
317 let mut spec = FormatSpec {
321 precision: CountImplied,
323 ty: &self.input[..0],
325 if !self.consume(':') {
330 if let Some(&(_, c)) = self.cur.peek() {
331 match self.cur.clone().skip(1).next() {
332 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
340 if self.consume('<') {
341 spec.align = AlignLeft;
342 } else if self.consume('>') {
343 spec.align = AlignRight;
344 } else if self.consume('^') {
345 spec.align = AlignCenter;
348 if self.consume('+') {
349 spec.flags |= 1 << (FlagSignPlus as u32);
350 } else if self.consume('-') {
351 spec.flags |= 1 << (FlagSignMinus as u32);
354 if self.consume('#') {
355 spec.flags |= 1 << (FlagAlternate as u32);
357 // Width and precision
358 let mut havewidth = false;
359 if self.consume('0') {
360 // small ambiguity with '0$' as a format string. In theory this is a
361 // '0' flag and then an ill-formatted format string with just a '$'
362 // and no count, but this is better if we instead interpret this as
363 // no '0' flag and '0$' as the width instead.
364 if self.consume('$') {
365 spec.width = CountIsParam(0);
368 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
372 spec.width = self.count();
374 if self.consume('.') {
375 if self.consume('*') {
376 // Resolve `CountIsNextParam`.
377 // We can do this immediately as `position` is resolved later.
380 spec.precision = CountIsParam(i);
382 spec.precision = self.count();
385 // Finally the actual format specifier
386 if self.consume('?') {
389 spec.ty = self.word();
394 /// Parses a Count parameter at the current position. This does not check
395 /// for 'CountIsNextParam' because that is only used in precision, not
397 fn count(&mut self) -> Count<'a> {
398 if let Some(i) = self.integer() {
399 if self.consume('$') {
405 let tmp = self.cur.clone();
406 let word = self.word();
411 if self.consume('$') {
421 /// Parses a word starting at the current position. A word is considered to
422 /// be an alphabetic character followed by any number of alphanumeric
424 fn word(&mut self) -> &'a str {
425 let start = match self.cur.peek() {
426 Some(&(pos, c)) if c.is_xid_start() => {
431 return &self.input[..0];
434 while let Some(&(pos, c)) = self.cur.peek() {
435 if c.is_xid_continue() {
438 return &self.input[start..pos];
441 &self.input[start..self.input.len()]
444 /// Optionally parses an integer at the current position. This doesn't deal
445 /// with overflow at all, it's just accumulating digits.
446 fn integer(&mut self) -> Option<usize> {
448 let mut found = false;
449 while let Some(&(_, c)) = self.cur.peek() {
450 if let Some(i) = c.to_digit(10) {
451 cur = cur * 10 + i as usize;
470 fn same(fmt: &'static str, p: &[Piece<'static>]) {
471 let parser = Parser::new(fmt);
472 assert!(parser.collect::<Vec<Piece<'static>>>() == p);
475 fn fmtdflt() -> FormatSpec<'static> {
480 precision: CountImplied,
486 fn musterr(s: &str) {
487 let mut p = Parser::new(s);
489 assert!(!p.errors.is_empty());
494 same("asdf", &[String("asdf")]);
495 same("a{{b", &[String("a"), String("{b")]);
496 same("a}}b", &[String("a"), String("}b")]);
497 same("a}}", &[String("a"), String("}")]);
498 same("}}", &[String("}")]);
499 same("\\}}", &[String("\\"), String("}")]);
524 fn format_nothing() {
526 &[NextArgument(Argument {
527 position: ArgumentIs(0),
532 fn format_position() {
534 &[NextArgument(Argument {
535 position: ArgumentIs(3),
540 fn format_position_nothing_else() {
542 &[NextArgument(Argument {
543 position: ArgumentIs(3),
550 &[NextArgument(Argument {
551 position: ArgumentIs(3),
556 precision: CountImplied,
563 fn format_align_fill() {
565 &[NextArgument(Argument {
566 position: ArgumentIs(3),
571 precision: CountImplied,
577 &[NextArgument(Argument {
578 position: ArgumentIs(3),
583 precision: CountImplied,
589 &[NextArgument(Argument {
590 position: ArgumentIs(3),
595 precision: CountImplied,
604 &[NextArgument(Argument {
605 position: ArgumentIs(0),
610 precision: CountImplied,
616 &[NextArgument(Argument {
617 position: ArgumentIs(0),
622 precision: CountIs(10),
623 width: CountIsParam(10),
628 &[NextArgument(Argument {
629 position: ArgumentIs(1),
634 precision: CountIsParam(0),
640 &[NextArgument(Argument {
641 position: ArgumentIs(0),
646 precision: CountIsParam(10),
652 &[NextArgument(Argument {
653 position: ArgumentIs(0),
658 precision: CountIsName("b"),
659 width: CountIsName("a"),
667 &[NextArgument(Argument {
668 position: ArgumentIs(0),
672 flags: (1 << FlagSignMinus as u32),
673 precision: CountImplied,
679 &[NextArgument(Argument {
680 position: ArgumentIs(0),
684 flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32),
685 precision: CountImplied,
692 fn format_mixture() {
693 same("abcd {3:a} efg",
695 NextArgument(Argument {
696 position: ArgumentIs(3),
701 precision: CountImplied,