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