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:
30 //! format!("Hello"); // => "Hello"
31 //! format!("Hello, {}!", "world"); // => "Hello, world!"
32 //! format!("The number is {}", 1i); // => "The number is 1"
33 //! format!("{:?}", (3i, 4i)); // => "(3i, 4i)"
34 //! format!("{value}", value=4i); // => "4"
35 //! format!("{} {}", 1i, 2u); // => "1 2"
38 //! From these, you can see that the first argument is a format string. It is
39 //! required by the compiler for this to be a string literal; it cannot be a
40 //! variable passed in (in order to perform validity checking). The compiler
41 //! will then parse the format string and determine if the list of arguments
42 //! provided is suitable to pass to this format string.
44 //! ### Positional parameters
46 //! Each formatting argument is allowed to specify which value argument it's
47 //! referencing, and if omitted it is assumed to be "the next argument". For
48 //! example, the format string `{} {} {}` would take three parameters, and they
49 //! would be formatted in the same order as they're given. The format string
50 //! `{2} {1} {0}`, however, would format arguments in reverse order.
52 //! Things can get a little tricky once you start intermingling the two types of
53 //! positional specifiers. The "next argument" specifier can be thought of as an
54 //! iterator over the argument. Each time a "next argument" specifier is seen,
55 //! the iterator advances. This leads to behavior like this:
58 //! format!("{1} {} {0} {}", 1i, 2i); // => "2 1 1 2"
61 //! The internal iterator over the argument has not been advanced by the time
62 //! the first `{}` is seen, so it prints the first argument. Then upon reaching
63 //! the second `{}`, the iterator has advanced forward to the second argument.
64 //! Essentially, parameters which explicitly name their argument do not affect
65 //! parameters which do not name an argument in terms of positional specifiers.
67 //! A format string is required to use all of its arguments, otherwise it is a
68 //! compile-time error. You may refer to the same argument more than once in the
69 //! format string, although it must always be referred to with the same type.
71 //! ### Named parameters
73 //! Rust itself does not have a Python-like equivalent of named parameters to a
74 //! function, but the `format!` macro is a syntax extension which allows it to
75 //! leverage named parameters. Named parameters are listed at the end of the
76 //! argument list and have the syntax:
79 //! identifier '=' expression
82 //! For example, the following `format!` expressions all use named argument:
85 //! format!("{argument}", argument = "test"); // => "test"
86 //! format!("{name} {}", 1i, name = 2i); // => "2 1"
87 //! format!("{a} {c} {b}", a="a", b='b', c=3i); // => "a 3 b"
90 //! It is illegal to put positional parameters (those without names) after
91 //! arguments which have names. Like with positional parameters, it is illegal
92 //! to provide named parameters that are unused by the format string.
94 //! ### Argument types
96 //! Each argument's type is dictated by the format string. It is a requirement
97 //! that every argument is only ever referred to by one type. For example, this
98 //! is an invalid format string:
104 //! This is invalid because the first argument is both referred to as a
105 //! hexadecimal as well as an
108 //! There are various parameters which do require a particular type, however.
109 //! Namely if the syntax `{:.*}` is used, then the number of characters to print
110 //! precedes the actual object being formatted, and the number of characters
111 //! must have the type `uint`. Although a `uint` can be printed with `{}`, it is
112 //! illegal to reference an argument as such. For example this is another
113 //! invalid format string:
119 //! ### Formatting traits
121 //! When requesting that an argument be formatted with a particular type, you
122 //! are actually requesting that an argument ascribes to a particular trait.
123 //! This allows multiple actual types to be formatted via `{:x}` (like `i8` as
124 //! well as `int`). The current mapping of types to traits is:
126 //! * *nothing* ⇒ `Display`
129 //! * `x` ⇒ `LowerHex`
130 //! * `X` ⇒ `UpperHex`
131 //! * `p` ⇒ `Pointer`
133 //! * `e` ⇒ `LowerExp`
134 //! * `E` ⇒ `UpperExp`
136 //! What this means is that any type of argument which implements the
137 //! `std::fmt::Binary` trait can then be formatted with `{:b}`. Implementations
138 //! are provided for these traits for a number of primitive types by the
139 //! standard library as well. If no format is specified (as in `{}` or `{:6}`),
140 //! then the format trait used is the `Display` trait.
142 //! When implementing a format trait for your own type, you will have to
143 //! implement a method of the signature:
147 //! # struct Foo; // our custom type
148 //! # impl fmt::Display for Foo {
149 //! fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result {
150 //! # write!(f, "testing, testing")
154 //! Your type will be passed as `self` by-reference, and then the function
155 //! should emit output into the `f.buf` stream. It is up to each format trait
156 //! implementation to correctly adhere to the requested formatting parameters.
157 //! The values of these parameters will be listed in the fields of the
158 //! `Formatter` struct. In order to help with this, the `Formatter` struct also
159 //! provides some helper methods.
161 //! Additionally, the return value of this function is `fmt::Result` which is a
162 //! typedef to `Result<(), IoError>` (also known as `IoResult<()>`). Formatting
163 //! implementations should ensure that they return errors from `write!`
164 //! correctly (propagating errors upward).
166 //! An example of implementing the formatting traits would look
172 //! use std::num::Float;
175 //! struct Vector2D {
180 //! impl fmt::Display for Vector2D {
181 //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
182 //! // The `f` value implements the `Writer` trait, which is what the
183 //! // write! macro is expecting. Note that this formatting ignores the
184 //! // various flags provided to format strings.
185 //! write!(f, "({}, {})", self.x, self.y)
189 //! // Different traits allow different forms of output of a type. The meaning
190 //! // of this format is to print the magnitude of a vector.
191 //! impl fmt::Binary for Vector2D {
192 //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
193 //! let magnitude = (self.x * self.x + self.y * self.y) as f64;
194 //! let magnitude = magnitude.sqrt();
196 //! // Respect the formatting flags by using the helper method
197 //! // `pad_integral` on the Formatter object. See the method documentation
198 //! // for details, and the function `pad` can be used to pad strings.
199 //! let decimals = f.precision().unwrap_or(3);
200 //! let string = f64::to_str_exact(magnitude, decimals);
201 //! f.pad_integral(true, "", string.as_slice())
206 //! let myvector = Vector2D { x: 3, y: 4 };
208 //! println!("{}", myvector); // => "(3, 4)"
209 //! println!("{:?}", myvector); // => "Vector2D {x: 3i, y:4i}"
210 //! println!("{:10.3b}", myvector); // => " 5.000"
214 //! #### fmt::Display vs fmt::Debug
216 //! These two formatting traits have distinct purposes:
218 //! - `fmt::Display` implementations assert that the type can be faithfully
219 //! represented as a UTF-8 string at all times. It is **not** expected that
220 //! all types implement the `Display` trait.
221 //! - `fmt::Debug` implementations should be implemented for **all** public types.
222 //! Output will typically represent the internal state as faithfully as possible.
223 //! The purpose of the `Debug` trait is to facilitate debugging Rust code. In
224 //! most cases, using `#[derive(Debug)]` is sufficient and recommended.
226 //! Some examples of the output from both traits:
229 //! assert_eq!(format!("{} {:?}", 3i32, 4i32), "3 4");
230 //! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'");
231 //! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\"");
234 //! ### Related macros
236 //! There are a number of related macros in the `format!` family. The ones that
237 //! are currently implemented are:
240 //! format! // described above
241 //! write! // first argument is a &mut old_io::Writer, the destination
242 //! writeln! // same as write but appends a newline
243 //! print! // the format string is printed to the standard output
244 //! println! // same as print but appends a newline
245 //! format_args! // described below.
250 //! This and `writeln` are two macros which are used to emit the format string
251 //! to a specified stream. This is used to prevent intermediate allocations of
252 //! format strings and instead directly write the output. Under the hood, this
253 //! function is actually invoking the `write` function defined in this module.
254 //! Example usage is:
257 //! # #![allow(unused_must_use)]
258 //! let mut w = Vec::new();
259 //! write!(&mut w, "Hello {}!", "world");
264 //! This and `println` emit their output to stdout. Similarly to the `write!`
265 //! macro, the goal of these macros is to avoid intermediate allocations when
266 //! printing output. Example usage is:
269 //! print!("Hello {}!", "world");
270 //! println!("I have a newline {}", "character at the end");
273 //! #### `format_args!`
274 //! This is a curious macro which is used to safely pass around
275 //! an opaque object describing the format string. This object
276 //! does not require any heap allocations to create, and it only
277 //! references information on the stack. Under the hood, all of
278 //! the related macros are implemented in terms of this. First
279 //! off, some example usage is:
285 //! fmt::format(format_args!("this returns {}", "String"));
287 //! let mut some_writer = old_io::stdout();
288 //! write!(&mut some_writer, "{}", format_args!("print with a {}", "macro"));
290 //! fn my_fmt_fn(args: fmt::Arguments) {
291 //! write!(&mut old_io::stdout(), "{}", args);
293 //! my_fmt_fn(format_args!("or a {} too", "function"));
296 //! The result of the `format_args!` macro is a value of type `fmt::Arguments`.
297 //! This structure can then be passed to the `write` and `format` functions
298 //! inside this module in order to process the format string.
299 //! The goal of this macro is to even further prevent intermediate allocations
300 //! when dealing formatting strings.
302 //! For example, a logging library could use the standard formatting syntax, but
303 //! it would internally pass around this structure until it has been determined
304 //! where output should go to.
308 //! The syntax for the formatting language used is drawn from other languages,
309 //! so it should not be too alien. Arguments are formatted with python-like
310 //! syntax, meaning that arguments are surrounded by `{}` instead of the C-like
311 //! `%`. The actual grammar for the formatting syntax is:
314 //! format_string := <text> [ format <text> ] *
315 //! format := '{' [ argument ] [ ':' format_spec ] '}'
316 //! argument := integer | identifier
318 //! format_spec := [[fill]align][sign]['#'][0][width]['.' precision][type]
319 //! fill := character
320 //! align := '<' | '^' | '>'
321 //! sign := '+' | '-'
323 //! precision := count | '*'
324 //! type := identifier | ''
325 //! count := parameter | integer
326 //! parameter := integer '$'
329 //! ## Formatting Parameters
331 //! Each argument being formatted can be transformed by a number of formatting
332 //! parameters (corresponding to `format_spec` in the syntax above). These
333 //! parameters affect the string representation of what's being formatted. This
334 //! syntax draws heavily from Python's, so it may seem a bit familiar.
336 //! ### Fill/Alignment
338 //! The fill character is provided normally in conjunction with the `width`
339 //! parameter. This indicates that if the value being formatted is smaller than
340 //! `width` some extra characters will be printed around it. The extra
341 //! characters are specified by `fill`, and the alignment can be one of two
344 //! * `<` - the argument is left-aligned in `width` columns
345 //! * `^` - the argument is center-aligned in `width` columns
346 //! * `>` - the argument is right-aligned in `width` columns
350 //! These can all be interpreted as flags for a particular formatter.
352 //! * '+' - This is intended for numeric types and indicates that the sign
353 //! should always be printed. Positive signs are never printed by
354 //! default, and the negative sign is only printed by default for the
355 //! `Signed` trait. This flag indicates that the correct sign (+ or -)
356 //! should always be printed.
357 //! * '-' - Currently not used
358 //! * '#' - This flag is indicates that the "alternate" form of printing should
359 //! be used. By default, this only applies to the integer formatting
360 //! traits and performs like:
361 //! * `x` - precedes the argument with a "0x"
362 //! * `X` - precedes the argument with a "0x"
363 //! * `t` - precedes the argument with a "0b"
364 //! * `o` - precedes the argument with a "0o"
365 //! * '0' - This is used to indicate for integer formats that the padding should
366 //! both be done with a `0` character as well as be sign-aware. A format
367 //! like `{:08d}` would yield `00000001` for the integer `1`, while the
368 //! same format would yield `-0000001` for the integer `-1`. Notice that
369 //! the negative version has one fewer zero than the positive version.
373 //! This is a parameter for the "minimum width" that the format should take up.
374 //! If the value's string does not fill up this many characters, then the
375 //! padding specified by fill/alignment will be used to take up the required
378 //! The default fill/alignment for non-numerics is a space and left-aligned. The
379 //! defaults for numeric formatters is also a space but with right-alignment. If
380 //! the '0' flag is specified for numerics, then the implicit fill character is
383 //! The value for the width can also be provided as a `uint` in the list of
384 //! parameters by using the `2$` syntax indicating that the second argument is a
385 //! `uint` specifying the width.
389 //! For non-numeric types, this can be considered a "maximum width". If the
390 //! resulting string is longer than this width, then it is truncated down to
391 //! this many characters and only those are emitted.
393 //! For integral types, this has no meaning currently.
395 //! For floating-point types, this indicates how many digits after the decimal
396 //! point should be printed.
400 //! The literal characters `{` and `}` may be included in a string by preceding
401 //! them with the same character. For example, the `{` character is escaped with
402 //! `{{` and the `}` character is escaped with `}}`.
404 #![unstable(feature = "std_misc")]
408 pub use core::fmt::{Formatter, Result, Writer, rt};
409 pub use core::fmt::{Show, String, Octal, Binary};
410 pub use core::fmt::{Display, Debug};
411 pub use core::fmt::{LowerHex, UpperHex, Pointer};
412 pub use core::fmt::{LowerExp, UpperExp};
413 pub use core::fmt::Error;
414 pub use core::fmt::{Argument, Arguments, write, radix, Radix, RadixFmt};
417 pub use core::fmt::{argument, argumentuint};
419 /// The format function takes a precompiled format string and a list of
420 /// arguments, to return the resulting formatted string.
424 /// * args - a structure of arguments generated via the `format_args!` macro.
431 /// let s = fmt::format(format_args!("Hello, {}!", "world"));
432 /// assert_eq!(s, "Hello, world!".to_string());
434 #[unstable(feature = "std_misc",
435 reason = "this is an implementation detail of format! and should not \
436 be called directly")]
437 pub fn format(args: Arguments) -> string::String {
438 let mut output = string::String::new();
439 let _ = write!(&mut output, "{}", args);