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 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
18 #![cfg_attr(stage0, feature(custom_attribute))]
19 #![crate_name = "fmt_macros"]
20 #![unstable(feature = "rustc_private", issue = "27812")]
22 #![crate_type = "rlib"]
23 #![crate_type = "dylib"]
24 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
25 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
26 html_root_url = "https://doc.rust-lang.org/nightly/",
27 html_playground_url = "https://play.rust-lang.org/",
28 test(attr(deny(warnings))))]
30 #![feature(staged_api)]
33 pub use self::Piece::*;
34 pub use self::Position::*;
35 pub use self::Alignment::*;
36 pub use self::Flag::*;
37 pub use self::Count::*;
43 /// A piece is a portion of the format string which represents the next part
44 /// to emit. These are emitted as a stream by the `Parser` class.
45 #[derive(Copy, Clone, PartialEq)]
47 /// A literal string which should directly be emitted
49 /// This describes that formatting should process the next argument (as
50 /// specified inside) for emission.
51 NextArgument(Argument<'a>),
54 /// Representation of an argument specification.
55 #[derive(Copy, Clone, PartialEq)]
56 pub struct Argument<'a> {
57 /// Where to find this argument
58 pub position: Position<'a>,
59 /// How to format the argument
60 pub format: FormatSpec<'a>,
63 /// Specification for the formatting of an argument in the format string.
64 #[derive(Copy, Clone, PartialEq)]
65 pub struct FormatSpec<'a> {
66 /// Optionally specified character to fill alignment with
67 pub fill: Option<char>,
68 /// Optionally specified alignment
70 /// Packed version of various flags provided
72 /// The integer precision to use
73 pub precision: Count<'a>,
74 /// The string width requested for the resulting format
76 /// The descriptor string representing the name of the format desired for
77 /// this argument, this can be empty or any number of characters, although
78 /// it is required to be one word.
82 /// Enum describing where an argument for a format can be located.
83 #[derive(Copy, Clone, PartialEq)]
84 pub enum Position<'a> {
85 /// The argument will be in the next position. This is the default.
87 /// The argument is located at a specific index.
89 /// The argument has a name.
90 ArgumentNamed(&'a str),
93 /// Enum of alignments which are supported.
94 #[derive(Copy, Clone, PartialEq)]
96 /// The value will be aligned to the left.
98 /// The value will be aligned to the right.
100 /// The value will be aligned in the center.
102 /// The value will take on a default alignment.
106 /// Various flags which can be applied to format strings. The meaning of these
107 /// flags is defined by the formatters themselves.
108 #[derive(Copy, Clone, PartialEq)]
110 /// A `+` will be used to denote positive numbers.
112 /// A `-` will be used to denote negative numbers. This is the default.
114 /// An alternate form will be used for the value. In the case of numbers,
115 /// this means that the number will be prefixed with the supplied string.
117 /// For numbers, this means that the number will be padded with zeroes,
118 /// and the sign (`+` or `-`) will precede them.
119 FlagSignAwareZeroPad,
122 /// A count is used for the precision and width parameters of an integer, and
123 /// can reference either an argument or a literal integer.
124 #[derive(Copy, Clone, PartialEq)]
126 /// The count is specified explicitly.
128 /// The count is specified by the argument with the given name.
129 CountIsName(&'a str),
130 /// The count is specified by the argument at the given index.
132 /// The count is specified by the next parameter.
134 /// The count is implied and cannot be explicitly specified.
138 /// The parser structure for interpreting the input format string. This is
139 /// modeled as an iterator over `Piece` structures to form a stream of tokens
142 /// This is a recursive-descent parser for the sake of simplicity, and if
143 /// necessary there's probably lots of room for improvement performance-wise.
144 pub struct Parser<'a> {
146 cur: iter::Peekable<str::CharIndices<'a>>,
147 /// Error messages accumulated during parsing
148 pub errors: Vec<string::String>,
151 impl<'a> Iterator for Parser<'a> {
152 type Item = Piece<'a>;
154 fn next(&mut self) -> Option<Piece<'a>> {
155 if let Some(&(pos, c)) = self.cur.peek() {
159 if self.consume('{') {
160 Some(String(self.string(pos + 1)))
162 let ret = Some(NextArgument(self.argument()));
163 self.must_consume('}');
169 if self.consume('}') {
170 Some(String(self.string(pos + 1)))
172 self.err("unmatched `}` found");
176 _ => Some(String(self.string(pos))),
184 impl<'a> Parser<'a> {
185 /// Creates a new parser for the given format string
186 pub fn new(s: &'a str) -> Parser<'a> {
189 cur: s.char_indices().peekable(),
194 /// Notifies of an error. The message doesn't actually need to be of type
195 /// String, but I think it does when this eventually uses conditions so it
196 /// might as well start using it now.
197 fn err(&mut self, msg: &str) {
198 self.errors.push(msg.to_owned());
201 /// Optionally consumes the specified character. If the character is not at
202 /// the current position, then the current iterator isn't moved and false is
203 /// returned, otherwise the character is consumed and true is returned.
204 fn consume(&mut self, c: char) -> bool {
205 if let Some(&(_, maybe)) = self.cur.peek() {
217 /// Forces consumption of the specified character. If the character is not
218 /// found, an error is emitted.
219 fn must_consume(&mut self, c: char) {
221 if let Some(&(_, maybe)) = self.cur.peek() {
225 self.err(&format!("expected `{:?}`, found `{:?}`", c, maybe));
228 self.err(&format!("expected `{:?}` but string was terminated", c));
232 /// Consumes all whitespace characters until the first non-whitespace
235 while let Some(&(_, c)) = self.cur.peek() {
236 if c.is_whitespace() {
244 /// Parses all of a string which is to be considered a "raw literal" in a
245 /// format string. This is everything outside of the braces.
246 fn string(&mut self, start: usize) -> &'a str {
247 // we may not consume the character, peek the iterator
248 while let Some(&(pos, c)) = self.cur.peek() {
251 return &self.input[start..pos];
258 &self.input[start..self.input.len()]
261 /// Parses an Argument structure, or what's contained within braces inside
262 /// the format string
263 fn argument(&mut self) -> Argument<'a> {
265 position: self.position(),
266 format: self.format(),
270 /// Parses a positional argument for a format. This could either be an
271 /// integer index of an argument, a named argument, or a blank string.
272 fn position(&mut self) -> Position<'a> {
273 if let Some(i) = self.integer() {
276 match self.cur.peek() {
277 Some(&(_, c)) if c.is_alphabetic() => ArgumentNamed(self.word()),
283 /// Parses a format specifier at the current position, returning all of the
284 /// relevant information in the FormatSpec struct.
285 fn format(&mut self) -> FormatSpec<'a> {
286 let mut spec = FormatSpec {
290 precision: CountImplied,
292 ty: &self.input[..0],
294 if !self.consume(':') {
299 if let Some(&(_, c)) = self.cur.peek() {
300 match self.cur.clone().skip(1).next() {
301 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
309 if self.consume('<') {
310 spec.align = AlignLeft;
311 } else if self.consume('>') {
312 spec.align = AlignRight;
313 } else if self.consume('^') {
314 spec.align = AlignCenter;
317 if self.consume('+') {
318 spec.flags |= 1 << (FlagSignPlus as u32);
319 } else if self.consume('-') {
320 spec.flags |= 1 << (FlagSignMinus as u32);
323 if self.consume('#') {
324 spec.flags |= 1 << (FlagAlternate as u32);
326 // Width and precision
327 let mut havewidth = false;
328 if self.consume('0') {
329 // small ambiguity with '0$' as a format string. In theory this is a
330 // '0' flag and then an ill-formatted format string with just a '$'
331 // and no count, but this is better if we instead interpret this as
332 // no '0' flag and '0$' as the width instead.
333 if self.consume('$') {
334 spec.width = CountIsParam(0);
337 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
341 spec.width = self.count();
343 if self.consume('.') {
344 if self.consume('*') {
345 spec.precision = CountIsNextParam;
347 spec.precision = self.count();
350 // Finally the actual format specifier
351 if self.consume('?') {
354 spec.ty = self.word();
359 /// Parses a Count parameter at the current position. This does not check
360 /// for 'CountIsNextParam' because that is only used in precision, not
362 fn count(&mut self) -> Count<'a> {
363 if let Some(i) = self.integer() {
364 if self.consume('$') {
370 let tmp = self.cur.clone();
371 let word = self.word();
376 if self.consume('$') {
386 /// Parses a word starting at the current position. A word is considered to
387 /// be an alphabetic character followed by any number of alphanumeric
389 fn word(&mut self) -> &'a str {
390 let start = match self.cur.peek() {
391 Some(&(pos, c)) if c.is_xid_start() => {
396 return &self.input[..0];
399 while let Some(&(pos, c)) = self.cur.peek() {
400 if c.is_xid_continue() {
403 return &self.input[start..pos];
406 &self.input[start..self.input.len()]
409 /// Optionally parses an integer at the current position. This doesn't deal
410 /// with overflow at all, it's just accumulating digits.
411 fn integer(&mut self) -> Option<usize> {
413 let mut found = false;
414 while let Some(&(_, c)) = self.cur.peek() {
415 if let Some(i) = c.to_digit(10) {
416 cur = cur * 10 + i as usize;
435 fn same(fmt: &'static str, p: &[Piece<'static>]) {
436 let parser = Parser::new(fmt);
437 assert!(parser.collect::<Vec<Piece<'static>>>() == p);
440 fn fmtdflt() -> FormatSpec<'static> {
445 precision: CountImplied,
451 fn musterr(s: &str) {
452 let mut p = Parser::new(s);
454 assert!(!p.errors.is_empty());
459 same("asdf", &[String("asdf")]);
460 same("a{{b", &[String("a"), String("{b")]);
461 same("a}}b", &[String("a"), String("}b")]);
462 same("a}}", &[String("a"), String("}")]);
463 same("}}", &[String("}")]);
464 same("\\}}", &[String("\\"), String("}")]);
489 fn format_nothing() {
491 &[NextArgument(Argument {
492 position: ArgumentNext,
497 fn format_position() {
499 &[NextArgument(Argument {
500 position: ArgumentIs(3),
505 fn format_position_nothing_else() {
507 &[NextArgument(Argument {
508 position: ArgumentIs(3),
515 &[NextArgument(Argument {
516 position: ArgumentIs(3),
521 precision: CountImplied,
528 fn format_align_fill() {
530 &[NextArgument(Argument {
531 position: ArgumentIs(3),
536 precision: CountImplied,
542 &[NextArgument(Argument {
543 position: ArgumentIs(3),
548 precision: CountImplied,
554 &[NextArgument(Argument {
555 position: ArgumentIs(3),
560 precision: CountImplied,
569 &[NextArgument(Argument {
570 position: ArgumentNext,
575 precision: CountImplied,
581 &[NextArgument(Argument {
582 position: ArgumentNext,
587 precision: CountIs(10),
588 width: CountIsParam(10),
593 &[NextArgument(Argument {
594 position: ArgumentNext,
599 precision: CountIsNextParam,
605 &[NextArgument(Argument {
606 position: ArgumentNext,
611 precision: CountIsParam(10),
617 &[NextArgument(Argument {
618 position: ArgumentNext,
623 precision: CountIsName("b"),
624 width: CountIsName("a"),
632 &[NextArgument(Argument {
633 position: ArgumentNext,
637 flags: (1 << FlagSignMinus as u32),
638 precision: CountImplied,
644 &[NextArgument(Argument {
645 position: ArgumentNext,
649 flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32),
650 precision: CountImplied,
657 fn format_mixture() {
658 same("abcd {3:a} efg",
660 NextArgument(Argument {
661 position: ArgumentIs(3),
666 precision: CountImplied,