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 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:
38 //! format!("Hello"); // => "Hello"
39 //! format!("Hello, {}!", "world"); // => "Hello, world!"
40 //! format!("The number is {}", 1i); // => "The number is 1"
41 //! format!("{}", (3i, 4i)); // => "(3, 4)"
42 //! format!("{value}", value=4i); // => "4"
43 //! format!("{} {}", 1i, 2u); // => "1 2"
47 //! From these, you can see that the first argument is a format string. It is
48 //! required by the compiler for this to be a string literal; it cannot be a
49 //! variable passed in (in order to perform validity checking). The compiler will
50 //! then parse the format string and determine if the list of arguments provided is
51 //! suitable to pass to this format string.
53 //! ### Positional parameters
55 //! Each formatting argument is allowed to specify which value argument it's
56 //! referencing, and if omitted it is assumed to be "the next argument". For
57 //! example, the format string `{} {} {}` would take three parameters, and they
58 //! would be formatted in the same order as they're given. The format string
59 //! `{2} {1} {0}`, however, would format arguments in reverse order.
61 //! Things can get a little tricky once you start intermingling the two types of
62 //! positional specifiers. The "next argument" specifier can be thought of as an
63 //! iterator over the argument. Each time a "next argument" specifier is seen, the
64 //! iterator advances. This leads to behavior like this:
67 //! format!("{1} {} {0} {}", 1i, 2i); // => "2 1 1 2"
70 //! The internal iterator over the argument has not been advanced by the time the
71 //! first `{}` is seen, so it prints the first argument. Then upon reaching the
72 //! second `{}`, the iterator has advanced forward to the second argument.
73 //! Essentially, parameters which explicitly name their argument do not affect
74 //! parameters which do not name an argument in terms of positional specifiers.
76 //! A format string is required to use all of its arguments, otherwise it is a
77 //! compile-time error. You may refer to the same argument more than once in the
78 //! format string, although it must always be referred to with the same type.
80 //! ### Named parameters
82 //! Rust itself does not have a Python-like equivalent of named parameters to a
83 //! function, but the `format!` macro is a syntax extension which allows it to
84 //! leverage named parameters. Named parameters are listed at the end of the
85 //! argument list and have the syntax:
88 //! identifier '=' expression
91 //! For example, the following `format!` expressions all use named argument:
95 //! format!("{argument}", argument = "test"); // => "test"
96 //! format!("{name} {}", 1i, name = 2i); // => "2 1"
97 //! format!("{a} {c} {b}", a="a", b=(), c=3i); // => "a 3 ()"
101 //! It is illegal to put positional parameters (those without names) after arguments
102 //! which have names. Like with positional parameters, it is illegal to provide
103 //! named parameters that are unused by the format string.
105 //! ### Argument types
107 //! Each argument's type is dictated by the format string. It is a requirement that every argument is
108 //! only ever referred to by one type. For example, this is an invalid format string:
114 //! This is invalid because the first argument is both referred to as a hexidecimal as well as an
117 //! There are various parameters which do require a particular type, however. Namely if the syntax
118 //! `{:.*}` is used, then the number of characters to print precedes the actual object being formatted,
119 //! and the number of characters must have the type `uint`. Although a `uint` can be printed with
120 //! `{}`, it is illegal to reference an argument as such. For example this is another invalid
127 //! ### Formatting traits
129 //! When requesting that an argument be formatted with a particular type, you are
130 //! actually requesting that an argument ascribes to a particular trait. This allows
131 //! multiple actual types to be formatted via `{:x}` (like `i8` as well as `int`).
132 //! The current mapping of types to traits is:
134 //! * *nothing* ⇒ `Show`
136 //! * `x` ⇒ `LowerHex`
137 //! * `X` ⇒ `UpperHex`
138 //! * `p` ⇒ `Pointer`
140 //! * `e` ⇒ `LowerExp`
141 //! * `E` ⇒ `UpperExp`
143 //! What this means is that any type of argument which implements the
144 //! `std::fmt::Binary` trait can then be formatted with `{:b}`. Implementations are
145 //! provided for these traits for a number of primitive types by the standard
146 //! library as well. If no format is specified (as in `{}` or `{:6}`), then the
147 //! format trait used is the `Show` trait. This is one of the more commonly
148 //! implemented traits when formatting a custom type.
150 //! When implementing a format trait for your own type, you will have to implement a
151 //! method of the signature:
155 //! # struct Foo; // our custom type
156 //! # impl fmt::Show for Foo {
157 //! fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result {
158 //! # write!(f, "testing, testing")
162 //! Your type will be passed as `self` by-reference, and then the function should
163 //! emit output into the `f.buf` stream. It is up to each format trait
164 //! implementation to correctly adhere to the requested formatting parameters. The
165 //! values of these parameters will be listed in the fields of the `Formatter`
166 //! struct. In order to help with this, the `Formatter` struct also provides some
169 //! Additionally, the return value of this function is `fmt::Result` which is a
170 //! typedef to `Result<(), IoError>` (also known as `IoResult<()>`). Formatting
171 //! implementations should ensure that they return errors from `write!` correctly
172 //! (propagating errors upward).
174 //! An example of implementing the formatting traits would look
180 //! use std::num::Float;
182 //! struct Vector2D {
187 //! impl fmt::Show for Vector2D {
188 //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
189 //! // The `f` value implements the `Writer` trait, which is what the
190 //! // write! macro is expecting. Note that this formatting ignores the
191 //! // various flags provided to format strings.
192 //! write!(f, "({}, {})", self.x, self.y)
196 //! // Different traits allow different forms of output of a type. The meaning of
197 //! // this format is to print the magnitude of a vector.
198 //! impl fmt::Binary for Vector2D {
199 //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
200 //! let magnitude = (self.x * self.x + self.y * self.y) as f64;
201 //! let magnitude = magnitude.sqrt();
203 //! // Respect the formatting flags by using the helper method
204 //! // `pad_integral` on the Formatter object. See the method documentation
205 //! // for details, and the function `pad` can be used to pad strings.
206 //! let decimals = f.precision().unwrap_or(3);
207 //! let string = f64::to_str_exact(magnitude, decimals);
208 //! f.pad_integral(true, "", string.as_bytes())
213 //! let myvector = Vector2D { x: 3, y: 4 };
215 //! println!("{}", myvector); // => "(3, 4)"
216 //! println!("{:10.3b}", myvector); // => " 5.000"
220 //! ### Related macros
222 //! There are a number of related macros in the `format!` family. The ones that are
223 //! currently implemented are:
226 //! format! // described above
227 //! write! // first argument is a &mut io::Writer, the destination
228 //! writeln! // same as write but appends a newline
229 //! print! // the format string is printed to the standard output
230 //! println! // same as print but appends a newline
231 //! format_args! // described below.
236 //! This and `writeln` are two macros which are used to emit the format string to a
237 //! specified stream. This is used to prevent intermediate allocations of format
238 //! strings and instead directly write the output. Under the hood, this function is
239 //! actually invoking the `write` function defined in this module. Example usage is:
242 //! # #![allow(unused_must_use)]
245 //! let mut w = Vec::new();
246 //! write!(&mut w as &mut io::Writer, "Hello {}!", "world");
251 //! This and `println` emit their output to stdout. Similarly to the `write!` macro,
252 //! the goal of these macros is to avoid intermediate allocations when printing
253 //! output. Example usage is:
256 //! print!("Hello {}!", "world");
257 //! println!("I have a newline {}", "character at the end");
260 //! #### `format_args!`
261 //! This is a curious macro which is used to safely pass around
262 //! an opaque object describing the format string. This object
263 //! does not require any heap allocations to create, and it only
264 //! references information on the stack. Under the hood, all of
265 //! the related macros are implemented in terms of this. First
266 //! off, some example usage is:
272 //! # #[allow(unused_must_use)]
274 //! format_args!(fmt::format, "this returns {}", "String");
276 //! let some_writer: &mut io::Writer = &mut io::stdout();
277 //! format_args!(|args| { write!(some_writer, "{}", args) }, "print with a {}", "closure");
279 //! fn my_fmt_fn(args: &fmt::Arguments) {
280 //! write!(&mut io::stdout(), "{}", args);
282 //! format_args!(my_fmt_fn, "or a {} too", "function");
286 //! The first argument of the `format_args!` macro is a function (or closure) which
287 //! takes one argument of type `&fmt::Arguments`. This structure can then be
288 //! passed to the `write` and `format` functions inside this module in order to
289 //! process the format string. The goal of this macro is to even further prevent
290 //! intermediate allocations when dealing formatting strings.
292 //! For example, a logging library could use the standard formatting syntax, but it
293 //! would internally pass around this structure until it has been determined where
294 //! output should go to.
296 //! It is unsafe to programmatically create an instance of `fmt::Arguments` because
297 //! the operations performed when executing a format string require the compile-time
298 //! checks provided by the compiler. The `format_args!` macro is the only method of
299 //! safely creating these structures, but they can be unsafely created with the
300 //! constructor provided.
304 //! The syntax for the formatting language used is drawn from other languages, so it
305 //! should not be too alien. Arguments are formatted with python-like syntax,
306 //! meaning that arguments are surrounded by `{}` instead of the C-like `%`. The
307 //! actual grammar for the formatting syntax is:
310 //! format_string := <text> [ format <text> ] *
311 //! format := '{' [ argument ] [ ':' format_spec ] '}'
312 //! argument := integer | identifier
314 //! format_spec := [[fill]align][sign]['#'][0][width]['.' precision][type]
315 //! fill := character
316 //! align := '<' | '^' | '>'
317 //! sign := '+' | '-'
319 //! precision := count | '*'
320 //! type := identifier | ''
321 //! count := parameter | integer
322 //! parameter := integer '$'
325 //! ## Formatting Parameters
327 //! Each argument being formatted can be transformed by a number of formatting
328 //! parameters (corresponding to `format_spec` in the syntax above). These
329 //! parameters affect the string representation of what's being formatted. This
330 //! syntax draws heavily from Python's, so it may seem a bit familiar.
332 //! ### Fill/Alignment
334 //! The fill character is provided normally in conjunction with the `width`
335 //! parameter. This indicates that if the value being formatted is smaller than
336 //! `width` some extra characters will be printed around it. The extra characters
337 //! are specified by `fill`, and the alignment can be one of two options:
339 //! * `<` - the argument is left-aligned in `width` columns
340 //! * `^` - the argument is center-aligned in `width` columns
341 //! * `>` - the argument is right-aligned in `width` columns
345 //! These can all be interpreted as flags for a particular formatter.
347 //! * '+' - This is intended for numeric types and indicates that the sign should
348 //! always be printed. Positive signs are never printed by default, and the
349 //! negative sign is only printed by default for the `Signed` trait. This
350 //! flag indicates that the correct sign (+ or -) should always be printed.
351 //! * '-' - Currently not used
352 //! * '#' - This flag is indicates that the "alternate" form of printing should be
353 //! used. By default, this only applies to the integer formatting traits and
355 //! * `x` - precedes the argument with a "0x"
356 //! * `X` - precedes the argument with a "0x"
357 //! * `t` - precedes the argument with a "0b"
358 //! * `o` - precedes the argument with a "0o"
359 //! * '0' - This is used to indicate for integer formats that the padding should
360 //! both be done with a `0` character as well as be sign-aware. A format
361 //! like `{:08d}` would yield `00000001` for the integer `1`, while the same
362 //! format would yield `-0000001` for the integer `-1`. Notice that the
363 //! negative version has one fewer zero than the positive version.
367 //! This is a parameter for the "minimum width" that the format should take up. If
368 //! the value's string does not fill up this many characters, then the padding
369 //! specified by fill/alignment will be used to take up the required space.
371 //! The default fill/alignment for non-numerics is a space and left-aligned. The
372 //! defaults for numeric formatters is also a space but with right-alignment. If the
373 //! '0' flag is specified for numerics, then the implicit fill character is '0'.
375 //! The value for the width can also be provided as a `uint` in the list of
376 //! parameters by using the `2$` syntax indicating that the second argument is a
377 //! `uint` specifying the width.
381 //! For non-numeric types, this can be considered a "maximum width". If the
382 //! resulting string is longer than this width, then it is truncated down to this
383 //! many characters and only those are emitted.
385 //! For integral types, this has no meaning currently.
387 //! For floating-point types, this indicates how many digits after the decimal point
388 //! should be printed.
392 //! The literal characters `{` and `}` may be included in a string by preceding them
393 //! with the same character. For example, the `{` character is escaped with `{{` and
394 //! the `}` character is escaped with `}}`.
400 use result::{Ok, Err};
404 pub use core::fmt::{Formatter, Result, FormatWriter, rt};
405 pub use core::fmt::{Show, Octal, Binary};
406 pub use core::fmt::{LowerHex, UpperHex, Pointer};
407 pub use core::fmt::{LowerExp, UpperExp};
408 pub use core::fmt::Error;
409 pub use core::fmt::{Argument, Arguments, write, radix, Radix, RadixFmt};
412 pub use core::fmt::{argument, argumentstr, argumentuint};
414 /// The format function takes a precompiled format string and a list of
415 /// arguments, to return the resulting formatted string.
419 /// * args - a structure of arguments generated via the `format_args!` macro.
420 /// Because this structure can only be safely generated at
421 /// compile-time, this function is safe.
428 /// let s = format_args!(fmt::format, "Hello, {}!", "world");
429 /// assert_eq!(s, "Hello, world!".to_string());
431 #[experimental = "this is an implementation detail of format! and should not \
433 pub fn format(args: &Arguments) -> string::String {
434 let mut output = Vec::new();
435 let _ = write!(&mut output as &mut Writer, "{}", args);
436 string::String::from_utf8(output).unwrap()
439 impl<'a> Writer for Formatter<'a> {
440 fn write(&mut self, b: &[u8]) -> io::IoResult<()> {
441 match (*self).write(b) {
443 Err(Error) => Err(io::standard_error(io::OtherIoError))