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