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
15 Utilities for formatting and printing strings
17 This module contains the runtime support for the `format!` syntax extension.
18 This macro is implemented in the compiler to emit calls to this module in order
19 to format arguments at runtime into strings and streams.
21 The functions contained in this module should not normally be used in everyday
22 use cases of `format!`. The assumptions made by these functions are unsafe for
23 all inputs, and the compiler performs a large amount of validation on the
24 arguments to `format!` in order to ensure safety at runtime. While it is
25 possible to call these functions directly, it is not recommended to do so in the
30 The `format!` macro is intended to be familiar to those coming from C's
31 printf/fprintf functions or Python's `str.format` function. In its current
32 revision, the `format!` macro returns a `String` type which is the result of
33 the formatting. In the future it will also be able to pass in a stream to
34 format arguments directly while performing minimal allocations.
36 Some examples of the `format!` extension are:
41 format!("Hello"); // => "Hello"
42 format!("Hello, {:s}!", "world"); // => "Hello, world!"
43 format!("The number is {:d}", 1i); // => "The number is 1"
44 format!("{:?}", (3i, 4i)); // => "(3, 4)"
45 format!("{value}", value=4i); // => "4"
46 format!("{} {}", 1i, 2i); // => "1 2"
50 From these, you can see that the first argument is a format string. It is
51 required by the compiler for this to be a string literal; it cannot be a
52 variable passed in (in order to perform validity checking). The compiler will
53 then parse the format string and determine if the list of arguments provided is
54 suitable to pass to this format string.
56 ### Positional parameters
58 Each formatting argument is allowed to specify which value argument it's
59 referencing, and if omitted it is assumed to be "the next argument". For
60 example, the format string `{} {} {}` would take three parameters, and they
61 would be formatted in the same order as they're given. The format string
62 `{2} {1} {0}`, however, would format arguments in reverse order.
64 Things can get a little tricky once you start intermingling the two types of
65 positional specifiers. The "next argument" specifier can be thought of as an
66 iterator over the argument. Each time a "next argument" specifier is seen, the
67 iterator advances. This leads to behavior like this:
70 format!("{1} {} {0} {}", 1i, 2i); // => "2 1 1 2"
73 The internal iterator over the argument has not been advanced by the time the
74 first `{}` is seen, so it prints the first argument. Then upon reaching the
75 second `{}`, the iterator has advanced forward to the second argument.
76 Essentially, parameters which explicitly name their argument do not affect
77 parameters which do not name an argument in terms of positional specifiers.
79 A format string is required to use all of its arguments, otherwise it is a
80 compile-time error. You may refer to the same argument more than once in the
81 format string, although it must always be referred to with the same type.
85 Rust itself does not have a Python-like equivalent of named parameters to a
86 function, but the `format!` macro is a syntax extension which allows it to
87 leverage named parameters. Named parameters are listed at the end of the
88 argument list and have the syntax:
91 identifier '=' expression
94 For example, the following `format!` expressions all use named argument:
99 format!("{argument}", argument = "test"); // => "test"
100 format!("{name} {}", 1i, name = 2i); // => "2 1"
101 format!("{a:s} {c:d} {b:?}", a="a", b=(), c=3i); // => "a 3 ()"
105 It is illegal to put positional parameters (those without names) after arguments
106 which have names. Like with positional parameters, it is illegal to provide
107 named parameters that are unused by the format string.
111 Each argument's type is dictated by the format string. It is a requirement that
112 every argument is only ever referred to by one type. For example, this is an
113 invalid format string:
119 This is invalid because the first argument is both referred to as an integer as
122 Because formatting is done via traits, there is no requirement that the
123 `d` format actually takes an `int`, but rather it simply requires a type which
124 ascribes to the `Signed` formatting trait. There are various parameters which do
125 require a particular type, however. Namely if the syntax `{:.*s}` is used, then
126 the number of characters to print from the string precedes the actual string and
127 must have the type `uint`. Although a `uint` can be printed with `{:u}`, it is
128 illegal to reference an argument as such. For example, this is another invalid
135 ### Formatting traits
137 When requesting that an argument be formatted with a particular type, you are
138 actually requesting that an argument ascribes to a particular trait. This allows
139 multiple actual types to be formatted via `{:d}` (like `i8` as well as `int`).
140 The current mapping of types to traits is:
159 > **Note**: The `Poly` formatting trait is provided by [libdebug](../../debug/)
160 > and is an experimental implementation that should not be relied upon. In order
161 > to use the `?` modifier, the libdebug crate must be linked against.
163 What this means is that any type of argument which implements the
164 `std::fmt::Binary` trait can then be formatted with `{:t}`. Implementations are
165 provided for these traits for a number of primitive types by the standard
166 library as well. If no format is specified (as in `{}` or `{:6}`), then the
167 format trait used is the `Show` trait. This is one of the more commonly
168 implemented traits when formatting a custom type.
170 When implementing a format trait for your own type, you will have to implement a
171 method of the signature:
175 # mod fmt { pub type Result = (); }
177 # trait SomeName<T> {
178 fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result;
182 Your type will be passed as `self` by-reference, and then the function should
183 emit output into the `f.buf` stream. It is up to each format trait
184 implementation to correctly adhere to the requested formatting parameters. The
185 values of these parameters will be listed in the fields of the `Formatter`
186 struct. In order to help with this, the `Formatter` struct also provides some
189 Additionally, the return value of this function is `fmt::Result` which is a
190 typedef to `Result<(), IoError>` (also known as `IoResult<()>`). Formatting
191 implementations should ensure that they return errors from `write!` correctly
192 (propagating errors upward).
194 An example of implementing the formatting traits would look
206 impl fmt::Show for Vector2D {
207 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
208 // The `f` value implements the `Writer` trait, which is what the
209 // write! macro is expecting. Note that this formatting ignores the
210 // various flags provided to format strings.
211 write!(f, "({}, {})", self.x, self.y)
215 // Different traits allow different forms of output of a type. The meaning of
216 // this format is to print the magnitude of a vector.
217 impl fmt::Binary for Vector2D {
218 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
219 let magnitude = (self.x * self.x + self.y * self.y) as f64;
220 let magnitude = magnitude.sqrt();
222 // Respect the formatting flags by using the helper method
223 // `pad_integral` on the Formatter object. See the method documentation
224 // for details, and the function `pad` can be used to pad strings.
225 let decimals = f.precision.unwrap_or(3);
226 let string = f64::to_str_exact(magnitude, decimals);
227 f.pad_integral(true, "", string.as_bytes())
232 let myvector = Vector2D { x: 3, y: 4 };
234 println!("{}", myvector); // => "(3, 4)"
235 println!("{:10.3t}", myvector); // => " 5.000"
241 There are a number of related macros in the `format!` family. The ones that are
242 currently implemented are:
245 format! // described above
246 write! // first argument is a &mut io::Writer, the destination
247 writeln! // same as write but appends a newline
248 print! // the format string is printed to the standard output
249 println! // same as print but appends a newline
250 format_args! // described below.
256 This and `writeln` are two macros which are used to emit the format string to a
257 specified stream. This is used to prevent intermediate allocations of format
258 strings and instead directly write the output. Under the hood, this function is
259 actually invoking the `write` function defined in this module. Example usage is:
262 # #![allow(unused_must_use)]
265 let mut w = io::MemWriter::new();
266 write!(&mut w as &mut io::Writer, "Hello {}!", "world");
271 This and `println` emit their output to stdout. Similarly to the `write!` macro,
272 the goal of these macros is to avoid intermediate allocations when printing
273 output. Example usage is:
276 print!("Hello {}!", "world");
277 println!("I have a newline {}", "character at the end");
281 This is a curious macro which is used to safely pass around
282 an opaque object describing the format string. This object
283 does not require any heap allocations to create, and it only
284 references information on the stack. Under the hood, all of
285 the related macros are implemented in terms of this. First
286 off, some example usage is:
292 # #[allow(unused_must_use)]
294 format_args!(fmt::format, "this returns {}", "String");
296 let some_writer: &mut io::Writer = &mut io::stdout();
297 format_args!(|args| { write!(some_writer, "{}", args) }, "print with a {}", "closure");
299 fn my_fmt_fn(args: &fmt::Arguments) {
300 write!(&mut io::stdout(), "{}", args);
302 format_args!(my_fmt_fn, "or a {} too", "function");
306 The first argument of the `format_args!` macro is a function (or closure) which
307 takes one argument of type `&fmt::Arguments`. This structure can then be
308 passed to the `write` and `format` functions inside this module in order to
309 process the format string. The goal of this macro is to even further prevent
310 intermediate allocations when dealing formatting strings.
312 For example, a logging library could use the standard formatting syntax, but it
313 would internally pass around this structure until it has been determined where
316 It is unsafe to programmatically create an instance of `fmt::Arguments` because
317 the operations performed when executing a format string require the compile-time
318 checks provided by the compiler. The `format_args!` macro is the only method of
319 safely creating these structures, but they can be unsafely created with the
320 constructor provided.
324 The syntax for the formatting language used is drawn from other languages, so it
325 should not be too alien. Arguments are formatted with python-like syntax,
326 meaning that arguments are surrounded by `{}` instead of the C-like `%`. The
327 actual grammar for the formatting syntax is:
330 format_string := <text> [ format <text> ] *
331 format := '{' [ argument ] [ ':' format_spec ] '}'
332 argument := integer | identifier
334 format_spec := [[fill]align][sign]['#'][0][width]['.' precision][type]
339 precision := count | '*'
340 type := identifier | ''
341 count := parameter | integer
342 parameter := integer '$'
345 ## Formatting Parameters
347 Each argument being formatted can be transformed by a number of formatting
348 parameters (corresponding to `format_spec` in the syntax above). These
349 parameters affect the string representation of what's being formatted. This
350 syntax draws heavily from Python's, so it may seem a bit familiar.
354 The fill character is provided normally in conjunction with the `width`
355 parameter. This indicates that if the value being formatted is smaller than
356 `width` some extra characters will be printed around it. The extra characters
357 are specified by `fill`, and the alignment can be one of two options:
359 * `<` - the argument is left-aligned in `width` columns
360 * `>` - the argument is right-aligned in `width` columns
364 These can all be interpreted as flags for a particular formatter.
366 * '+' - This is intended for numeric types and indicates that the sign should
367 always be printed. Positive signs are never printed by default, and the
368 negative sign is only printed by default for the `Signed` trait. This
369 flag indicates that the correct sign (+ or -) should always be printed.
370 * '-' - Currently not used
371 * '#' - This flag is indicates that the "alternate" form of printing should be
372 used. By default, this only applies to the integer formatting traits and
374 * `x` - precedes the argument with a "0x"
375 * `X` - precedes the argument with a "0x"
376 * `t` - precedes the argument with a "0b"
377 * `o` - precedes the argument with a "0o"
378 * '0' - This is used to indicate for integer formats that the padding should
379 both be done with a `0` character as well as be sign-aware. A format
380 like `{:08d}` would yield `00000001` for the integer `1`, while the same
381 format would yield `-0000001` for the integer `-1`. Notice that the
382 negative version has one fewer zero than the positive version.
386 This is a parameter for the "minimum width" that the format should take up. If
387 the value's string does not fill up this many characters, then the padding
388 specified by fill/alignment will be used to take up the required space.
390 The default fill/alignment for non-numerics is a space and left-aligned. The
391 defaults for numeric formatters is also a space but with right-alignment. If the
392 '0' flag is specified for numerics, then the implicit fill character is '0'.
394 The value for the width can also be provided as a `uint` in the list of
395 parameters by using the `2$` syntax indicating that the second argument is a
396 `uint` specifying the width.
400 For non-numeric types, this can be considered a "maximum width". If the
401 resulting string is longer than this width, then it is truncated down to this
402 many characters and only those are emitted.
404 For integral types, this has no meaning currently.
406 For floating-point types, this indicates how many digits after the decimal point
411 The literal characters `{` and `}` may be included in a string by preceding them
412 with the same character. For example, the `{` character is escaped with `{{` and
413 the `}` character is escaped with `}}`.
421 use result::{Ok, Err};
424 pub use core::fmt::{Formatter, Result, FormatWriter, rt};
425 pub use core::fmt::{Show, Bool, Char, Signed, Unsigned, Octal, Binary};
426 pub use core::fmt::{LowerHex, UpperHex, String, Pointer};
427 pub use core::fmt::{Float, LowerExp, UpperExp};
428 pub use core::fmt::{FormatError, WriteError};
429 pub use core::fmt::{Argument, Arguments, write, radix, Radix, RadixFmt};
432 pub use core::fmt::{argument, argumentstr, argumentuint};
434 pub use core::fmt::{secret_show, secret_string, secret_unsigned};
436 pub use core::fmt::{secret_signed, secret_lower_hex, secret_upper_hex};
438 pub use core::fmt::{secret_bool, secret_char, secret_octal, secret_binary};
440 pub use core::fmt::{secret_float, secret_upper_exp, secret_lower_exp};
442 pub use core::fmt::{secret_pointer};
444 /// The format function takes a precompiled format string and a list of
445 /// arguments, to return the resulting formatted string.
449 /// * args - a structure of arguments generated via the `format_args!` macro.
450 /// Because this structure can only be safely generated at
451 /// compile-time, this function is safe.
458 /// let s = format_args!(fmt::format, "Hello, {}!", "world");
459 /// assert_eq!(s, "Hello, world!".to_string());
461 pub fn format(args: &Arguments) -> string::String{
462 let mut output = io::MemWriter::new();
463 let _ = write!(&mut output, "{}", args);
464 string::String::from_utf8(output.unwrap()).unwrap()
467 impl<'a> Writer for Formatter<'a> {
468 fn write(&mut self, b: &[u8]) -> io::IoResult<()> {
469 match (*self).write(b) {
471 Err(WriteError) => Err(io::standard_error(io::OtherIoError))