]> git.lizzy.rs Git - rust.git/blob - src/libstd/fmt.rs
std: Remove format_strbuf!()
[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}", 1); // => "The number is 1"
42 format!("{:?}", (3, 4));          // => "(3, 4)"
43 format!("{value}", value=4);      // => "4"
44 format!("{} {}", 1, 2);           // => "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} {}", 1, 2); // => "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 ```notrust
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} {}", 1, name = 2);              // => "2 1"
99 format!("{a:s} {c:d} {b:?}", a="a", b=(), c=3); // => "a 3 ()"
100 # }
101 ```
102
103 It is illegal to put positional parameters (those without names) after arguments
104 which have names. Like positional parameters, it is illegal to provided named
105 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 ```notrust
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 ```notrust
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 `IoError<()>`). 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 ## Internationalization
321
322 The formatting syntax supported by the `format!` extension supports
323 internationalization by providing "methods" which execute various different
324 outputs depending on the input. The syntax and methods provided are similar to
325 other internationalization systems, so again nothing should seem alien.
326 Currently two methods are supported by this extension: "select" and "plural".
327
328 Each method will execute one of a number of clauses, and then the value of the
329 clause will become what's the result of the argument's format. Inside of the
330 cases, nested argument strings may be provided, but all formatting arguments
331 must not be done through implicit positional means. All arguments inside of each
332 case of a method must be explicitly selected by their name or their integer
333 position.
334
335 Furthermore, whenever a case is running, the special character `#` can be used
336 to reference the string value of the argument which was selected upon. As an
337 example:
338
339 ```rust
340 format!("{0, select, other{#}}", "hello"); // => "hello"
341 ```
342
343 This example is the equivalent of `{0:s}` essentially.
344
345 ### Select
346
347 The select method is a switch over a `&str` parameter, and the parameter *must*
348 be of the type `&str`. An example of the syntax is:
349
350 ```notrust
351 {0, select, male{...} female{...} other{...}}
352 ```
353
354 Breaking this down, the `0`-th argument is selected upon with the `select`
355 method, and then a number of cases follow. Each case is preceded by an
356 identifier which is the match-clause to execute the given arm. In this case,
357 there are two explicit cases, `male` and `female`. The case will be executed if
358 the string argument provided is an exact match to the case selected.
359
360 The `other` case is also a required case for all `select` methods. This arm will
361 be executed if none of the other arms matched the word being selected over.
362
363 ### Plural
364
365 The plural method is a switch statement over a `uint` parameter, and the
366 parameter *must* be a `uint`. A plural method in its full glory can be specified
367 as:
368
369 ```notrust
370 {0, plural, offset=1 =1{...} two{...} many{...} other{...}}
371 ```
372
373 To break this down, the first `0` indicates that this method is selecting over
374 the value of the first positional parameter to the format string. Next, the
375 `plural` method is being executed. An optionally-supplied `offset` is then given
376 which indicates a number to subtract from argument `0` when matching. This is
377 then followed by a list of cases.
378
379 Each case is allowed to supply a specific value to match upon with the syntax
380 `=N`. This case is executed if the value at argument `0` matches N exactly,
381 without taking the offset into account. A case may also be specified by one of
382 five keywords: `zero`, `one`, `two`, `few`, and `many`. These cases are matched
383 on after argument `0` has the offset taken into account. Currently the
384 definitions of `many` and `few` are hardcoded, but they are in theory defined by
385 the current locale.
386
387 Finally, all `plural` methods must have an `other` case supplied which will be
388 executed if none of the other cases match.
389
390 ## Syntax
391
392 The syntax for the formatting language used is drawn from other languages, so it
393 should not be too alien. Arguments are formatted with python-like syntax,
394 meaning that arguments are surrounded by `{}` instead of the C-like `%`. The
395 actual grammar for the formatting syntax is:
396
397 ```notrust
398 format_string := <text> [ format <text> ] *
399 format := '{' [ argument ] [ ':' format_spec ] [ ',' function_spec ] '}'
400 argument := integer | identifier
401
402 format_spec := [[fill]align][sign]['#'][0][width]['.' precision][type]
403 fill := character
404 align := '<' | '>'
405 sign := '+' | '-'
406 width := count
407 precision := count | '*'
408 type := identifier | ''
409 count := parameter | integer
410 parameter := integer '$'
411
412 function_spec := plural | select
413 select := 'select' ',' ( identifier arm ) *
414 plural := 'plural' ',' [ 'offset:' integer ] ( selector arm ) *
415 selector := '=' integer | keyword
416 keyword := 'zero' | 'one' | 'two' | 'few' | 'many' | 'other'
417 arm := '{' format_string '}'
418 ```
419
420 ## Formatting Parameters
421
422 Each argument being formatted can be transformed by a number of formatting
423 parameters (corresponding to `format_spec` in the syntax above). These
424 parameters affect the string representation of what's being formatted. This
425 syntax draws heavily from Python's, so it may seem a bit familiar.
426
427 ### Fill/Alignment
428
429 The fill character is provided normally in conjunction with the `width`
430 parameter. This indicates that if the value being formatted is smaller than
431 `width` some extra characters will be printed around it. The extra characters
432 are specified by `fill`, and the alignment can be one of two options:
433
434 * `<` - the argument is left-aligned in `width` columns
435 * `>` - the argument is right-aligned in `width` columns
436
437 ### Sign/#/0
438
439 These can all be interpreted as flags for a particular formatter.
440
441 * '+' - This is intended for numeric types and indicates that the sign should
442         always be printed. Positive signs are never printed by default, and the
443         negative sign is only printed by default for the `Signed` trait. This
444         flag indicates that the correct sign (+ or -) should always be printed.
445 * '-' - Currently not used
446 * '#' - This flag is indicates that the "alternate" form of printing should be
447         used. By default, this only applies to the integer formatting traits and
448         performs like:
449     * `x` - precedes the argument with a "0x"
450     * `X` - precedes the argument with a "0x"
451     * `t` - precedes the argument with a "0b"
452     * `o` - precedes the argument with a "0o"
453 * '0' - This is used to indicate for integer formats that the padding should
454         both be done with a `0` character as well as be sign-aware. A format
455         like `{:08d}` would yield `00000001` for the integer `1`, while the same
456         format would yield `-0000001` for the integer `-1`. Notice that the
457         negative version has one fewer zero than the positive version.
458
459 ### Width
460
461 This is a parameter for the "minimum width" that the format should take up. If
462 the value's string does not fill up this many characters, then the padding
463 specified by fill/alignment will be used to take up the required space.
464
465 The default fill/alignment for non-numerics is a space and left-aligned. The
466 defaults for numeric formatters is also a space but with right-alignment. If the
467 '0' flag is specified for numerics, then the implicit fill character is '0'.
468
469 The value for the width can also be provided as a `uint` in the list of
470 parameters by using the `2$` syntax indicating that the second argument is a
471 `uint` specifying the width.
472
473 ### Precision
474
475 For non-numeric types, this can be considered a "maximum width". If the
476 resulting string is longer than this width, then it is truncated down to this
477 many characters and only those are emitted.
478
479 For integral types, this has no meaning currently.
480
481 For floating-point types, this indicates how many digits after the decimal point
482 should be printed.
483
484 ## Escaping
485
486 The literal characters `{`, `}`, or `#` may be included in a string by
487 preceding them with the `\` character. Since `\` is already an
488 escape character in Rust strings, a string literal using this escape
489 will look like `"\\{"`.
490
491 */
492
493 use io::Writer;
494 use io;
495 #[cfg(stage0)]
496 use option::None;
497 #[cfg(stage0)]
498 use repr;
499 use result::{Ok, Err};
500 use str::{Str, StrAllocating};
501 use str;
502 use string;
503 use slice::Vector;
504
505 pub use core::fmt::{Formatter, Result, FormatWriter, Show, rt};
506 pub use core::fmt::{Show, Bool, Char, Signed, Unsigned, Octal, Binary};
507 pub use core::fmt::{LowerHex, UpperHex, String, Pointer};
508 pub use core::fmt::{Float, LowerExp, UpperExp};
509 pub use core::fmt::{FormatError, WriteError};
510 pub use core::fmt::{Argument, Arguments, write, radix, Radix, RadixFmt};
511
512 #[doc(hidden)]
513 pub use core::fmt::{argument, argumentstr, argumentuint};
514 #[doc(hidden)]
515 pub use core::fmt::{secret_show, secret_string, secret_unsigned};
516 #[doc(hidden)]
517 pub use core::fmt::{secret_signed, secret_lower_hex, secret_upper_hex};
518 #[doc(hidden)]
519 pub use core::fmt::{secret_bool, secret_char, secret_octal, secret_binary};
520 #[doc(hidden)]
521 pub use core::fmt::{secret_bool, secret_char, secret_octal, secret_binary};
522 #[doc(hidden)]
523 pub use core::fmt::{secret_float, secret_upper_exp, secret_lower_exp};
524 #[doc(hidden)]
525 pub use core::fmt::{secret_pointer};
526
527 #[doc(hidden)]
528 #[cfg(stage0)]
529 pub fn secret_poly<T: Poly>(x: &T, fmt: &mut Formatter) -> Result {
530     // FIXME #11938 - UFCS would make us able call the this method
531     //                directly Poly::fmt(x, fmt).
532     x.fmt(fmt)
533 }
534
535 /// Format trait for the `?` character
536 #[cfg(stage0)]
537 pub trait Poly {
538     /// Formats the value using the given formatter.
539     fn fmt(&self, &mut Formatter) -> Result;
540 }
541
542 /// The format function takes a precompiled format string and a list of
543 /// arguments, to return the resulting formatted string.
544 ///
545 /// # Arguments
546 ///
547 ///   * args - a structure of arguments generated via the `format_args!` macro.
548 ///            Because this structure can only be safely generated at
549 ///            compile-time, this function is safe.
550 ///
551 /// # Example
552 ///
553 /// ```rust
554 /// use std::fmt;
555 ///
556 /// let s = format_args!(fmt::format, "Hello, {}!", "world");
557 /// assert_eq!(s, "Hello, world!".to_string());
558 /// ```
559 pub fn format(args: &Arguments) -> string::String{
560     let mut output = io::MemWriter::new();
561     let _ = write!(&mut output, "{}", args);
562     str::from_utf8(output.unwrap().as_slice()).unwrap().into_string()
563 }
564
565 #[cfg(stage0)]
566 impl<T> Poly for T {
567     fn fmt(&self, f: &mut Formatter) -> Result {
568         match (f.width, f.precision) {
569             (None, None) => {
570                 match repr::write_repr(f, self) {
571                     Ok(()) => Ok(()),
572                     Err(..) => Err(WriteError),
573                 }
574             }
575
576             // If we have a specified width for formatting, then we have to make
577             // this allocation of a new string
578             _ => {
579                 let s = repr::repr_to_str(self);
580                 f.pad(s.as_slice())
581             }
582         }
583     }
584 }
585
586 impl<'a> Writer for Formatter<'a> {
587     fn write(&mut self, b: &[u8]) -> io::IoResult<()> {
588         match (*self).write(b) {
589             Ok(()) => Ok(()),
590             Err(WriteError) => Err(io::standard_error(io::OtherIoError))
591         }
592     }
593 }