]> git.lizzy.rs Git - rust.git/blob - src/libstd/fmt.rs
Merge pull request #20674 from jbcrail/fix-misspelled-comments
[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));         // => "(3i, 4i)"
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='b', c=3i);  // => "a 3 b"
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 //! hexadecimal 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* ⇒ `String`
131 //! * `?` ⇒ `Show`
132 //! * `o` ⇒ `Octal`
133 //! * `x` ⇒ `LowerHex`
134 //! * `X` ⇒ `UpperHex`
135 //! * `p` ⇒ `Pointer`
136 //! * `b` ⇒ `Binary`
137 //! * `e` ⇒ `LowerExp`
138 //! * `E` ⇒ `UpperExp`
139 //!
140 //! What this means is that any type of argument which implements the
141 //! `std::fmt::Binary` trait can then be formatted with `{:b}`. Implementations
142 //! are provided for these traits for a number of primitive types by the
143 //! standard library as well. If no format is specified (as in `{}` or `{:6}`),
144 //! then the format trait used is the `String` trait.
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 //! #[deriving(Show)]
179 //! struct Vector2D {
180 //!     x: int,
181 //!     y: int,
182 //! }
183 //!
184 //! impl fmt::String for Vector2D {
185 //!     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
186 //!         // The `f` value implements the `Writer` trait, which is what the
187 //!         // write! macro is expecting. Note that this formatting ignores the
188 //!         // various flags provided to format strings.
189 //!         write!(f, "({}, {})", self.x, self.y)
190 //!     }
191 //! }
192 //!
193 //! // Different traits allow different forms of output of a type. The meaning
194 //! // of this format is to print the magnitude of a vector.
195 //! impl fmt::Binary for Vector2D {
196 //!     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
197 //!         let magnitude = (self.x * self.x + self.y * self.y) as f64;
198 //!         let magnitude = magnitude.sqrt();
199 //!
200 //!         // Respect the formatting flags by using the helper method
201 //!         // `pad_integral` on the Formatter object. See the method documentation
202 //!         // for details, and the function `pad` can be used to pad strings.
203 //!         let decimals = f.precision().unwrap_or(3);
204 //!         let string = f64::to_str_exact(magnitude, decimals);
205 //!         f.pad_integral(true, "", string.as_slice())
206 //!     }
207 //! }
208 //!
209 //! fn main() {
210 //!     let myvector = Vector2D { x: 3, y: 4 };
211 //!
212 //!     println!("{}", myvector);       // => "(3, 4)"
213 //!     println!("{:?}", myvector);     // => "Vector2D {x: 3i, y:4i}"
214 //!     println!("{:10.3b}", myvector); // => "     5.000"
215 //! }
216 //! ```
217 //!
218 //! #### fmt::String vs fmt::Show
219 //!
220 //! These two formatting traits have distinct purposes:
221 //!
222 //! - `fmt::String` implementations assert that the type can be faithfully
223 //!   represented as a UTF-8 string at all times. It is **not** expected that
224 //!   all types implement the `String` trait.
225 //! - `fmt::Show` implementations should be implemented for **all** public types.
226 //!   Output will typically represent the internal state as faithfully as possible.
227 //!   The purpose of the `Show` trait is to facilitate debugging Rust code. In
228 //!   most cases, using `#[deriving(Show)]` is sufficient and recommended.
229 //!
230 //! Some examples of the output from both traits:
231 //!
232 //! ```
233 //! assert_eq!(format!("{} {:?}", 3i32, 4i32), "3 4i32");
234 //! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'");
235 //! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\"");
236 //! ```
237 //!
238 //! ### Related macros
239 //!
240 //! There are a number of related macros in the `format!` family. The ones that
241 //! are currently implemented are:
242 //!
243 //! ```ignore
244 //! format!      // described above
245 //! write!       // first argument is a &mut io::Writer, the destination
246 //! writeln!     // same as write but appends a newline
247 //! print!       // the format string is printed to the standard output
248 //! println!     // same as print but appends a newline
249 //! format_args! // described below.
250 //! ```
251 //!
252 //! #### `write!`
253 //!
254 //! This and `writeln` are two macros which are used to emit the format string
255 //! to a specified stream. This is used to prevent intermediate allocations of
256 //! format strings and instead directly write the output. Under the hood, this
257 //! function is actually invoking the `write` function defined in this module.
258 //! Example usage is:
259 //!
260 //! ```rust
261 //! # #![allow(unused_must_use)]
262 //! use std::io;
263 //!
264 //! let mut w = Vec::new();
265 //! write!(&mut w as &mut io::Writer, "Hello {}!", "world");
266 //! ```
267 //!
268 //! #### `print!`
269 //!
270 //! This and `println` emit their output to stdout. Similarly to the `write!`
271 //! macro, the goal of these macros is to avoid intermediate allocations when
272 //! printing output. Example usage is:
273 //!
274 //! ```rust
275 //! print!("Hello {}!", "world");
276 //! println!("I have a newline {}", "character at the end");
277 //! ```
278 //!
279 //! #### `format_args!`
280 //! This is a curious macro which is used to safely pass around
281 //! an opaque object describing the format string. This object
282 //! does not require any heap allocations to create, and it only
283 //! references information on the stack. Under the hood, all of
284 //! the related macros are implemented in terms of this. First
285 //! off, some example usage is:
286 //!
287 //! ```
288 //! use std::fmt;
289 //! use std::io;
290 //!
291 //! # #[allow(unused_must_use)]
292 //! # fn main() {
293 //! fmt::format(format_args!("this returns {}", "String"));
294 //!
295 //! let some_writer: &mut io::Writer = &mut io::stdout();
296 //! write!(some_writer, "{}", format_args!("print with a {}", "macro"));
297 //!
298 //! fn my_fmt_fn(args: fmt::Arguments) {
299 //!     write!(&mut io::stdout(), "{}", args);
300 //! }
301 //! my_fmt_fn(format_args!("or a {} too", "function"));
302 //! # }
303 //! ```
304 //!
305 //! The result of the `format_args!` macro is a value of type `fmt::Arguments`.
306 //! This structure can then be passed to the `write` and `format` functions
307 //! inside this module in order to process the format string.
308 //! The goal of this macro is to even further prevent intermediate allocations
309 //! when dealing formatting strings.
310 //!
311 //! For example, a logging library could use the standard formatting syntax, but
312 //! it would internally pass around this structure until it has been determined
313 //! where output should go to.
314 //!
315 //! ## Syntax
316 //!
317 //! The syntax for the formatting language used is drawn from other languages,
318 //! so it should not be too alien. Arguments are formatted with python-like
319 //! syntax, meaning that arguments are surrounded by `{}` instead of the C-like
320 //! `%`. The actual grammar for the formatting syntax is:
321 //!
322 //! ```text
323 //! format_string := <text> [ format <text> ] *
324 //! format := '{' [ argument ] [ ':' format_spec ] '}'
325 //! argument := integer | identifier
326 //!
327 //! format_spec := [[fill]align][sign]['#'][0][width]['.' precision][type]
328 //! fill := character
329 //! align := '<' | '^' | '>'
330 //! sign := '+' | '-'
331 //! width := count
332 //! precision := count | '*'
333 //! type := identifier | ''
334 //! count := parameter | integer
335 //! parameter := integer '$'
336 //! ```
337 //!
338 //! ## Formatting Parameters
339 //!
340 //! Each argument being formatted can be transformed by a number of formatting
341 //! parameters (corresponding to `format_spec` in the syntax above). These
342 //! parameters affect the string representation of what's being formatted. This
343 //! syntax draws heavily from Python's, so it may seem a bit familiar.
344 //!
345 //! ### Fill/Alignment
346 //!
347 //! The fill character is provided normally in conjunction with the `width`
348 //! parameter. This indicates that if the value being formatted is smaller than
349 //! `width` some extra characters will be printed around it. The extra
350 //! characters are specified by `fill`, and the alignment can be one of two
351 //! options:
352 //!
353 //! * `<` - the argument is left-aligned in `width` columns
354 //! * `^` - the argument is center-aligned in `width` columns
355 //! * `>` - the argument is right-aligned in `width` columns
356 //!
357 //! ### Sign/#/0
358 //!
359 //! These can all be interpreted as flags for a particular formatter.
360 //!
361 //! * '+' - This is intended for numeric types and indicates that the sign
362 //!         should always be printed. Positive signs are never printed by
363 //!         default, and the negative sign is only printed by default for the
364 //!         `Signed` trait. This flag indicates that the correct sign (+ or -)
365 //!         should always be printed.
366 //! * '-' - Currently not used
367 //! * '#' - This flag is indicates that the "alternate" form of printing should
368 //!         be used. By default, this only applies to the integer formatting
369 //!         traits and performs like:
370 //!     * `x` - precedes the argument with a "0x"
371 //!     * `X` - precedes the argument with a "0x"
372 //!     * `t` - precedes the argument with a "0b"
373 //!     * `o` - precedes the argument with a "0o"
374 //! * '0' - This is used to indicate for integer formats that the padding should
375 //!         both be done with a `0` character as well as be sign-aware. A format
376 //!         like `{:08d}` would yield `00000001` for the integer `1`, while the
377 //!         same format would yield `-0000001` for the integer `-1`. Notice that
378 //!         the negative version has one fewer zero than the positive version.
379 //!
380 //! ### Width
381 //!
382 //! This is a parameter for the "minimum width" that the format should take up.
383 //! If the value's string does not fill up this many characters, then the
384 //! padding specified by fill/alignment will be used to take up the required
385 //! space.
386 //!
387 //! The default fill/alignment for non-numerics is a space and left-aligned. The
388 //! defaults for numeric formatters is also a space but with right-alignment. If
389 //! the '0' flag is specified for numerics, then the implicit fill character is
390 //! '0'.
391 //!
392 //! The value for the width can also be provided as a `uint` in the list of
393 //! parameters by using the `2$` syntax indicating that the second argument is a
394 //! `uint` specifying the width.
395 //!
396 //! ### Precision
397 //!
398 //! For non-numeric types, this can be considered a "maximum width". If the
399 //! resulting string is longer than this width, then it is truncated down to
400 //! this many characters and only those are emitted.
401 //!
402 //! For integral types, this has no meaning currently.
403 //!
404 //! For floating-point types, this indicates how many digits after the decimal
405 //! point should be printed.
406 //!
407 //! ## Escaping
408 //!
409 //! The literal characters `{` and `}` may be included in a string by preceding
410 //! them with the same character. For example, the `{` character is escaped with
411 //! `{{` and the `}` character is escaped with `}}`.
412
413 #![experimental]
414
415 use string;
416
417 pub use core::fmt::{Formatter, Result, Writer, rt};
418 pub use core::fmt::{Show, String, Octal, Binary};
419 pub use core::fmt::{LowerHex, UpperHex, Pointer};
420 pub use core::fmt::{LowerExp, UpperExp};
421 pub use core::fmt::Error;
422 pub use core::fmt::{Argument, Arguments, write, radix, Radix, RadixFmt};
423
424 #[doc(hidden)]
425 pub use core::fmt::{argument, argumentuint};
426
427 /// The format function takes a precompiled format string and a list of
428 /// arguments, to return the resulting formatted string.
429 ///
430 /// # Arguments
431 ///
432 ///   * args - a structure of arguments generated via the `format_args!` macro.
433 ///
434 /// # Example
435 ///
436 /// ```rust
437 /// use std::fmt;
438 ///
439 /// let s = fmt::format(format_args!("Hello, {}!", "world"));
440 /// assert_eq!(s, "Hello, world!".to_string());
441 /// ```
442 #[experimental = "this is an implementation detail of format! and should not \
443                   be called directly"]
444 pub fn format(args: Arguments) -> string::String {
445     let mut output = string::String::new();
446     let _ = write!(&mut output, "{}", args);
447     output
448 }