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.
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 order
17 to format arguments at runtime into strings and streams.
19 The functions contained in this module should not normally be used in everyday
20 use cases of `format!`. The assumptions made by these functions are unsafe for
21 all inputs, and the compiler performs a large amount of validation on the
22 arguments to `format!` in order to ensure safety at runtime. While it is
23 possible to call these functions directly, it is not recommended to do so in the
28 The `format!` macro is intended to be familiar to those coming from C's
29 printf/fprintf functions or Python's `str.format` function. In its current
30 revision, the `format!` macro returns a `String` type which is the result of
31 the formatting. In the future it will also be able to pass in a stream to
32 format arguments directly while performing minimal allocations.
34 Some examples of the `format!` extension are:
39 format!("Hello"); // => "Hello"
40 format!("Hello, {:s}!", "world"); // => "Hello, world!"
41 format!("The number is {:d}", 1); // => "The number is 1"
42 format!("{:?}", (3, 4)); // => "(3, 4)"
43 format!("{value}", value=4); // => "4"
44 format!("{} {}", 1, 2); // => "1 2"
48 From these, you can see that the first argument is a format string. It is
49 required by the compiler for this to be a string literal; it cannot be a
50 variable passed in (in order to perform validity checking). The compiler will
51 then parse the format string and determine if the list of arguments provided is
52 suitable to pass to this format string.
54 ### Positional parameters
56 Each formatting argument is allowed to specify which value argument it's
57 referencing, and if omitted it is assumed to be "the next argument". For
58 example, the format string `{} {} {}` would take three parameters, and they
59 would be formatted in the same order as they're given. The format string
60 `{2} {1} {0}`, however, would format arguments in reverse order.
62 Things can get a little tricky once you start intermingling the two types of
63 positional specifiers. The "next argument" specifier can be thought of as an
64 iterator over the argument. Each time a "next argument" specifier is seen, the
65 iterator advances. This leads to behavior like this:
68 format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2"
71 The internal iterator over the argument has not been advanced by the time the
72 first `{}` is seen, so it prints the first argument. Then upon reaching the
73 second `{}`, the iterator has advanced forward to the second argument.
74 Essentially, parameters which explicitly name their argument do not affect
75 parameters which do not name an argument in terms of positional specifiers.
77 A format string is required to use all of its arguments, otherwise it is a
78 compile-time error. You may refer to the same argument more than once in the
79 format string, although it must always be referred to with the same type.
83 Rust itself does not have a Python-like equivalent of named parameters to a
84 function, but the `format!` macro is a syntax extension which allows it to
85 leverage named parameters. Named parameters are listed at the end of the
86 argument list and have the syntax:
89 identifier '=' expression
92 For example, the following `format!` expressions all use named argument:
97 format!("{argument}", argument = "test"); // => "test"
98 format!("{name} {}", 1, name = 2); // => "2 1"
99 format!("{a:s} {c:d} {b:?}", a="a", b=(), c=3); // => "a 3 ()"
103 It is illegal to put positional parameters (those without names) after arguments
104 which have names. Like positional parameters, it is illegal to provided named
105 parameters that are unused by the format string.
109 Each argument's type is dictated by the format string. It is a requirement that
110 every argument is only ever referred to by one type. For example, this is an
111 invalid format string:
117 This is invalid because the first argument is both referred to as an integer as
120 Because formatting is done via traits, there is no requirement that the
121 `d` format actually takes an `int`, but rather it simply requires a type which
122 ascribes to the `Signed` formatting trait. There are various parameters which do
123 require a particular type, however. Namely if the syntax `{:.*s}` is used, then
124 the number of characters to print from the string precedes the actual string and
125 must have the type `uint`. Although a `uint` can be printed with `{:u}`, it is
126 illegal to reference an argument as such. For example, this is another invalid
133 ### Formatting traits
135 When requesting that an argument be formatted with a particular type, you are
136 actually requesting that an argument ascribes to a particular trait. This allows
137 multiple actual types to be formatted via `{:d}` (like `i8` as well as `int`).
138 The current mapping of types to traits is:
157 > **Note**: The `Poly` formatting trait is provided by [libdebug](../../debug/)
158 > and is an experimental implementation that should not be relied upon. In order
159 > to use the `?` modifier, the libdebug crate must be linked against.
161 What this means is that any type of argument which implements the
162 `std::fmt::Binary` trait can then be formatted with `{:t}`. Implementations are
163 provided for these traits for a number of primitive types by the standard
164 library as well. If no format is specified (as in `{}` or `{:6}`), then the
165 format trait used is the `Show` trait. This is one of the more commonly
166 implemented traits when formatting a custom type.
168 When implementing a format trait for your own type, you will have to implement a
169 method of the signature:
173 # mod fmt { pub type Result = (); }
175 # trait SomeName<T> {
176 fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result;
180 Your type will be passed as `self` by-reference, and then the function should
181 emit output into the `f.buf` stream. It is up to each format trait
182 implementation to correctly adhere to the requested formatting parameters. The
183 values of these parameters will be listed in the fields of the `Formatter`
184 struct. In order to help with this, the `Formatter` struct also provides some
187 Additionally, the return value of this function is `fmt::Result` which is a
188 typedef to `Result<(), IoError>` (also known as `IoError<()>`). Formatting
189 implementations should ensure that they return errors from `write!` correctly
190 (propagating errors upward).
192 An example of implementing the formatting traits would look
204 impl fmt::Show for Vector2D {
205 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
206 // The `f` value implements the `Writer` trait, which is what the
207 // write! macro is expecting. Note that this formatting ignores the
208 // various flags provided to format strings.
209 write!(f, "({}, {})", self.x, self.y)
213 // Different traits allow different forms of output of a type. The meaning of
214 // this format is to print the magnitude of a vector.
215 impl fmt::Binary for Vector2D {
216 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
217 let magnitude = (self.x * self.x + self.y * self.y) as f64;
218 let magnitude = magnitude.sqrt();
220 // Respect the formatting flags by using the helper method
221 // `pad_integral` on the Formatter object. See the method documentation
222 // for details, and the function `pad` can be used to pad strings.
223 let decimals = f.precision.unwrap_or(3);
224 let string = f64::to_str_exact(magnitude, decimals);
225 f.pad_integral(true, "", string.as_bytes())
230 let myvector = Vector2D { x: 3, y: 4 };
232 println!("{}", myvector); // => "(3, 4)"
233 println!("{:10.3t}", myvector); // => " 5.000"
239 There are a number of related macros in the `format!` family. The ones that are
240 currently implemented are:
243 format! // described above
244 write! // first argument is a &mut io::Writer, the destination
245 writeln! // same as write but appends a newline
246 print! // the format string is printed to the standard output
247 println! // same as print but appends a newline
248 format_args! // described below.
254 This and `writeln` are two macros which are used to emit the format string to a
255 specified stream. This is used to prevent intermediate allocations of format
256 strings and instead directly write the output. Under the hood, this function is
257 actually invoking the `write` function defined in this module. Example usage is:
260 # #![allow(unused_must_use)]
263 let mut w = io::MemWriter::new();
264 write!(&mut w as &mut io::Writer, "Hello {}!", "world");
269 This and `println` emit their output to stdout. Similarly to the `write!` macro,
270 the goal of these macros is to avoid intermediate allocations when printing
271 output. Example usage is:
274 print!("Hello {}!", "world");
275 println!("I have a newline {}", "character at the end");
279 This is a curious macro which is used to safely pass around
280 an opaque object describing the format string. This object
281 does not require any heap allocations to create, and it only
282 references information on the stack. Under the hood, all of
283 the related macros are implemented in terms of this. First
284 off, some example usage is:
290 # #[allow(unused_must_use)]
292 format_args!(fmt::format, "this returns {}", "String");
294 let some_writer: &mut io::Writer = &mut io::stdout();
295 format_args!(|args| { write!(some_writer, "{}", args) }, "print with a {}", "closure");
297 fn my_fmt_fn(args: &fmt::Arguments) {
298 write!(&mut io::stdout(), "{}", args);
300 format_args!(my_fmt_fn, "or a {} too", "function");
304 The first argument of the `format_args!` macro is a function (or closure) which
305 takes one argument of type `&fmt::Arguments`. This structure can then be
306 passed to the `write` and `format` functions inside this module in order to
307 process the format string. The goal of this macro is to even further prevent
308 intermediate allocations when dealing formatting strings.
310 For example, a logging library could use the standard formatting syntax, but it
311 would internally pass around this structure until it has been determined where
314 It is unsafe to programmatically create an instance of `fmt::Arguments` because
315 the operations performed when executing a format string require the compile-time
316 checks provided by the compiler. The `format_args!` macro is the only method of
317 safely creating these structures, but they can be unsafely created with the
318 constructor provided.
320 ## Internationalization
322 The formatting syntax supported by the `format!` extension supports
323 internationalization by providing "methods" which execute various different
324 outputs depending on the input. The syntax and methods provided are similar to
325 other internationalization systems, so again nothing should seem alien.
326 Currently two methods are supported by this extension: "select" and "plural".
328 Each method will execute one of a number of clauses, and then the value of the
329 clause will become what's the result of the argument's format. Inside of the
330 cases, nested argument strings may be provided, but all formatting arguments
331 must not be done through implicit positional means. All arguments inside of each
332 case of a method must be explicitly selected by their name or their integer
335 Furthermore, whenever a case is running, the special character `#` can be used
336 to reference the string value of the argument which was selected upon. As an
340 format!("{0, select, other{#}}", "hello"); // => "hello"
343 This example is the equivalent of `{0:s}` essentially.
347 The select method is a switch over a `&str` parameter, and the parameter *must*
348 be of the type `&str`. An example of the syntax is:
351 {0, select, male{...} female{...} other{...}}
354 Breaking this down, the `0`-th argument is selected upon with the `select`
355 method, and then a number of cases follow. Each case is preceded by an
356 identifier which is the match-clause to execute the given arm. In this case,
357 there are two explicit cases, `male` and `female`. The case will be executed if
358 the string argument provided is an exact match to the case selected.
360 The `other` case is also a required case for all `select` methods. This arm will
361 be executed if none of the other arms matched the word being selected over.
365 The plural method is a switch statement over a `uint` parameter, and the
366 parameter *must* be a `uint`. A plural method in its full glory can be specified
370 {0, plural, offset=1 =1{...} two{...} many{...} other{...}}
373 To break this down, the first `0` indicates that this method is selecting over
374 the value of the first positional parameter to the format string. Next, the
375 `plural` method is being executed. An optionally-supplied `offset` is then given
376 which indicates a number to subtract from argument `0` when matching. This is
377 then followed by a list of cases.
379 Each case is allowed to supply a specific value to match upon with the syntax
380 `=N`. This case is executed if the value at argument `0` matches N exactly,
381 without taking the offset into account. A case may also be specified by one of
382 five keywords: `zero`, `one`, `two`, `few`, and `many`. These cases are matched
383 on after argument `0` has the offset taken into account. Currently the
384 definitions of `many` and `few` are hardcoded, but they are in theory defined by
387 Finally, all `plural` methods must have an `other` case supplied which will be
388 executed if none of the other cases match.
392 The syntax for the formatting language used is drawn from other languages, so it
393 should not be too alien. Arguments are formatted with python-like syntax,
394 meaning that arguments are surrounded by `{}` instead of the C-like `%`. The
395 actual grammar for the formatting syntax is:
398 format_string := <text> [ format <text> ] *
399 format := '{' [ argument ] [ ':' format_spec ] [ ',' function_spec ] '}'
400 argument := integer | identifier
402 format_spec := [[fill]align][sign]['#'][0][width]['.' precision][type]
407 precision := count | '*'
408 type := identifier | ''
409 count := parameter | integer
410 parameter := integer '$'
412 function_spec := plural | select
413 select := 'select' ',' ( identifier arm ) *
414 plural := 'plural' ',' [ 'offset:' integer ] ( selector arm ) *
415 selector := '=' integer | keyword
416 keyword := 'zero' | 'one' | 'two' | 'few' | 'many' | 'other'
417 arm := '{' format_string '}'
420 ## Formatting Parameters
422 Each argument being formatted can be transformed by a number of formatting
423 parameters (corresponding to `format_spec` in the syntax above). These
424 parameters affect the string representation of what's being formatted. This
425 syntax draws heavily from Python's, so it may seem a bit familiar.
429 The fill character is provided normally in conjunction with the `width`
430 parameter. This indicates that if the value being formatted is smaller than
431 `width` some extra characters will be printed around it. The extra characters
432 are specified by `fill`, and the alignment can be one of two options:
434 * `<` - the argument is left-aligned in `width` columns
435 * `>` - the argument is right-aligned in `width` columns
439 These can all be interpreted as flags for a particular formatter.
441 * '+' - This is intended for numeric types and indicates that the sign should
442 always be printed. Positive signs are never printed by default, and the
443 negative sign is only printed by default for the `Signed` trait. This
444 flag indicates that the correct sign (+ or -) should always be printed.
445 * '-' - Currently not used
446 * '#' - This flag is indicates that the "alternate" form of printing should be
447 used. By default, this only applies to the integer formatting traits and
449 * `x` - precedes the argument with a "0x"
450 * `X` - precedes the argument with a "0x"
451 * `t` - precedes the argument with a "0b"
452 * `o` - precedes the argument with a "0o"
453 * '0' - This is used to indicate for integer formats that the padding should
454 both be done with a `0` character as well as be sign-aware. A format
455 like `{:08d}` would yield `00000001` for the integer `1`, while the same
456 format would yield `-0000001` for the integer `-1`. Notice that the
457 negative version has one fewer zero than the positive version.
461 This is a parameter for the "minimum width" that the format should take up. If
462 the value's string does not fill up this many characters, then the padding
463 specified by fill/alignment will be used to take up the required space.
465 The default fill/alignment for non-numerics is a space and left-aligned. The
466 defaults for numeric formatters is also a space but with right-alignment. If the
467 '0' flag is specified for numerics, then the implicit fill character is '0'.
469 The value for the width can also be provided as a `uint` in the list of
470 parameters by using the `2$` syntax indicating that the second argument is a
471 `uint` specifying the width.
475 For non-numeric types, this can be considered a "maximum width". If the
476 resulting string is longer than this width, then it is truncated down to this
477 many characters and only those are emitted.
479 For integral types, this has no meaning currently.
481 For floating-point types, this indicates how many digits after the decimal point
486 The literal characters `{`, `}`, or `#` may be included in a string by
487 preceding them with the `\` character. Since `\` is already an
488 escape character in Rust strings, a string literal using this escape
489 will look like `"\\{"`.
499 use result::{Ok, Err};
500 use str::{Str, StrAllocating};
505 pub use core::fmt::{Formatter, Result, FormatWriter, Show, rt};
506 pub use core::fmt::{Show, Bool, Char, Signed, Unsigned, Octal, Binary};
507 pub use core::fmt::{LowerHex, UpperHex, String, Pointer};
508 pub use core::fmt::{Float, LowerExp, UpperExp};
509 pub use core::fmt::{FormatError, WriteError};
510 pub use core::fmt::{Argument, Arguments, write, radix, Radix, RadixFmt};
513 pub use core::fmt::{argument, argumentstr, argumentuint};
515 pub use core::fmt::{secret_show, secret_string, secret_unsigned};
517 pub use core::fmt::{secret_signed, secret_lower_hex, secret_upper_hex};
519 pub use core::fmt::{secret_bool, secret_char, secret_octal, secret_binary};
521 pub use core::fmt::{secret_bool, secret_char, secret_octal, secret_binary};
523 pub use core::fmt::{secret_float, secret_upper_exp, secret_lower_exp};
525 pub use core::fmt::{secret_pointer};
529 pub fn secret_poly<T: Poly>(x: &T, fmt: &mut Formatter) -> Result {
530 // FIXME #11938 - UFCS would make us able call the this method
531 // directly Poly::fmt(x, fmt).
535 /// Format trait for the `?` character
538 /// Formats the value using the given formatter.
539 fn fmt(&self, &mut Formatter) -> Result;
542 /// The format function takes a precompiled format string and a list of
543 /// arguments, to return the resulting formatted string.
547 /// * args - a structure of arguments generated via the `format_args!` macro.
548 /// Because this structure can only be safely generated at
549 /// compile-time, this function is safe.
556 /// let s = format_args!(fmt::format, "Hello, {}!", "world");
557 /// assert_eq!(s, "Hello, world!".to_string());
559 pub fn format(args: &Arguments) -> string::String{
560 let mut output = io::MemWriter::new();
561 let _ = write!(&mut output, "{}", args);
562 str::from_utf8(output.unwrap().as_slice()).unwrap().into_string()
567 fn fmt(&self, f: &mut Formatter) -> Result {
568 match (f.width, f.precision) {
570 match repr::write_repr(f, self) {
572 Err(..) => Err(WriteError),
576 // If we have a specified width for formatting, then we have to make
577 // this allocation of a new string
579 let s = repr::repr_to_str(self);
586 impl<'a> Writer for Formatter<'a> {
587 fn write(&mut self, b: &[u8]) -> io::IoResult<()> {
588 match (*self).write(b) {
590 Err(WriteError) => Err(io::standard_error(io::OtherIoError))