1 //! Macro support for format strings
3 //! These structures are used when parsing format strings for the compiler.
4 //! Parsing does not happen at runtime: structures of `std::fmt::rt` are
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
8 html_playground_url = "https://play.rust-lang.org/",
9 test(attr(deny(warnings))))]
11 #![deny(rust_2018_idioms)]
12 #![deny(unused_lifetimes)]
15 #![feature(rustc_private)]
27 use syntax_pos::{InnerSpan, Symbol};
29 #[derive(Copy, Clone)]
30 struct InnerOffset(usize);
33 fn to(self, end: InnerOffset) -> InnerSpan {
34 InnerSpan::new(self.0, end.0)
38 /// A piece is a portion of the format string which represents the next part
39 /// to emit. These are emitted as a stream by the `Parser` class.
40 #[derive(Copy, Clone, PartialEq)]
42 /// A literal string which should directly be emitted
44 /// This describes that formatting should process the next argument (as
45 /// specified inside) for emission.
46 NextArgument(Argument<'a>),
49 /// Representation of an argument specification.
50 #[derive(Copy, Clone, PartialEq)]
51 pub struct Argument<'a> {
52 /// Where to find this argument
53 pub position: Position,
54 /// How to format the argument
55 pub format: FormatSpec<'a>,
58 /// Specification for the formatting of an argument in the format string.
59 #[derive(Copy, Clone, PartialEq)]
60 pub struct FormatSpec<'a> {
61 /// Optionally specified character to fill alignment with
62 pub fill: Option<char>,
63 /// Optionally specified alignment
65 /// Packed version of various flags provided
67 /// The integer precision to use
69 /// The string width requested for the resulting format
71 /// The descriptor string representing the name of the format desired for
72 /// this argument, this can be empty or any number of characters, although
73 /// it is required to be one word.
77 /// Enum describing where an argument for a format can be located.
78 #[derive(Copy, Clone, PartialEq)]
80 /// The argument is implied to be located at an index
81 ArgumentImplicitlyIs(usize),
82 /// The argument is located at a specific index given in the format
84 /// The argument has a name.
85 ArgumentNamed(Symbol),
89 pub fn index(&self) -> Option<usize> {
91 ArgumentIs(i) | ArgumentImplicitlyIs(i) => Some(*i),
97 /// Enum of alignments which are supported.
98 #[derive(Copy, Clone, PartialEq)]
100 /// The value will be aligned to the left.
102 /// The value will be aligned to the right.
104 /// The value will be aligned in the center.
106 /// The value will take on a default alignment.
110 /// Various flags which can be applied to format strings. The meaning of these
111 /// flags is defined by the formatters themselves.
112 #[derive(Copy, Clone, PartialEq)]
114 /// A `+` will be used to denote positive numbers.
116 /// A `-` will be used to denote negative numbers. This is the default.
118 /// An alternate form will be used for the value. In the case of numbers,
119 /// this means that the number will be prefixed with the supplied string.
121 /// For numbers, this means that the number will be padded with zeroes,
122 /// and the sign (`+` or `-`) will precede them.
123 FlagSignAwareZeroPad,
124 /// For Debug / `?`, format integers in lower-case hexadecimal.
126 /// For Debug / `?`, format integers in upper-case hexadecimal.
130 /// A count is used for the precision and width parameters of an integer, and
131 /// can reference either an argument or a literal integer.
132 #[derive(Copy, Clone, PartialEq)]
134 /// The count is specified explicitly.
136 /// The count is specified by the argument with the given name.
138 /// The count is specified by the argument at the given index.
140 /// The count is implied and cannot be explicitly specified.
144 pub struct ParseError {
145 pub description: string::String,
146 pub note: Option<string::String>,
147 pub label: string::String,
149 pub secondary_label: Option<(string::String, InnerSpan)>,
152 /// The parser structure for interpreting the input format string. This is
153 /// modeled as an iterator over `Piece` structures to form a stream of tokens
156 /// This is a recursive-descent parser for the sake of simplicity, and if
157 /// necessary there's probably lots of room for improvement performance-wise.
158 pub struct Parser<'a> {
160 cur: iter::Peekable<str::CharIndices<'a>>,
161 /// Error messages accumulated during parsing
162 pub errors: Vec<ParseError>,
163 /// Current position of implicit positional argument pointer
165 /// `Some(raw count)` when the string is "raw", used to position spans correctly
166 style: Option<usize>,
167 /// Start and end byte offset of every successfully parsed argument
168 pub arg_places: Vec<InnerSpan>,
169 /// Characters that need to be shifted
171 /// Span of the last opening brace seen, used for error reporting
172 last_opening_brace: Option<InnerSpan>,
173 /// Wether the source string is comes from `println!` as opposed to `format!` or `print!`
174 append_newline: bool,
177 impl<'a> Iterator for Parser<'a> {
178 type Item = Piece<'a>;
180 fn next(&mut self) -> Option<Piece<'a>> {
181 if let Some(&(pos, c)) = self.cur.peek() {
184 let curr_last_brace = self.last_opening_brace;
185 let byte_pos = self.to_span_index(pos);
186 self.last_opening_brace = Some(byte_pos.to(InnerOffset(byte_pos.0 + 1)));
188 if self.consume('{') {
189 self.last_opening_brace = curr_last_brace;
191 Some(String(self.string(pos + 1)))
193 let arg = self.argument();
194 if let Some(end) = self.must_consume('}') {
195 let start = self.to_span_index(pos);
196 let end = self.to_span_index(end + 1);
197 self.arg_places.push(start.to(end));
199 Some(NextArgument(arg))
204 if self.consume('}') {
205 Some(String(self.string(pos + 1)))
207 let err_pos = self.to_span_index(pos);
209 "unmatched `}` found",
211 "if you intended to print `}`, you can escape it using `}}`",
218 Some(String(self.string(pos)))
220 _ => Some(String(self.string(pos))),
228 impl<'a> Parser<'a> {
229 /// Creates a new parser for the given format string
232 style: Option<usize>,
234 append_newline: bool,
238 cur: s.char_indices().peekable(),
244 last_opening_brace: None,
249 /// Notifies of an error. The message doesn't actually need to be of type
250 /// String, but I think it does when this eventually uses conditions so it
251 /// might as well start using it now.
252 fn err<S1: Into<string::String>, S2: Into<string::String>>(
258 self.errors.push(ParseError {
259 description: description.into(),
263 secondary_label: None,
267 /// Notifies of an error. The message doesn't actually need to be of type
268 /// String, but I think it does when this eventually uses conditions so it
269 /// might as well start using it now.
270 fn err_with_note<S1: Into<string::String>, S2: Into<string::String>, S3: Into<string::String>>(
277 self.errors.push(ParseError {
278 description: description.into(),
279 note: Some(note.into()),
282 secondary_label: None,
286 /// Optionally consumes the specified character. If the character is not at
287 /// the current position, then the current iterator isn't moved and false is
288 /// returned, otherwise the character is consumed and true is returned.
289 fn consume(&mut self, c: char) -> bool {
290 if let Some(&(_, maybe)) = self.cur.peek() {
302 fn to_span_index(&self, pos: usize) -> InnerOffset {
304 // This handles the raw string case, the raw argument is the number of #
305 // in r###"..."### (we need to add one because of the `r`).
306 let raw = self.style.map(|raw| raw + 1).unwrap_or(0);
307 for skip in &self.skips {
310 } else if pos == *skip && raw == 0 {
316 InnerOffset(raw + pos + 1)
319 /// Forces consumption of the specified character. If the character is not
320 /// found, an error is emitted.
321 fn must_consume(&mut self, c: char) -> Option<usize> {
324 if let Some(&(pos, maybe)) = self.cur.peek() {
329 let pos = self.to_span_index(pos);
330 let description = format!("expected `'}}'`, found `{:?}`", maybe);
331 let label = "expected `}`".to_owned();
332 let (note, secondary_label) = if c == '}' {
333 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
334 self.last_opening_brace.map(|sp| {
335 ("because of this opening brace".to_owned(), sp)
340 self.errors.push(ParseError {
350 let description = format!("expected `{:?}` but string was terminated", c);
351 // point at closing `"`
352 let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
353 let pos = self.to_span_index(pos);
355 let label = format!("expected `{:?}`", c);
356 let (note, secondary_label) = if c == '}' {
357 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
358 self.last_opening_brace.map(|sp| {
359 ("because of this opening brace".to_owned(), sp)
364 self.errors.push(ParseError {
372 self.err(description, format!("expected `{:?}`", c), pos.to(pos));
378 /// Consumes all whitespace characters until the first non-whitespace character
380 while let Some(&(_, c)) = self.cur.peek() {
381 if c.is_whitespace() {
389 /// Parses all of a string which is to be considered a "raw literal" in a
390 /// format string. This is everything outside of the braces.
391 fn string(&mut self, start: usize) -> &'a str {
392 // we may not consume the character, peek the iterator
393 while let Some(&(pos, c)) = self.cur.peek() {
396 return &self.input[start..pos];
403 &self.input[start..self.input.len()]
406 /// Parses an Argument structure, or what's contained within braces inside the format string
407 fn argument(&mut self) -> Argument<'a> {
408 let pos = self.position();
409 let format = self.format();
411 // Resolve position after parsing format spec.
412 let pos = match pos {
413 Some(position) => position,
417 ArgumentImplicitlyIs(i)
427 /// Parses a positional argument for a format. This could either be an
428 /// integer index of an argument, a named argument, or a blank string.
429 /// Returns `Some(parsed_position)` if the position is not implicitly
430 /// consuming a macro argument, `None` if it's the case.
431 fn position(&mut self) -> Option<Position> {
432 if let Some(i) = self.integer() {
435 match self.cur.peek() {
436 Some(&(_, c)) if c.is_alphabetic() => {
437 Some(ArgumentNamed(Symbol::intern(self.word())))
439 Some(&(pos, c)) if c == '_' => {
440 let invalid_name = self.string(pos);
441 self.err_with_note(format!("invalid argument name `{}`", invalid_name),
442 "invalid argument name",
443 "argument names cannot start with an underscore",
444 self.to_span_index(pos).to(
445 self.to_span_index(pos + invalid_name.len())
448 Some(ArgumentNamed(Symbol::intern(invalid_name)))
451 // This is an `ArgumentNext`.
452 // Record the fact and do the resolution after parsing the
453 // format spec, to make things like `{:.*}` work.
459 /// Parses a format specifier at the current position, returning all of the
460 /// relevant information in the FormatSpec struct.
461 fn format(&mut self) -> FormatSpec<'a> {
462 let mut spec = FormatSpec {
466 precision: CountImplied,
468 ty: &self.input[..0],
470 if !self.consume(':') {
475 if let Some(&(_, c)) = self.cur.peek() {
476 match self.cur.clone().nth(1) {
477 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
485 if self.consume('<') {
486 spec.align = AlignLeft;
487 } else if self.consume('>') {
488 spec.align = AlignRight;
489 } else if self.consume('^') {
490 spec.align = AlignCenter;
493 if self.consume('+') {
494 spec.flags |= 1 << (FlagSignPlus as u32);
495 } else if self.consume('-') {
496 spec.flags |= 1 << (FlagSignMinus as u32);
499 if self.consume('#') {
500 spec.flags |= 1 << (FlagAlternate as u32);
502 // Width and precision
503 let mut havewidth = false;
504 if self.consume('0') {
505 // small ambiguity with '0$' as a format string. In theory this is a
506 // '0' flag and then an ill-formatted format string with just a '$'
507 // and no count, but this is better if we instead interpret this as
508 // no '0' flag and '0$' as the width instead.
509 if self.consume('$') {
510 spec.width = CountIsParam(0);
513 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
517 spec.width = self.count();
519 if self.consume('.') {
520 if self.consume('*') {
521 // Resolve `CountIsNextParam`.
522 // We can do this immediately as `position` is resolved later.
525 spec.precision = CountIsParam(i);
527 spec.precision = self.count();
530 // Optional radix followed by the actual format specifier
531 if self.consume('x') {
532 if self.consume('?') {
533 spec.flags |= 1 << (FlagDebugLowerHex as u32);
538 } else if self.consume('X') {
539 if self.consume('?') {
540 spec.flags |= 1 << (FlagDebugUpperHex as u32);
545 } else if self.consume('?') {
548 spec.ty = self.word();
553 /// Parses a Count parameter at the current position. This does not check
554 /// for 'CountIsNextParam' because that is only used in precision, not
556 fn count(&mut self) -> Count {
557 if let Some(i) = self.integer() {
558 if self.consume('$') {
564 let tmp = self.cur.clone();
565 let word = self.word();
569 } else if self.consume('$') {
570 CountIsName(Symbol::intern(word))
578 /// Parses a word starting at the current position. A word is considered to
579 /// be an alphabetic character followed by any number of alphanumeric
581 fn word(&mut self) -> &'a str {
582 let start = match self.cur.peek() {
583 Some(&(pos, c)) if c.is_xid_start() => {
588 return &self.input[..0];
591 while let Some(&(pos, c)) = self.cur.peek() {
592 if c.is_xid_continue() {
595 return &self.input[start..pos];
598 &self.input[start..self.input.len()]
601 /// Optionally parses an integer at the current position. This doesn't deal
602 /// with overflow at all, it's just accumulating digits.
603 fn integer(&mut self) -> Option<usize> {
605 let mut found = false;
606 while let Some(&(_, c)) = self.cur.peek() {
607 if let Some(i) = c.to_digit(10) {
608 cur = cur * 10 + i as usize;