]> git.lizzy.rs Git - rust.git/blob - src/libstd/fmt.rs
rollup merge of #20385: nick29581/x-object
[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 //! ```rust
30 //! # fn main() {
31 //! format!("Hello");                  // => "Hello"
32 //! format!("Hello, {}!", "world");    // => "Hello, world!"
33 //! format!("The number is {}", 1i);   // => "The number is 1"
34 //! format!("{}", (3i, 4i));           // => "(3, 4)"
35 //! format!("{value}", value=4i);      // => "4"
36 //! format!("{} {}", 1i, 2u);          // => "1 2"
37 //! # }
38 //! ```
39 //!
40 //! From these, you can see that the first argument is a format string. It is
41 //! required by the compiler for this to be a string literal; it cannot be a
42 //! variable passed in (in order to perform validity checking). The compiler
43 //! will then parse the format string and determine if the list of arguments
44 //! provided is suitable to pass to this format string.
45 //!
46 //! ### Positional parameters
47 //!
48 //! Each formatting argument is allowed to specify which value argument it's
49 //! referencing, and if omitted it is assumed to be "the next argument". For
50 //! example, the format string `{} {} {}` would take three parameters, and they
51 //! would be formatted in the same order as they're given. The format string
52 //! `{2} {1} {0}`, however, would format arguments in reverse order.
53 //!
54 //! Things can get a little tricky once you start intermingling the two types of
55 //! positional specifiers. The "next argument" specifier can be thought of as an
56 //! iterator over the argument. Each time a "next argument" specifier is seen,
57 //! the iterator advances. This leads to behavior like this:
58 //!
59 //! ```rust
60 //! format!("{1} {} {0} {}", 1i, 2i); // => "2 1 1 2"
61 //! ```
62 //!
63 //! The internal iterator over the argument has not been advanced by the time
64 //! the first `{}` is seen, so it prints the first argument. Then upon reaching
65 //! the second `{}`, the iterator has advanced forward to the second argument.
66 //! Essentially, parameters which explicitly name their argument do not affect
67 //! parameters which do not name an argument in terms of positional specifiers.
68 //!
69 //! A format string is required to use all of its arguments, otherwise it is a
70 //! compile-time error. You may refer to the same argument more than once in the
71 //! format string, although it must always be referred to with the same type.
72 //!
73 //! ### Named parameters
74 //!
75 //! Rust itself does not have a Python-like equivalent of named parameters to a
76 //! function, but the `format!` macro is a syntax extension which allows it to
77 //! leverage named parameters. Named parameters are listed at the end of the
78 //! argument list and have the syntax:
79 //!
80 //! ```text
81 //! identifier '=' expression
82 //! ```
83 //!
84 //! For example, the following `format!` expressions all use named argument:
85 //!
86 //! ```rust
87 //! # fn main() {
88 //! format!("{argument}", argument = "test");   // => "test"
89 //! format!("{name} {}", 1i, name = 2i);        // => "2 1"
90 //! format!("{a} {c} {b}", a="a", b=(), c=3i);  // => "a 3 ()"
91 //! # }
92 //! ```
93 //!
94 //! It is illegal to put positional parameters (those without names) after
95 //! arguments which have names. Like with positional parameters, it is illegal
96 //! to provide named parameters that are unused by the format string.
97 //!
98 //! ### Argument types
99 //!
100 //! Each argument's type is dictated by the format string. It is a requirement
101 //! that every argument is only ever referred to by one type. For example, this
102 //! is an invalid format string:
103 //!
104 //! ```text
105 //! {0:x} {0:o}
106 //! ```
107 //!
108 //! This is invalid because the first argument is both referred to as a
109 //! hexidecimal as well as an
110 //! octal.
111 //!
112 //! There are various parameters which do require a particular type, however.
113 //! Namely if the syntax `{:.*}` is used, then the number of characters to print
114 //! precedes the actual object being formatted, and the number of characters
115 //! must have the type `uint`. Although a `uint` can be printed with `{}`, it is
116 //! illegal to reference an argument as such. For example this is another
117 //! invalid format string:
118 //!
119 //! ```text
120 //! {:.*} {0}
121 //! ```
122 //!
123 //! ### Formatting traits
124 //!
125 //! When requesting that an argument be formatted with a particular type, you
126 //! are actually requesting that an argument ascribes to a particular trait.
127 //! This allows multiple actual types to be formatted via `{:x}` (like `i8` as
128 //! well as `int`).  The current mapping of types to traits is:
129 //!
130 //! * *nothing* ⇒ `Show`
131 //! * `o` ⇒ `Octal`
132 //! * `x` ⇒ `LowerHex`
133 //! * `X` ⇒ `UpperHex`
134 //! * `p` ⇒ `Pointer`
135 //! * `b` ⇒ `Binary`
136 //! * `e` ⇒ `LowerExp`
137 //! * `E` ⇒ `UpperExp`
138 //!
139 //! What this means is that any type of argument which implements the
140 //! `std::fmt::Binary` trait can then be formatted with `{:b}`. Implementations
141 //! are provided for these traits for a number of primitive types by the
142 //! standard library as well. If no format is specified (as in `{}` or `{:6}`),
143 //! then the format trait used is the `Show` trait. This is one of the more
144 //! commonly implemented traits when formatting a custom type.
145 //!
146 //! When implementing a format trait for your own type, you will have to
147 //! implement a method of the signature:
148 //!
149 //! ```rust
150 //! # use std::fmt;
151 //! # struct Foo; // our custom type
152 //! # impl fmt::Show for Foo {
153 //! fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result {
154 //! # write!(f, "testing, testing")
155 //! # } }
156 //! ```
157 //!
158 //! Your type will be passed as `self` by-reference, and then the function
159 //! should emit output into the `f.buf` stream. It is up to each format trait
160 //! implementation to correctly adhere to the requested formatting parameters.
161 //! The values of these parameters will be listed in the fields of the
162 //! `Formatter` struct. In order to help with this, the `Formatter` struct also
163 //! provides some helper methods.
164 //!
165 //! Additionally, the return value of this function is `fmt::Result` which is a
166 //! typedef to `Result<(), IoError>` (also known as `IoResult<()>`). Formatting
167 //! implementations should ensure that they return errors from `write!`
168 //! correctly (propagating errors upward).
169 //!
170 //! An example of implementing the formatting traits would look
171 //! like:
172 //!
173 //! ```rust
174 //! use std::fmt;
175 //! use std::f64;
176 //! use std::num::Float;
177 //!
178 //! struct Vector2D {
179 //!     x: int,
180 //!     y: int,
181 //! }
182 //!
183 //! impl fmt::Show for Vector2D {
184 //!     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
185 //!         // The `f` value implements the `Writer` trait, which is what the
186 //!         // write! macro is expecting. Note that this formatting ignores the
187 //!         // various flags provided to format strings.
188 //!         write!(f, "({}, {})", self.x, self.y)
189 //!     }
190 //! }
191 //!
192 //! // Different traits allow different forms of output of a type. The meaning
193 //! // of this format is to print the magnitude of a vector.
194 //! impl fmt::Binary for Vector2D {
195 //!     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
196 //!         let magnitude = (self.x * self.x + self.y * self.y) as f64;
197 //!         let magnitude = magnitude.sqrt();
198 //!
199 //!         // Respect the formatting flags by using the helper method
200 //!         // `pad_integral` on the Formatter object. See the method documentation
201 //!         // for details, and the function `pad` can be used to pad strings.
202 //!         let decimals = f.precision().unwrap_or(3);
203 //!         let string = f64::to_str_exact(magnitude, decimals);
204 //!         f.pad_integral(true, "", string.as_slice())
205 //!     }
206 //! }
207 //!
208 //! fn main() {
209 //!     let myvector = Vector2D { x: 3, y: 4 };
210 //!
211 //!     println!("{}", myvector);       // => "(3, 4)"
212 //!     println!("{:10.3b}", myvector); // => "     5.000"
213 //! }
214 //! ```
215 //!
216 //! ### Related macros
217 //!
218 //! There are a number of related macros in the `format!` family. The ones that
219 //! are currently implemented are:
220 //!
221 //! ```ignore
222 //! format!      // described above
223 //! write!       // first argument is a &mut io::Writer, the destination
224 //! writeln!     // same as write but appends a newline
225 //! print!       // the format string is printed to the standard output
226 //! println!     // same as print but appends a newline
227 //! format_args! // described below.
228 //! ```
229 //!
230 //! #### `write!`
231 //!
232 //! This and `writeln` are two macros which are used to emit the format string
233 //! to a specified stream. This is used to prevent intermediate allocations of
234 //! format strings and instead directly write the output. Under the hood, this
235 //! function is actually invoking the `write` function defined in this module.
236 //! Example usage is:
237 //!
238 //! ```rust
239 //! # #![allow(unused_must_use)]
240 //! use std::io;
241 //!
242 //! let mut w = Vec::new();
243 //! write!(&mut w as &mut io::Writer, "Hello {}!", "world");
244 //! ```
245 //!
246 //! #### `print!`
247 //!
248 //! This and `println` emit their output to stdout. Similarly to the `write!`
249 //! macro, the goal of these macros is to avoid intermediate allocations when
250 //! printing output. Example usage is:
251 //!
252 //! ```rust
253 //! print!("Hello {}!", "world");
254 //! println!("I have a newline {}", "character at the end");
255 //! ```
256 //!
257 //! #### `format_args!`
258 //! This is a curious macro which is used to safely pass around
259 //! an opaque object describing the format string. This object
260 //! does not require any heap allocations to create, and it only
261 //! references information on the stack. Under the hood, all of
262 //! the related macros are implemented in terms of this. First
263 //! off, some example usage is:
264 //!
265 //! ```
266 //! use std::fmt;
267 //! use std::io;
268 //!
269 //! # #[allow(unused_must_use)]
270 //! # fn main() {
271 //! fmt::format(format_args!("this returns {}", "String"));
272 //!
273 //! let some_writer: &mut io::Writer = &mut io::stdout();
274 //! write!(some_writer, "{}", format_args!("print with a {}", "macro"));
275 //!
276 //! fn my_fmt_fn(args: fmt::Arguments) {
277 //!     write!(&mut io::stdout(), "{}", args);
278 //! }
279 //! my_fmt_fn(format_args!("or a {} too", "function"));
280 //! # }
281 //! ```
282 //!
283 //! The result of the `format_args!` macro is a value of type `fmt::Arguments`.
284 //! This structure can then be passed to the `write` and `format` functions
285 //! inside this module in order to process the format string.
286 //! The goal of this macro is to even further prevent intermediate allocations
287 //! when dealing formatting strings.
288 //!
289 //! For example, a logging library could use the standard formatting syntax, but
290 //! it would internally pass around this structure until it has been determined
291 //! where output should go to.
292 //!
293 //! ## Syntax
294 //!
295 //! The syntax for the formatting language used is drawn from other languages,
296 //! so it should not be too alien. Arguments are formatted with python-like
297 //! syntax, meaning that arguments are surrounded by `{}` instead of the C-like
298 //! `%`. The actual grammar for the formatting syntax is:
299 //!
300 //! ```text
301 //! format_string := <text> [ format <text> ] *
302 //! format := '{' [ argument ] [ ':' format_spec ] '}'
303 //! argument := integer | identifier
304 //!
305 //! format_spec := [[fill]align][sign]['#'][0][width]['.' precision][type]
306 //! fill := character
307 //! align := '<' | '^' | '>'
308 //! sign := '+' | '-'
309 //! width := count
310 //! precision := count | '*'
311 //! type := identifier | ''
312 //! count := parameter | integer
313 //! parameter := integer '$'
314 //! ```
315 //!
316 //! ## Formatting Parameters
317 //!
318 //! Each argument being formatted can be transformed by a number of formatting
319 //! parameters (corresponding to `format_spec` in the syntax above). These
320 //! parameters affect the string representation of what's being formatted. This
321 //! syntax draws heavily from Python's, so it may seem a bit familiar.
322 //!
323 //! ### Fill/Alignment
324 //!
325 //! The fill character is provided normally in conjunction with the `width`
326 //! parameter. This indicates that if the value being formatted is smaller than
327 //! `width` some extra characters will be printed around it. The extra
328 //! characters are specified by `fill`, and the alignment can be one of two
329 //! options:
330 //!
331 //! * `<` - the argument is left-aligned in `width` columns
332 //! * `^` - the argument is center-aligned in `width` columns
333 //! * `>` - the argument is right-aligned in `width` columns
334 //!
335 //! ### Sign/#/0
336 //!
337 //! These can all be interpreted as flags for a particular formatter.
338 //!
339 //! * '+' - This is intended for numeric types and indicates that the sign
340 //!         should always be printed. Positive signs are never printed by
341 //!         default, and the negative sign is only printed by default for the
342 //!         `Signed` trait. This flag indicates that the correct sign (+ or -)
343 //!         should always be printed.
344 //! * '-' - Currently not used
345 //! * '#' - This flag is indicates that the "alternate" form of printing should
346 //!         be used. By default, this only applies to the integer formatting
347 //!         traits and performs like:
348 //!     * `x` - precedes the argument with a "0x"
349 //!     * `X` - precedes the argument with a "0x"
350 //!     * `t` - precedes the argument with a "0b"
351 //!     * `o` - precedes the argument with a "0o"
352 //! * '0' - This is used to indicate for integer formats that the padding should
353 //!         both be done with a `0` character as well as be sign-aware. A format
354 //!         like `{:08d}` would yield `00000001` for the integer `1`, while the
355 //!         same format would yield `-0000001` for the integer `-1`. Notice that
356 //!         the negative version has one fewer zero than the positive version.
357 //!
358 //! ### Width
359 //!
360 //! This is a parameter for the "minimum width" that the format should take up.
361 //! If the value's string does not fill up this many characters, then the
362 //! padding specified by fill/alignment will be used to take up the required
363 //! space.
364 //!
365 //! The default fill/alignment for non-numerics is a space and left-aligned. The
366 //! defaults for numeric formatters is also a space but with right-alignment. If
367 //! the '0' flag is specified for numerics, then the implicit fill character is
368 //! '0'.
369 //!
370 //! The value for the width can also be provided as a `uint` in the list of
371 //! parameters by using the `2$` syntax indicating that the second argument is a
372 //! `uint` specifying the width.
373 //!
374 //! ### Precision
375 //!
376 //! For non-numeric types, this can be considered a "maximum width". If the
377 //! resulting string is longer than this width, then it is truncated down to
378 //! this many characters and only those are emitted.
379 //!
380 //! For integral types, this has no meaning currently.
381 //!
382 //! For floating-point types, this indicates how many digits after the decimal
383 //! point should be printed.
384 //!
385 //! ## Escaping
386 //!
387 //! The literal characters `{` and `}` may be included in a string by preceding
388 //! them with the same character. For example, the `{` character is escaped with
389 //! `{{` and the `}` character is escaped with `}}`.
390
391 #![experimental]
392
393 use string;
394
395 pub use core::fmt::{Formatter, Result, Writer, rt};
396 pub use core::fmt::{Show, Octal, Binary};
397 pub use core::fmt::{LowerHex, UpperHex, Pointer};
398 pub use core::fmt::{LowerExp, UpperExp};
399 pub use core::fmt::Error;
400 pub use core::fmt::{Argument, Arguments, write, radix, Radix, RadixFmt};
401
402 #[doc(hidden)]
403 pub use core::fmt::{argument, argumentuint};
404
405 /// The format function takes a precompiled format string and a list of
406 /// arguments, to return the resulting formatted string.
407 ///
408 /// # Arguments
409 ///
410 ///   * args - a structure of arguments generated via the `format_args!` macro.
411 ///
412 /// # Example
413 ///
414 /// ```rust
415 /// use std::fmt;
416 ///
417 /// let s = fmt::format(format_args!("Hello, {}!", "world"));
418 /// assert_eq!(s, "Hello, world!".to_string());
419 /// ```
420 #[experimental = "this is an implementation detail of format! and should not \
421                   be called directly"]
422 pub fn format(args: Arguments) -> string::String {
423     let mut output = string::String::new();
424     let _ = write!(&mut output, "{}", args);
425     output
426 }