1 // Copyright 2013 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.
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.
11 //! Macro support for format strings
13 //! These structures are used when parsing format strings for the compiler.
14 //! Parsing does not happen at runtime: structures of `std::fmt::rt` are
15 //! generated instead.
17 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
18 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
19 html_root_url = "https://doc.rust-lang.org/nightly/",
20 html_playground_url = "https://play.rust-lang.org/",
21 test(attr(deny(warnings))))]
23 pub use self::Piece::*;
24 pub use self::Position::*;
25 pub use self::Alignment::*;
26 pub use self::Flag::*;
27 pub use self::Count::*;
33 /// A piece is a portion of the format string which represents the next part
34 /// to emit. These are emitted as a stream by the `Parser` class.
35 #[derive(Copy, Clone, PartialEq)]
37 /// A literal string which should directly be emitted
39 /// This describes that formatting should process the next argument (as
40 /// specified inside) for emission.
41 NextArgument(Argument<'a>),
44 /// Representation of an argument specification.
45 #[derive(Copy, Clone, PartialEq)]
46 pub struct Argument<'a> {
47 /// Where to find this argument
48 pub position: Position<'a>,
49 /// How to format the argument
50 pub format: FormatSpec<'a>,
53 /// Specification for the formatting of an argument in the format string.
54 #[derive(Copy, Clone, PartialEq)]
55 pub struct FormatSpec<'a> {
56 /// Optionally specified character to fill alignment with
57 pub fill: Option<char>,
58 /// Optionally specified alignment
60 /// Packed version of various flags provided
62 /// The integer precision to use
63 pub precision: Count<'a>,
64 /// The string width requested for the resulting format
66 /// The descriptor string representing the name of the format desired for
67 /// this argument, this can be empty or any number of characters, although
68 /// it is required to be one word.
72 /// Enum describing where an argument for a format can be located.
73 #[derive(Copy, Clone, PartialEq)]
74 pub enum Position<'a> {
75 /// The argument is implied to be located at an index
76 ArgumentImplicitlyIs(usize),
77 /// The argument is located at a specific index given in the format
79 /// The argument has a name.
80 ArgumentNamed(&'a str),
83 /// Enum of alignments which are supported.
84 #[derive(Copy, Clone, PartialEq)]
86 /// The value will be aligned to the left.
88 /// The value will be aligned to the right.
90 /// The value will be aligned in the center.
92 /// The value will take on a default alignment.
96 /// Various flags which can be applied to format strings. The meaning of these
97 /// flags is defined by the formatters themselves.
98 #[derive(Copy, Clone, PartialEq)]
100 /// A `+` will be used to denote positive numbers.
102 /// A `-` will be used to denote negative numbers. This is the default.
104 /// An alternate form will be used for the value. In the case of numbers,
105 /// this means that the number will be prefixed with the supplied string.
107 /// For numbers, this means that the number will be padded with zeroes,
108 /// and the sign (`+` or `-`) will precede them.
109 FlagSignAwareZeroPad,
110 /// For Debug / `?`, format integers in lower-case hexadecimal.
112 /// For Debug / `?`, format integers in upper-case hexadecimal.
116 /// A count is used for the precision and width parameters of an integer, and
117 /// can reference either an argument or a literal integer.
118 #[derive(Copy, Clone, PartialEq)]
120 /// The count is specified explicitly.
122 /// The count is specified by the argument with the given name.
123 CountIsName(&'a str),
124 /// The count is specified by the argument at the given index.
126 /// The count is implied and cannot be explicitly specified.
130 pub struct ParseError {
131 pub description: string::String,
132 pub note: Option<string::String>,
133 pub label: string::String,
138 /// The parser structure for interpreting the input format string. This is
139 /// modeled as an iterator over `Piece` structures to form a stream of tokens
142 /// This is a recursive-descent parser for the sake of simplicity, and if
143 /// necessary there's probably lots of room for improvement performance-wise.
144 pub struct Parser<'a> {
146 cur: iter::Peekable<str::CharIndices<'a>>,
147 /// Error messages accumulated during parsing
148 pub errors: Vec<ParseError>,
149 /// Current position of implicit positional argument pointer
151 /// `Some(raw count)` when the string is "raw", used to position spans correctly
152 style: Option<usize>,
153 /// How many newlines have been seen in the string so far, to adjust the error spans
154 seen_newlines: usize,
155 /// Start and end byte offset of every successfuly parsed argument
156 pub arg_places: Vec<(usize, usize)>,
159 impl<'a> Iterator for Parser<'a> {
160 type Item = Piece<'a>;
162 fn next(&mut self) -> Option<Piece<'a>> {
163 let raw = self.style.map(|raw| raw + self.seen_newlines).unwrap_or(0);
164 if let Some(&(pos, c)) = self.cur.peek() {
168 if self.consume('{') {
169 Some(String(self.string(pos + 1)))
171 let arg = self.argument();
172 if let Some(arg_pos) = self.must_consume('}').map(|end| {
173 (pos + raw + 1, end + raw + 2)
175 self.arg_places.push(arg_pos);
177 Some(NextArgument(arg))
182 if self.consume('}') {
183 Some(String(self.string(pos + 1)))
185 let err_pos = pos + raw + 1;
187 "unmatched `}` found",
189 "if you intended to print `}`, you can escape it using `}}`",
197 self.seen_newlines += 1;
198 Some(String(self.string(pos)))
200 _ => Some(String(self.string(pos))),
208 impl<'a> Parser<'a> {
209 /// Creates a new parser for the given format string
210 pub fn new(s: &'a str, style: Option<usize>) -> Parser<'a> {
213 cur: s.char_indices().peekable(),
222 /// Notifies of an error. The message doesn't actually need to be of type
223 /// String, but I think it does when this eventually uses conditions so it
224 /// might as well start using it now.
225 fn err<S1: Into<string::String>, S2: Into<string::String>>(
232 self.errors.push(ParseError {
233 description: description.into(),
241 /// Notifies of an error. The message doesn't actually need to be of type
242 /// String, but I think it does when this eventually uses conditions so it
243 /// might as well start using it now.
244 fn err_with_note<S1: Into<string::String>, S2: Into<string::String>, S3: Into<string::String>>(
252 self.errors.push(ParseError {
253 description: description.into(),
254 note: Some(note.into()),
261 /// Optionally consumes the specified character. If the character is not at
262 /// the current position, then the current iterator isn't moved and false is
263 /// returned, otherwise the character is consumed and true is returned.
264 fn consume(&mut self, c: char) -> bool {
265 if let Some(&(_, maybe)) = self.cur.peek() {
277 /// Forces consumption of the specified character. If the character is not
278 /// found, an error is emitted.
279 fn must_consume(&mut self, c: char) -> Option<usize> {
281 let raw = self.style.unwrap_or(0);
283 let padding = raw + self.seen_newlines;
284 if let Some(&(pos, maybe)) = self.cur.peek() {
289 let pos = pos + padding + 1;
290 self.err(format!("expected `{:?}`, found `{:?}`", c, maybe),
291 format!("expected `{}`", c),
297 let msg = format!("expected `{:?}` but string was terminated", c);
298 // point at closing `"`, unless the last char is `\n` to account for `println`
299 let pos = match self.input.chars().last() {
300 Some('\n') => self.input.len(),
301 _ => self.input.len() + 1,
304 self.err_with_note(msg,
305 format!("expected `{:?}`", c),
306 "if you intended to print `{`, you can escape it using `{{`",
310 self.err(msg, format!("expected `{:?}`", c), pos, pos);
316 /// Consumes all whitespace characters until the first non-whitespace
319 while let Some(&(_, c)) = self.cur.peek() {
320 if c.is_whitespace() {
328 /// Parses all of a string which is to be considered a "raw literal" in a
329 /// format string. This is everything outside of the braces.
330 fn string(&mut self, start: usize) -> &'a str {
331 // we may not consume the character, peek the iterator
332 while let Some(&(pos, c)) = self.cur.peek() {
335 return &self.input[start..pos];
342 &self.input[start..self.input.len()]
345 /// Parses an Argument structure, or what's contained within braces inside
346 /// the format string
347 fn argument(&mut self) -> Argument<'a> {
348 let pos = self.position();
349 let format = self.format();
351 // Resolve position after parsing format spec.
352 let pos = match pos {
353 Some(position) => position,
357 ArgumentImplicitlyIs(i)
367 /// Parses a positional argument for a format. This could either be an
368 /// integer index of an argument, a named argument, or a blank string.
369 /// Returns `Some(parsed_position)` if the position is not implicitly
370 /// consuming a macro argument, `None` if it's the case.
371 fn position(&mut self) -> Option<Position<'a>> {
372 if let Some(i) = self.integer() {
375 match self.cur.peek() {
376 Some(&(_, c)) if c.is_alphabetic() => Some(ArgumentNamed(self.word())),
377 Some(&(pos, c)) if c == '_' => {
378 let invalid_name = self.string(pos);
379 self.err_with_note(format!("invalid argument name `{}`", invalid_name),
380 "invalid argument name",
381 "argument names cannot start with an underscore",
382 pos + 1, // add 1 to account for leading `{`
383 pos + 1 + invalid_name.len());
384 Some(ArgumentNamed(invalid_name))
387 // This is an `ArgumentNext`.
388 // Record the fact and do the resolution after parsing the
389 // format spec, to make things like `{:.*}` work.
395 /// Parses a format specifier at the current position, returning all of the
396 /// relevant information in the FormatSpec struct.
397 fn format(&mut self) -> FormatSpec<'a> {
398 let mut spec = FormatSpec {
402 precision: CountImplied,
404 ty: &self.input[..0],
406 if !self.consume(':') {
411 if let Some(&(_, c)) = self.cur.peek() {
412 match self.cur.clone().skip(1).next() {
413 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
421 if self.consume('<') {
422 spec.align = AlignLeft;
423 } else if self.consume('>') {
424 spec.align = AlignRight;
425 } else if self.consume('^') {
426 spec.align = AlignCenter;
429 if self.consume('+') {
430 spec.flags |= 1 << (FlagSignPlus as u32);
431 } else if self.consume('-') {
432 spec.flags |= 1 << (FlagSignMinus as u32);
435 if self.consume('#') {
436 spec.flags |= 1 << (FlagAlternate as u32);
438 // Width and precision
439 let mut havewidth = false;
440 if self.consume('0') {
441 // small ambiguity with '0$' as a format string. In theory this is a
442 // '0' flag and then an ill-formatted format string with just a '$'
443 // and no count, but this is better if we instead interpret this as
444 // no '0' flag and '0$' as the width instead.
445 if self.consume('$') {
446 spec.width = CountIsParam(0);
449 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
453 spec.width = self.count();
455 if self.consume('.') {
456 if self.consume('*') {
457 // Resolve `CountIsNextParam`.
458 // We can do this immediately as `position` is resolved later.
461 spec.precision = CountIsParam(i);
463 spec.precision = self.count();
466 // Optional radix followed by the actual format specifier
467 if self.consume('x') {
468 if self.consume('?') {
469 spec.flags |= 1 << (FlagDebugLowerHex as u32);
474 } else if self.consume('X') {
475 if self.consume('?') {
476 spec.flags |= 1 << (FlagDebugUpperHex as u32);
481 } else if self.consume('?') {
484 spec.ty = self.word();
489 /// Parses a Count parameter at the current position. This does not check
490 /// for 'CountIsNextParam' because that is only used in precision, not
492 fn count(&mut self) -> Count<'a> {
493 if let Some(i) = self.integer() {
494 if self.consume('$') {
500 let tmp = self.cur.clone();
501 let word = self.word();
506 if self.consume('$') {
516 /// Parses a word starting at the current position. A word is considered to
517 /// be an alphabetic character followed by any number of alphanumeric
519 fn word(&mut self) -> &'a str {
520 let start = match self.cur.peek() {
521 Some(&(pos, c)) if c.is_xid_start() => {
526 return &self.input[..0];
529 while let Some(&(pos, c)) = self.cur.peek() {
530 if c.is_xid_continue() {
533 return &self.input[start..pos];
536 &self.input[start..self.input.len()]
539 /// Optionally parses an integer at the current position. This doesn't deal
540 /// with overflow at all, it's just accumulating digits.
541 fn integer(&mut self) -> Option<usize> {
543 let mut found = false;
544 while let Some(&(_, c)) = self.cur.peek() {
545 if let Some(i) = c.to_digit(10) {
546 cur = cur * 10 + i as usize;
565 fn same(fmt: &'static str, p: &[Piece<'static>]) {
566 let parser = Parser::new(fmt, None);
567 assert!(parser.collect::<Vec<Piece<'static>>>() == p);
570 fn fmtdflt() -> FormatSpec<'static> {
575 precision: CountImplied,
581 fn musterr(s: &str) {
582 let mut p = Parser::new(s, None);
584 assert!(!p.errors.is_empty());
589 same("asdf", &[String("asdf")]);
590 same("a{{b", &[String("a"), String("{b")]);
591 same("a}}b", &[String("a"), String("}b")]);
592 same("a}}", &[String("a"), String("}")]);
593 same("}}", &[String("}")]);
594 same("\\}}", &[String("\\"), String("}")]);
619 fn format_nothing() {
621 &[NextArgument(Argument {
622 position: ArgumentImplicitlyIs(0),
627 fn format_position() {
629 &[NextArgument(Argument {
630 position: ArgumentIs(3),
635 fn format_position_nothing_else() {
637 &[NextArgument(Argument {
638 position: ArgumentIs(3),
645 &[NextArgument(Argument {
646 position: ArgumentIs(3),
651 precision: CountImplied,
658 fn format_align_fill() {
660 &[NextArgument(Argument {
661 position: ArgumentIs(3),
666 precision: CountImplied,
672 &[NextArgument(Argument {
673 position: ArgumentIs(3),
678 precision: CountImplied,
684 &[NextArgument(Argument {
685 position: ArgumentIs(3),
690 precision: CountImplied,
699 &[NextArgument(Argument {
700 position: ArgumentImplicitlyIs(0),
705 precision: CountImplied,
711 &[NextArgument(Argument {
712 position: ArgumentImplicitlyIs(0),
717 precision: CountIs(10),
718 width: CountIsParam(10),
723 &[NextArgument(Argument {
724 position: ArgumentImplicitlyIs(1),
729 precision: CountIsParam(0),
735 &[NextArgument(Argument {
736 position: ArgumentImplicitlyIs(0),
741 precision: CountIsParam(10),
747 &[NextArgument(Argument {
748 position: ArgumentImplicitlyIs(0),
753 precision: CountIsName("b"),
754 width: CountIsName("a"),
762 &[NextArgument(Argument {
763 position: ArgumentImplicitlyIs(0),
767 flags: (1 << FlagSignMinus as u32),
768 precision: CountImplied,
774 &[NextArgument(Argument {
775 position: ArgumentImplicitlyIs(0),
779 flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32),
780 precision: CountImplied,
787 fn format_mixture() {
788 same("abcd {3:a} efg",
790 NextArgument(Argument {
791 position: ArgumentIs(3),
796 precision: CountImplied,