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")]
22 #![crate_type = "rlib"]
23 #![crate_type = "dylib"]
24 #![doc(html_logo_url = "http://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
= "http://doc.rust-lang.org/nightly/",
27 html_playground_url
= "http://play.rust-lang.org/")]
29 #![feature(staged_api)]
32 pub use self::Piece
::*;
33 pub use self::Position
::*;
34 pub use self::Alignment
::*;
35 pub use self::Flag
::*;
36 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 will be in the next position. This is the default.
85 /// The argument is located at a specific index.
87 /// The argument has a name.
88 ArgumentNamed(&'a
str),
91 /// Enum of alignments which are supported.
92 #[derive(Copy, Clone, PartialEq)]
94 /// The value will be aligned to the left.
96 /// The value will be aligned to the right.
98 /// The value will be aligned in the center.
100 /// The value will take on a default alignment.
104 /// Various flags which can be applied to format strings. The meaning of these
105 /// flags is defined by the formatters themselves.
106 #[derive(Copy, Clone, PartialEq)]
108 /// A `+` will be used to denote positive numbers.
110 /// A `-` will be used to denote negative numbers. This is the default.
112 /// An alternate form will be used for the value. In the case of numbers,
113 /// this means that the number will be prefixed with the supplied string.
115 /// For numbers, this means that the number will be padded with zeroes,
116 /// and the sign (`+` or `-`) will precede them.
117 FlagSignAwareZeroPad
,
120 /// A count is used for the precision and width parameters of an integer, and
121 /// can reference either an argument or a literal integer.
122 #[derive(Copy, Clone, PartialEq)]
124 /// The count is specified explicitly.
126 /// The count is specified by the argument with the given name.
127 CountIsName(&'a
str),
128 /// The count is specified by the argument at the given index.
130 /// The count is specified by the next parameter.
132 /// The count is implied and cannot be explicitly specified.
136 /// The parser structure for interpreting the input format string. This is
137 /// modelled as an iterator over `Piece` structures to form a stream of tokens
140 /// This is a recursive-descent parser for the sake of simplicity, and if
141 /// necessary there's probably lots of room for improvement performance-wise.
142 pub struct Parser
<'a
> {
144 cur
: str::CharIndices
<'a
>,
145 /// Error messages accumulated during parsing
146 pub errors
: Vec
<string
::String
>,
149 impl<'a
> Iterator
for Parser
<'a
> {
150 type Item
= Piece
<'a
>;
152 fn next(&mut self) -> Option
<Piece
<'a
>> {
153 match self.cur
.clone().next() {
154 Some((pos
, '
{'
)) => {
156 if self.consume('
{'
) {
157 Some(String(self.string(pos
+ 1)))
159 let ret
= Some(NextArgument(self.argument()));
160 self.must_consume('
}'
);
164 Some((pos
, '
}'
)) => {
166 if self.consume('
}'
) {
167 Some(String(self.string(pos
+ 1)))
169 self.err("unmatched `}` found");
173 Some((pos
, _
)) => { Some(String(self.string(pos))) }
179 impl<'a
> Parser
<'a
> {
180 /// Creates a new parser for the given format string
181 pub fn new(s
: &'a
str) -> Parser
<'a
> {
184 cur
: s
.char_indices(),
189 /// Notifies of an error. The message doesn't actually need to be of type
190 /// String, but I think it does when this eventually uses conditions so it
191 /// might as well start using it now.
192 fn err(&mut self, msg
: &str) {
193 self.errors
.push(msg
.to_string());
196 /// Optionally consumes the specified character. If the character is not at
197 /// the current position, then the current iterator isn't moved and false is
198 /// returned, otherwise the character is consumed and true is returned.
199 fn consume(&mut self, c
: char) -> bool
{
200 match self.cur
.clone().next() {
201 Some((_
, maybe
)) if c
== maybe
=> {
205 Some(..) | None
=> false,
209 /// Forces consumption of the specified character. If the character is not
210 /// found, an error is emitted.
211 fn must_consume(&mut self, c
: char) {
213 match self.cur
.clone().next() {
214 Some((_
, maybe
)) if c
== maybe
=> {
217 Some((_
, other
)) => {
218 self.err(&format
!("expected `{:?}`, found `{:?}`", c
,
222 self.err(&format
!("expected `{:?}` but string was terminated",
228 /// Consumes all whitespace characters until the first non-whitespace
232 match self.cur
.clone().next() {
233 Some((_
, c
)) if c
.is_whitespace() => { self.cur.next(); }
234 Some(..) | None
=> { return }
239 /// Parses all of a string which is to be considered a "raw literal" in a
240 /// format string. This is everything outside of the braces.
241 fn string(&mut self, start
: usize) -> &'a
str {
243 // we may not consume the character, so clone the iterator
244 match self.cur
.clone().next() {
245 Some((pos
, '
}'
)) | Some((pos
, '
{'
)) => {
246 return &self.input
[start
..pos
];
248 Some(..) => { self.cur.next(); }
251 return &self.input
[start
..self.input
.len()];
257 /// Parses an Argument structure, or what's contained within braces inside
258 /// the format string
259 fn argument(&mut self) -> Argument
<'a
> {
261 position
: self.position(),
262 format
: self.format(),
266 /// Parses a positional argument for a format. This could either be an
267 /// integer index of an argument, a named argument, or a blank string.
268 fn position(&mut self) -> Position
<'a
> {
269 match self.integer() {
270 Some(i
) => { ArgumentIs(i) }
272 match self.cur
.clone().next() {
273 Some((_
, c
)) if c
.is_alphabetic() => {
274 ArgumentNamed(self.word())
282 /// Parses a format specifier at the current position, returning all of the
283 /// relevant information in the FormatSpec struct.
284 fn format(&mut self) -> FormatSpec
<'a
> {
285 let mut spec
= FormatSpec
{
289 precision
: CountImplied
,
291 ty
: &self.input
[..0],
293 if !self.consume('
:'
) { return spec }
296 match self.cur
.clone().next() {
298 match self.cur
.clone().skip(1).next() {
299 Some((_
, '
>'
)) | Some((_
, '
<'
)) | Some((_
, '
^')) => {
303 Some(..) | None
=> {}
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 match self.integer() {
365 if self.consume('$'
) {
372 let tmp
= self.cur
.clone();
374 word
if !word
.is_empty() => {
375 if self.consume('$'
) {
391 /// Parses a word starting at the current position. A word is considered to
392 /// be an alphabetic character followed by any number of alphanumeric
394 fn word(&mut self) -> &'a
str {
395 let start
= match self.cur
.clone().next() {
396 Some((pos
, c
)) if c
.is_xid_start() => {
400 Some(..) | None
=> { return &self.input[..0]; }
404 match self.cur
.clone().next() {
405 Some((_
, c
)) if c
.is_xid_continue() => {
408 Some((pos
, _
)) => { end = pos; break }
409 None
=> { end = self.input.len(); break }
412 &self.input
[start
..end
]
415 /// Optionally parses an integer at the current position. This doesn't deal
416 /// with overflow at all, it's just accumulating digits.
417 fn integer(&mut self) -> Option
<usize> {
419 let mut found
= false;
421 match self.cur
.clone().next() {
423 match c
.to_digit(10) {
425 cur
= cur
* 10 + i
as usize;
447 fn same(fmt
: &'
static str, p
: &[Piece
<'
static>]) {
448 let parser
= Parser
::new(fmt
);
449 assert
!(parser
.collect
::<Vec
<Piece
<'
static>>>() == p
);
452 fn fmtdflt() -> FormatSpec
<'
static> {
457 precision
: CountImplied
,
463 fn musterr(s
: &str) {
464 let mut p
= Parser
::new(s
);
466 assert
!(!p
.errors
.is_empty());
471 same("asdf", &[String("asdf")]);
472 same("a{{b", &[String("a"), String("{b")]);
473 same("a}}b", &[String("a"), String("}b")]);
474 same("a}}", &[String("a"), String("}")]);
475 same("}}", &[String("}")]);
476 same("\\}}", &[String("\\"), String("}")]);
479 #[test] fn invalid01() { musterr("{") }
480 #[test] fn invalid02() { musterr("}") }
481 #[test] fn invalid04() { musterr("{3a}") }
482 #[test] fn invalid05() { musterr("{:|}") }
483 #[test] fn invalid06() { musterr("{:>>>}") }
486 fn format_nothing() {
487 same("{}", &[NextArgument(Argument
{
488 position
: ArgumentNext
,
493 fn format_position() {
494 same("{3}", &[NextArgument(Argument
{
495 position
: ArgumentIs(3),
500 fn format_position_nothing_else() {
501 same("{3:}", &[NextArgument(Argument
{
502 position
: ArgumentIs(3),
508 same("{3:a}", &[NextArgument(Argument
{
509 position
: ArgumentIs(3),
514 precision
: CountImplied
,
521 fn format_align_fill() {
522 same("{3:>}", &[NextArgument(Argument
{
523 position
: ArgumentIs(3),
528 precision
: CountImplied
,
533 same("{3:0<}", &[NextArgument(Argument
{
534 position
: ArgumentIs(3),
539 precision
: CountImplied
,
544 same("{3:*<abcd}", &[NextArgument(Argument
{
545 position
: ArgumentIs(3),
550 precision
: CountImplied
,
558 same("{:10s}", &[NextArgument(Argument
{
559 position
: ArgumentNext
,
564 precision
: CountImplied
,
569 same("{:10$.10s}", &[NextArgument(Argument
{
570 position
: ArgumentNext
,
575 precision
: CountIs(10),
576 width
: CountIsParam(10),
580 same("{:.*s}", &[NextArgument(Argument
{
581 position
: ArgumentNext
,
586 precision
: CountIsNextParam
,
591 same("{:.10$s}", &[NextArgument(Argument
{
592 position
: ArgumentNext
,
597 precision
: CountIsParam(10),
602 same("{:a$.b$s}", &[NextArgument(Argument
{
603 position
: ArgumentNext
,
608 precision
: CountIsName("b"),
609 width
: CountIsName("a"),
616 same("{:-}", &[NextArgument(Argument
{
617 position
: ArgumentNext
,
621 flags
: (1 << FlagSignMinus
as u32),
622 precision
: CountImplied
,
627 same("{:+#}", &[NextArgument(Argument
{
628 position
: ArgumentNext
,
632 flags
: (1 << FlagSignPlus
as u32) | (1 << FlagAlternate
as u32),
633 precision
: CountImplied
,
640 fn format_mixture() {
641 same("abcd {3:a} efg", &[String("abcd "), NextArgument(Argument
{
642 position
: ArgumentIs(3),
647 precision
: CountImplied
,
651 }), String(" efg")]);