1 // Copyright 2013-2014 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 // ignore-lexer-test FIXME #15679
13 //! Utilities for formatting and printing strings
15 //! This module contains the runtime support for the `format!` syntax extension.
16 //! This macro is implemented in the compiler to emit calls to this module in
17 //! order to format arguments at runtime into strings and streams.
21 //! The `format!` macro is intended to be familiar to those coming from C's
22 //! printf/fprintf functions or Python's `str.format` function. In its current
23 //! revision, the `format!` macro returns a `String` type which is the result of
24 //! the formatting. In the future it will also be able to pass in a stream to
25 //! format arguments directly while performing minimal allocations.
27 //! Some examples of the `format!` extension are:
31 //! format!("Hello"); // => "Hello"
32 //! format!("Hello, {}!", "world"); // => "Hello, world!"
33 //! format!("The number is {}", 1i); // => "The number is 1"
34 //! format!("{:?}", (3i, 4i)); // => "(3i, 4i)"
35 //! format!("{value}", value=4i); // => "4"
36 //! format!("{} {}", 1i, 2u); // => "1 2"
40 //! From these, you can see that the first argument is a format string. It is
41 //! required by the compiler for this to be a string literal; it cannot be a
42 //! variable passed in (in order to perform validity checking). The compiler
43 //! will then parse the format string and determine if the list of arguments
44 //! provided is suitable to pass to this format string.
46 //! ### Positional parameters
48 //! Each formatting argument is allowed to specify which value argument it's
49 //! referencing, and if omitted it is assumed to be "the next argument". For
50 //! example, the format string `{} {} {}` would take three parameters, and they
51 //! would be formatted in the same order as they're given. The format string
52 //! `{2} {1} {0}`, however, would format arguments in reverse order.
54 //! Things can get a little tricky once you start intermingling the two types of
55 //! positional specifiers. The "next argument" specifier can be thought of as an
56 //! iterator over the argument. Each time a "next argument" specifier is seen,
57 //! the iterator advances. This leads to behavior like this:
60 //! format!("{1} {} {0} {}", 1i, 2i); // => "2 1 1 2"
63 //! The internal iterator over the argument has not been advanced by the time
64 //! the first `{}` is seen, so it prints the first argument. Then upon reaching
65 //! the second `{}`, the iterator has advanced forward to the second argument.
66 //! Essentially, parameters which explicitly name their argument do not affect
67 //! parameters which do not name an argument in terms of positional specifiers.
69 //! A format string is required to use all of its arguments, otherwise it is a
70 //! compile-time error. You may refer to the same argument more than once in the
71 //! format string, although it must always be referred to with the same type.
73 //! ### Named parameters
75 //! Rust itself does not have a Python-like equivalent of named parameters to a
76 //! function, but the `format!` macro is a syntax extension which allows it to
77 //! leverage named parameters. Named parameters are listed at the end of the
78 //! argument list and have the syntax:
81 //! identifier '=' expression
84 //! For example, the following `format!` expressions all use named argument:
88 //! format!("{argument}", argument = "test"); // => "test"
89 //! format!("{name} {}", 1i, name = 2i); // => "2 1"
90 //! format!("{a} {c} {b}", a="a", b='b', c=3i); // => "a 3 b"
94 //! It is illegal to put positional parameters (those without names) after
95 //! arguments which have names. Like with positional parameters, it is illegal
96 //! to provide named parameters that are unused by the format string.
98 //! ### Argument types
100 //! Each argument's type is dictated by the format string. It is a requirement
101 //! that every argument is only ever referred to by one type. For example, this
102 //! is an invalid format string:
108 //! This is invalid because the first argument is both referred to as a
109 //! hexadecimal as well as an
112 //! There are various parameters which do require a particular type, however.
113 //! Namely if the syntax `{:.*}` is used, then the number of characters to print
114 //! precedes the actual object being formatted, and the number of characters
115 //! must have the type `uint`. Although a `uint` can be printed with `{}`, it is
116 //! illegal to reference an argument as such. For example this is another
117 //! invalid format string:
123 //! ### Formatting traits
125 //! When requesting that an argument be formatted with a particular type, you
126 //! are actually requesting that an argument ascribes to a particular trait.
127 //! This allows multiple actual types to be formatted via `{:x}` (like `i8` as
128 //! well as `int`). The current mapping of types to traits is:
130 //! * *nothing* ⇒ `String`
133 //! * `x` ⇒ `LowerHex`
134 //! * `X` ⇒ `UpperHex`
135 //! * `p` ⇒ `Pointer`
137 //! * `e` ⇒ `LowerExp`
138 //! * `E` ⇒ `UpperExp`
140 //! What this means is that any type of argument which implements the
141 //! `std::fmt::Binary` trait can then be formatted with `{:b}`. Implementations
142 //! are provided for these traits for a number of primitive types by the
143 //! standard library as well. If no format is specified (as in `{}` or `{:6}`),
144 //! then the format trait used is the `String` trait.
146 //! When implementing a format trait for your own type, you will have to
147 //! implement a method of the signature:
151 //! # struct Foo; // our custom type
152 //! # impl fmt::Show for Foo {
153 //! fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result {
154 //! # write!(f, "testing, testing")
158 //! Your type will be passed as `self` by-reference, and then the function
159 //! should emit output into the `f.buf` stream. It is up to each format trait
160 //! implementation to correctly adhere to the requested formatting parameters.
161 //! The values of these parameters will be listed in the fields of the
162 //! `Formatter` struct. In order to help with this, the `Formatter` struct also
163 //! provides some helper methods.
165 //! Additionally, the return value of this function is `fmt::Result` which is a
166 //! typedef to `Result<(), IoError>` (also known as `IoResult<()>`). Formatting
167 //! implementations should ensure that they return errors from `write!`
168 //! correctly (propagating errors upward).
170 //! An example of implementing the formatting traits would look
176 //! use std::num::Float;
178 //! #[deriving(Show)]
179 //! struct Vector2D {
184 //! impl fmt::String for Vector2D {
185 //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
186 //! // The `f` value implements the `Writer` trait, which is what the
187 //! // write! macro is expecting. Note that this formatting ignores the
188 //! // various flags provided to format strings.
189 //! write!(f, "({}, {})", self.x, self.y)
193 //! // Different traits allow different forms of output of a type. The meaning
194 //! // of this format is to print the magnitude of a vector.
195 //! impl fmt::Binary for Vector2D {
196 //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
197 //! let magnitude = (self.x * self.x + self.y * self.y) as f64;
198 //! let magnitude = magnitude.sqrt();
200 //! // Respect the formatting flags by using the helper method
201 //! // `pad_integral` on the Formatter object. See the method documentation
202 //! // for details, and the function `pad` can be used to pad strings.
203 //! let decimals = f.precision().unwrap_or(3);
204 //! let string = f64::to_str_exact(magnitude, decimals);
205 //! f.pad_integral(true, "", string.as_slice())
210 //! let myvector = Vector2D { x: 3, y: 4 };
212 //! println!("{}", myvector); // => "(3, 4)"
213 //! println!("{:?}", myvector); // => "Vector2D {x: 3i, y:4i}"
214 //! println!("{:10.3b}", myvector); // => " 5.000"
218 //! #### fmt::String vs fmt::Show
220 //! These two formatting traits have distinct purposes:
222 //! - `fmt::String` implementations assert that the type can be faithfully
223 //! represented as a UTF-8 string at all times. It is **not** expected that
224 //! all types implement the `String` trait.
225 //! - `fmt::Show` implementations should be implemented for **all** public types.
226 //! Output will typically represent the internal state as faithfully as possible.
227 //! The purpose of the `Show` trait is to facilitate debugging Rust code. In
228 //! most cases, using `#[deriving(Show)]` is sufficient and recommended.
230 //! Some examples of the output from both traits:
233 //! assert_eq!(format!("{} {:?}", 3i32, 4i32), "3 4i32");
234 //! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'");
235 //! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\"");
238 //! ### Related macros
240 //! There are a number of related macros in the `format!` family. The ones that
241 //! are currently implemented are:
244 //! format! // described above
245 //! write! // first argument is a &mut io::Writer, the destination
246 //! writeln! // same as write but appends a newline
247 //! print! // the format string is printed to the standard output
248 //! println! // same as print but appends a newline
249 //! format_args! // described below.
254 //! This and `writeln` are two macros which are used to emit the format string
255 //! to a specified stream. This is used to prevent intermediate allocations of
256 //! format strings and instead directly write the output. Under the hood, this
257 //! function is actually invoking the `write` function defined in this module.
258 //! Example usage is:
261 //! # #![allow(unused_must_use)]
264 //! let mut w = Vec::new();
265 //! write!(&mut w as &mut io::Writer, "Hello {}!", "world");
270 //! This and `println` emit their output to stdout. Similarly to the `write!`
271 //! macro, the goal of these macros is to avoid intermediate allocations when
272 //! printing output. Example usage is:
275 //! print!("Hello {}!", "world");
276 //! println!("I have a newline {}", "character at the end");
279 //! #### `format_args!`
280 //! This is a curious macro which is used to safely pass around
281 //! an opaque object describing the format string. This object
282 //! does not require any heap allocations to create, and it only
283 //! references information on the stack. Under the hood, all of
284 //! the related macros are implemented in terms of this. First
285 //! off, some example usage is:
291 //! # #[allow(unused_must_use)]
293 //! fmt::format(format_args!("this returns {}", "String"));
295 //! let some_writer: &mut io::Writer = &mut io::stdout();
296 //! write!(some_writer, "{}", format_args!("print with a {}", "macro"));
298 //! fn my_fmt_fn(args: fmt::Arguments) {
299 //! write!(&mut io::stdout(), "{}", args);
301 //! my_fmt_fn(format_args!("or a {} too", "function"));
305 //! The result of the `format_args!` macro is a value of type `fmt::Arguments`.
306 //! This structure can then be passed to the `write` and `format` functions
307 //! inside this module in order to process the format string.
308 //! The goal of this macro is to even further prevent intermediate allocations
309 //! when dealing formatting strings.
311 //! For example, a logging library could use the standard formatting syntax, but
312 //! it would internally pass around this structure until it has been determined
313 //! where output should go to.
317 //! The syntax for the formatting language used is drawn from other languages,
318 //! so it should not be too alien. Arguments are formatted with python-like
319 //! syntax, meaning that arguments are surrounded by `{}` instead of the C-like
320 //! `%`. The actual grammar for the formatting syntax is:
323 //! format_string := <text> [ format <text> ] *
324 //! format := '{' [ argument ] [ ':' format_spec ] '}'
325 //! argument := integer | identifier
327 //! format_spec := [[fill]align][sign]['#'][0][width]['.' precision][type]
328 //! fill := character
329 //! align := '<' | '^' | '>'
330 //! sign := '+' | '-'
332 //! precision := count | '*'
333 //! type := identifier | ''
334 //! count := parameter | integer
335 //! parameter := integer '$'
338 //! ## Formatting Parameters
340 //! Each argument being formatted can be transformed by a number of formatting
341 //! parameters (corresponding to `format_spec` in the syntax above). These
342 //! parameters affect the string representation of what's being formatted. This
343 //! syntax draws heavily from Python's, so it may seem a bit familiar.
345 //! ### Fill/Alignment
347 //! The fill character is provided normally in conjunction with the `width`
348 //! parameter. This indicates that if the value being formatted is smaller than
349 //! `width` some extra characters will be printed around it. The extra
350 //! characters are specified by `fill`, and the alignment can be one of two
353 //! * `<` - the argument is left-aligned in `width` columns
354 //! * `^` - the argument is center-aligned in `width` columns
355 //! * `>` - the argument is right-aligned in `width` columns
359 //! These can all be interpreted as flags for a particular formatter.
361 //! * '+' - This is intended for numeric types and indicates that the sign
362 //! should always be printed. Positive signs are never printed by
363 //! default, and the negative sign is only printed by default for the
364 //! `Signed` trait. This flag indicates that the correct sign (+ or -)
365 //! should always be printed.
366 //! * '-' - Currently not used
367 //! * '#' - This flag is indicates that the "alternate" form of printing should
368 //! be used. By default, this only applies to the integer formatting
369 //! traits and performs like:
370 //! * `x` - precedes the argument with a "0x"
371 //! * `X` - precedes the argument with a "0x"
372 //! * `t` - precedes the argument with a "0b"
373 //! * `o` - precedes the argument with a "0o"
374 //! * '0' - This is used to indicate for integer formats that the padding should
375 //! both be done with a `0` character as well as be sign-aware. A format
376 //! like `{:08d}` would yield `00000001` for the integer `1`, while the
377 //! same format would yield `-0000001` for the integer `-1`. Notice that
378 //! the negative version has one fewer zero than the positive version.
382 //! This is a parameter for the "minimum width" that the format should take up.
383 //! If the value's string does not fill up this many characters, then the
384 //! padding specified by fill/alignment will be used to take up the required
387 //! The default fill/alignment for non-numerics is a space and left-aligned. The
388 //! defaults for numeric formatters is also a space but with right-alignment. If
389 //! the '0' flag is specified for numerics, then the implicit fill character is
392 //! The value for the width can also be provided as a `uint` in the list of
393 //! parameters by using the `2$` syntax indicating that the second argument is a
394 //! `uint` specifying the width.
398 //! For non-numeric types, this can be considered a "maximum width". If the
399 //! resulting string is longer than this width, then it is truncated down to
400 //! this many characters and only those are emitted.
402 //! For integral types, this has no meaning currently.
404 //! For floating-point types, this indicates how many digits after the decimal
405 //! point should be printed.
409 //! The literal characters `{` and `}` may be included in a string by preceding
410 //! them with the same character. For example, the `{` character is escaped with
411 //! `{{` and the `}` character is escaped with `}}`.
417 pub use core::fmt::{Formatter, Result, Writer, rt};
418 pub use core::fmt::{Show, String, Octal, Binary};
419 pub use core::fmt::{LowerHex, UpperHex, Pointer};
420 pub use core::fmt::{LowerExp, UpperExp};
421 pub use core::fmt::Error;
422 pub use core::fmt::{Argument, Arguments, write, radix, Radix, RadixFmt};
425 pub use core::fmt::{argument, argumentuint};
427 /// The format function takes a precompiled format string and a list of
428 /// arguments, to return the resulting formatted string.
432 /// * args - a structure of arguments generated via the `format_args!` macro.
439 /// let s = fmt::format(format_args!("Hello, {}!", "world"));
440 /// assert_eq!(s, "Hello, world!".to_string());
442 #[experimental = "this is an implementation detail of format! and should not \
444 pub fn format(args: Arguments) -> string::String {
445 let mut output = string::String::new();
446 let _ = write!(&mut output, "{}", args);