]> git.lizzy.rs Git - rust.git/blob - src/libstd/fmt.rs
rollup merge of #21438: taralx/kill-racycell
[rust.git] / src / libstd / fmt.rs
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.
4 //
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.
10 //
11 // ignore-lexer-test FIXME #15679
12
13 //! Utilities for formatting and printing strings
14 //!
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.
18 //!
19 //! ## Usage
20 //!
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.
26 //!
27 //! Some examples of the `format!` extension are:
28 //!
29 //! ```
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"
36 //! ```
37 //!
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.
43 //!
44 //! ### Positional parameters
45 //!
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.
51 //!
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:
56 //!
57 //! ```rust
58 //! format!("{1} {} {0} {}", 1i, 2i); // => "2 1 1 2"
59 //! ```
60 //!
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.
66 //!
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.
70 //!
71 //! ### Named parameters
72 //!
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:
77 //!
78 //! ```text
79 //! identifier '=' expression
80 //! ```
81 //!
82 //! For example, the following `format!` expressions all use named argument:
83 //!
84 //! ```
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"
88 //! ```
89 //!
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.
93 //!
94 //! ### Argument types
95 //!
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:
99 //!
100 //! ```text
101 //! {0:x} {0:o}
102 //! ```
103 //!
104 //! This is invalid because the first argument is both referred to as a
105 //! hexadecimal as well as an
106 //! octal.
107 //!
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:
114 //!
115 //! ```text
116 //! {:.*} {0}
117 //! ```
118 //!
119 //! ### Formatting traits
120 //!
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:
125 //!
126 //! * *nothing* ⇒ `String`
127 //! * `?` ⇒ `Show`
128 //! * `o` ⇒ `Octal`
129 //! * `x` ⇒ `LowerHex`
130 //! * `X` ⇒ `UpperHex`
131 //! * `p` ⇒ `Pointer`
132 //! * `b` ⇒ `Binary`
133 //! * `e` ⇒ `LowerExp`
134 //! * `E` ⇒ `UpperExp`
135 //!
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 `String` trait.
141 //!
142 //! When implementing a format trait for your own type, you will have to
143 //! implement a method of the signature:
144 //!
145 //! ```rust
146 //! # use std::fmt;
147 //! # struct Foo; // our custom type
148 //! # impl fmt::Show for Foo {
149 //! fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result {
150 //! # write!(f, "testing, testing")
151 //! # } }
152 //! ```
153 //!
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.
160 //!
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).
165 //!
166 //! An example of implementing the formatting traits would look
167 //! like:
168 //!
169 //! ```rust
170 //! use std::fmt;
171 //! use std::f64;
172 //! use std::num::Float;
173 //!
174 //! #[derive(Show)]
175 //! struct Vector2D {
176 //!     x: int,
177 //!     y: int,
178 //! }
179 //!
180 //! impl fmt::String 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)
186 //!     }
187 //! }
188 //!
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();
195 //!
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())
202 //!     }
203 //! }
204 //!
205 //! fn main() {
206 //!     let myvector = Vector2D { x: 3, y: 4 };
207 //!
208 //!     println!("{}", myvector);       // => "(3, 4)"
209 //!     println!("{:?}", myvector);     // => "Vector2D {x: 3i, y:4i}"
210 //!     println!("{:10.3b}", myvector); // => "     5.000"
211 //! }
212 //! ```
213 //!
214 //! #### fmt::String vs fmt::Show
215 //!
216 //! These two formatting traits have distinct purposes:
217 //!
218 //! - `fmt::String` 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 `String` trait.
221 //! - `fmt::Show` 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 `Show` trait is to facilitate debugging Rust code. In
224 //!   most cases, using `#[derive(Show)]` is sufficient and recommended.
225 //!
226 //! Some examples of the output from both traits:
227 //!
228 //! ```
229 //! assert_eq!(format!("{} {:?}", 3i32, 4i32), "3 4i32");
230 //! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'");
231 //! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\"");
232 //! ```
233 //!
234 //! ### Related macros
235 //!
236 //! There are a number of related macros in the `format!` family. The ones that
237 //! are currently implemented are:
238 //!
239 //! ```ignore
240 //! format!      // described above
241 //! write!       // first argument is a &mut 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.
246 //! ```
247 //!
248 //! #### `write!`
249 //!
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:
255 //!
256 //! ```rust
257 //! # #![allow(unused_must_use)]
258 //! use std::io;
259 //!
260 //! let mut w = Vec::new();
261 //! write!(&mut w as &mut io::Writer, "Hello {}!", "world");
262 //! ```
263 //!
264 //! #### `print!`
265 //!
266 //! This and `println` emit their output to stdout. Similarly to the `write!`
267 //! macro, the goal of these macros is to avoid intermediate allocations when
268 //! printing output. Example usage is:
269 //!
270 //! ```rust
271 //! print!("Hello {}!", "world");
272 //! println!("I have a newline {}", "character at the end");
273 //! ```
274 //!
275 //! #### `format_args!`
276 //! This is a curious macro which is used to safely pass around
277 //! an opaque object describing the format string. This object
278 //! does not require any heap allocations to create, and it only
279 //! references information on the stack. Under the hood, all of
280 //! the related macros are implemented in terms of this. First
281 //! off, some example usage is:
282 //!
283 //! ```
284 //! use std::fmt;
285 //! use std::io;
286 //!
287 //! fmt::format(format_args!("this returns {}", "String"));
288 //!
289 //! let some_writer: &mut io::Writer = &mut io::stdout();
290 //! write!(some_writer, "{}", format_args!("print with a {}", "macro"));
291 //!
292 //! fn my_fmt_fn(args: fmt::Arguments) {
293 //!     write!(&mut io::stdout(), "{}", args);
294 //! }
295 //! my_fmt_fn(format_args!("or a {} too", "function"));
296 //! ```
297 //!
298 //! The result of the `format_args!` macro is a value of type `fmt::Arguments`.
299 //! This structure can then be passed to the `write` and `format` functions
300 //! inside this module in order to process the format string.
301 //! The goal of this macro is to even further prevent intermediate allocations
302 //! when dealing formatting strings.
303 //!
304 //! For example, a logging library could use the standard formatting syntax, but
305 //! it would internally pass around this structure until it has been determined
306 //! where output should go to.
307 //!
308 //! ## Syntax
309 //!
310 //! The syntax for the formatting language used is drawn from other languages,
311 //! so it should not be too alien. Arguments are formatted with python-like
312 //! syntax, meaning that arguments are surrounded by `{}` instead of the C-like
313 //! `%`. The actual grammar for the formatting syntax is:
314 //!
315 //! ```text
316 //! format_string := <text> [ format <text> ] *
317 //! format := '{' [ argument ] [ ':' format_spec ] '}'
318 //! argument := integer | identifier
319 //!
320 //! format_spec := [[fill]align][sign]['#'][0][width]['.' precision][type]
321 //! fill := character
322 //! align := '<' | '^' | '>'
323 //! sign := '+' | '-'
324 //! width := count
325 //! precision := count | '*'
326 //! type := identifier | ''
327 //! count := parameter | integer
328 //! parameter := integer '$'
329 //! ```
330 //!
331 //! ## Formatting Parameters
332 //!
333 //! Each argument being formatted can be transformed by a number of formatting
334 //! parameters (corresponding to `format_spec` in the syntax above). These
335 //! parameters affect the string representation of what's being formatted. This
336 //! syntax draws heavily from Python's, so it may seem a bit familiar.
337 //!
338 //! ### Fill/Alignment
339 //!
340 //! The fill character is provided normally in conjunction with the `width`
341 //! parameter. This indicates that if the value being formatted is smaller than
342 //! `width` some extra characters will be printed around it. The extra
343 //! characters are specified by `fill`, and the alignment can be one of two
344 //! options:
345 //!
346 //! * `<` - the argument is left-aligned in `width` columns
347 //! * `^` - the argument is center-aligned in `width` columns
348 //! * `>` - the argument is right-aligned in `width` columns
349 //!
350 //! ### Sign/#/0
351 //!
352 //! These can all be interpreted as flags for a particular formatter.
353 //!
354 //! * '+' - This is intended for numeric types and indicates that the sign
355 //!         should always be printed. Positive signs are never printed by
356 //!         default, and the negative sign is only printed by default for the
357 //!         `Signed` trait. This flag indicates that the correct sign (+ or -)
358 //!         should always be printed.
359 //! * '-' - Currently not used
360 //! * '#' - This flag is indicates that the "alternate" form of printing should
361 //!         be used. By default, this only applies to the integer formatting
362 //!         traits and performs like:
363 //!     * `x` - precedes the argument with a "0x"
364 //!     * `X` - precedes the argument with a "0x"
365 //!     * `t` - precedes the argument with a "0b"
366 //!     * `o` - precedes the argument with a "0o"
367 //! * '0' - This is used to indicate for integer formats that the padding should
368 //!         both be done with a `0` character as well as be sign-aware. A format
369 //!         like `{:08d}` would yield `00000001` for the integer `1`, while the
370 //!         same format would yield `-0000001` for the integer `-1`. Notice that
371 //!         the negative version has one fewer zero than the positive version.
372 //!
373 //! ### Width
374 //!
375 //! This is a parameter for the "minimum width" that the format should take up.
376 //! If the value's string does not fill up this many characters, then the
377 //! padding specified by fill/alignment will be used to take up the required
378 //! space.
379 //!
380 //! The default fill/alignment for non-numerics is a space and left-aligned. The
381 //! defaults for numeric formatters is also a space but with right-alignment. If
382 //! the '0' flag is specified for numerics, then the implicit fill character is
383 //! '0'.
384 //!
385 //! The value for the width can also be provided as a `uint` in the list of
386 //! parameters by using the `2$` syntax indicating that the second argument is a
387 //! `uint` specifying the width.
388 //!
389 //! ### Precision
390 //!
391 //! For non-numeric types, this can be considered a "maximum width". If the
392 //! resulting string is longer than this width, then it is truncated down to
393 //! this many characters and only those are emitted.
394 //!
395 //! For integral types, this has no meaning currently.
396 //!
397 //! For floating-point types, this indicates how many digits after the decimal
398 //! point should be printed.
399 //!
400 //! ## Escaping
401 //!
402 //! The literal characters `{` and `}` may be included in a string by preceding
403 //! them with the same character. For example, the `{` character is escaped with
404 //! `{{` and the `}` character is escaped with `}}`.
405
406 #![unstable]
407
408 use string;
409
410 pub use core::fmt::{Formatter, Result, Writer, rt};
411 pub use core::fmt::{Show, String, Octal, Binary};
412 pub use core::fmt::{LowerHex, UpperHex, Pointer};
413 pub use core::fmt::{LowerExp, UpperExp};
414 pub use core::fmt::Error;
415 pub use core::fmt::{Argument, Arguments, write, radix, Radix, RadixFmt};
416
417 #[doc(hidden)]
418 pub use core::fmt::{argument, argumentuint};
419
420 /// The format function takes a precompiled format string and a list of
421 /// arguments, to return the resulting formatted string.
422 ///
423 /// # Arguments
424 ///
425 ///   * args - a structure of arguments generated via the `format_args!` macro.
426 ///
427 /// # Example
428 ///
429 /// ```rust
430 /// use std::fmt;
431 ///
432 /// let s = fmt::format(format_args!("Hello, {}!", "world"));
433 /// assert_eq!(s, "Hello, world!".to_string());
434 /// ```
435 #[unstable = "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);
440     output
441 }