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))))]
12 #![feature(rustc_private)]
13 #![feature(unicode_internals)]
14 #![feature(bool_to_option)]
26 use syntax_pos::{InnerSpan, Symbol};
28 #[derive(Copy, Clone)]
29 struct InnerOffset(usize);
32 fn to(self, end: InnerOffset) -> InnerSpan {
33 InnerSpan::new(self.0, end.0)
37 /// A piece is a portion of the format string which represents the next part
38 /// to emit. These are emitted as a stream by the `Parser` class.
39 #[derive(Copy, Clone, Debug, PartialEq)]
41 /// A literal string which should directly be emitted
43 /// This describes that formatting should process the next argument (as
44 /// specified inside) for emission.
45 NextArgument(Argument<'a>),
48 /// Representation of an argument specification.
49 #[derive(Copy, Clone, Debug, PartialEq)]
50 pub struct Argument<'a> {
51 /// Where to find this argument
52 pub position: Position,
53 /// How to format the argument
54 pub format: FormatSpec<'a>,
57 /// Specification for the formatting of an argument in the format string.
58 #[derive(Copy, Clone, Debug, PartialEq)]
59 pub struct FormatSpec<'a> {
60 /// Optionally specified character to fill alignment with.
61 pub fill: Option<char>,
62 /// Optionally specified alignment.
64 /// Packed version of various flags provided.
66 /// The integer precision to use.
68 /// The span of the precision formatting flag (for diagnostics).
69 pub precision_span: Option<InnerSpan>,
70 /// The string width requested for the resulting format.
72 /// The span of the width formatting flag (for diagnostics).
73 pub width_span: Option<InnerSpan>,
74 /// The descriptor string representing the name of the format desired for
75 /// this argument, this can be empty or any number of characters, although
76 /// it is required to be one word.
78 /// The span of the descriptor string (for diagnostics).
79 pub ty_span: Option<InnerSpan>,
82 /// Enum describing where an argument for a format can be located.
83 #[derive(Copy, Clone, Debug, PartialEq)]
85 /// The argument is implied to be located at an index
86 ArgumentImplicitlyIs(usize),
87 /// The argument is located at a specific index given in the format
89 /// The argument has a name.
90 ArgumentNamed(Symbol),
94 pub fn index(&self) -> Option<usize> {
96 ArgumentIs(i) | ArgumentImplicitlyIs(i) => Some(*i),
102 /// Enum of alignments which are supported.
103 #[derive(Copy, Clone, Debug, PartialEq)]
105 /// The value will be aligned to the left.
107 /// The value will be aligned to the right.
109 /// The value will be aligned in the center.
111 /// The value will take on a default alignment.
115 /// Various flags which can be applied to format strings. The meaning of these
116 /// flags is defined by the formatters themselves.
117 #[derive(Copy, Clone, Debug, PartialEq)]
119 /// A `+` will be used to denote positive numbers.
121 /// A `-` will be used to denote negative numbers. This is the default.
123 /// An alternate form will be used for the value. In the case of numbers,
124 /// this means that the number will be prefixed with the supplied string.
126 /// For numbers, this means that the number will be padded with zeroes,
127 /// and the sign (`+` or `-`) will precede them.
128 FlagSignAwareZeroPad,
129 /// For Debug / `?`, format integers in lower-case hexadecimal.
131 /// For Debug / `?`, format integers in upper-case hexadecimal.
135 /// A count is used for the precision and width parameters of an integer, and
136 /// can reference either an argument or a literal integer.
137 #[derive(Copy, Clone, Debug, PartialEq)]
139 /// The count is specified explicitly.
141 /// The count is specified by the argument with the given name.
143 /// The count is specified by the argument at the given index.
145 /// The count is implied and cannot be explicitly specified.
149 pub struct ParseError {
150 pub description: string::String,
151 pub note: Option<string::String>,
152 pub label: string::String,
154 pub secondary_label: Option<(string::String, InnerSpan)>,
157 /// The parser structure for interpreting the input format string. This is
158 /// modeled as an iterator over `Piece` structures to form a stream of tokens
161 /// This is a recursive-descent parser for the sake of simplicity, and if
162 /// necessary there's probably lots of room for improvement performance-wise.
163 pub struct Parser<'a> {
165 cur: iter::Peekable<str::CharIndices<'a>>,
166 /// Error messages accumulated during parsing
167 pub errors: Vec<ParseError>,
168 /// Current position of implicit positional argument pointer
170 /// `Some(raw count)` when the string is "raw", used to position spans correctly
171 style: Option<usize>,
172 /// Start and end byte offset of every successfully parsed argument
173 pub arg_places: Vec<InnerSpan>,
174 /// Characters that need to be shifted
176 /// Span of the last opening brace seen, used for error reporting
177 last_opening_brace: Option<InnerSpan>,
178 /// Wether the source string is comes from `println!` as opposed to `format!` or `print!`
179 append_newline: bool,
182 impl<'a> Iterator for Parser<'a> {
183 type Item = Piece<'a>;
185 fn next(&mut self) -> Option<Piece<'a>> {
186 if let Some(&(pos, c)) = self.cur.peek() {
189 let curr_last_brace = self.last_opening_brace;
190 let byte_pos = self.to_span_index(pos);
191 self.last_opening_brace = Some(byte_pos.to(InnerOffset(byte_pos.0 + 1)));
193 if self.consume('{') {
194 self.last_opening_brace = curr_last_brace;
196 Some(String(self.string(pos + 1)))
198 let arg = self.argument();
199 if let Some(end) = self.must_consume('}') {
200 let start = self.to_span_index(pos);
201 let end = self.to_span_index(end + 1);
202 self.arg_places.push(start.to(end));
204 Some(NextArgument(arg))
209 if self.consume('}') {
210 Some(String(self.string(pos + 1)))
212 let err_pos = self.to_span_index(pos);
214 "unmatched `}` found",
216 "if you intended to print `}`, you can escape it using `}}`",
223 Some(String(self.string(pos)))
225 _ => Some(String(self.string(pos))),
233 impl<'a> Parser<'a> {
234 /// Creates a new parser for the given format string
237 style: Option<usize>,
239 append_newline: bool,
243 cur: s.char_indices().peekable(),
249 last_opening_brace: None,
254 /// Notifies of an error. The message doesn't actually need to be of type
255 /// String, but I think it does when this eventually uses conditions so it
256 /// might as well start using it now.
257 fn err<S1: Into<string::String>, S2: Into<string::String>>(
263 self.errors.push(ParseError {
264 description: description.into(),
268 secondary_label: None,
272 /// Notifies of an error. The message doesn't actually need to be of type
273 /// String, but I think it does when this eventually uses conditions so it
274 /// might as well start using it now.
275 fn err_with_note<S1: Into<string::String>, S2: Into<string::String>, S3: Into<string::String>>(
282 self.errors.push(ParseError {
283 description: description.into(),
284 note: Some(note.into()),
287 secondary_label: None,
291 /// Optionally consumes the specified character. If the character is not at
292 /// the current position, then the current iterator isn't moved and `false` is
293 /// returned, otherwise the character is consumed and `true` is returned.
294 fn consume(&mut self, c: char) -> bool {
295 self.consume_pos(c).is_some()
298 /// Optionally consumes the specified character. If the character is not at
299 /// the current position, then the current iterator isn't moved and `None` is
300 /// returned, otherwise the character is consumed and the current position is
302 fn consume_pos(&mut self, c: char) -> Option<usize> {
303 if let Some(&(pos, maybe)) = self.cur.peek() {
312 fn to_span_index(&self, pos: usize) -> InnerOffset {
314 // This handles the raw string case, the raw argument is the number of #
315 // in r###"..."### (we need to add one because of the `r`).
316 let raw = self.style.map(|raw| raw + 1).unwrap_or(0);
317 for skip in &self.skips {
320 } else if pos == *skip && raw == 0 {
326 InnerOffset(raw + pos + 1)
329 /// Forces consumption of the specified character. If the character is not
330 /// found, an error is emitted.
331 fn must_consume(&mut self, c: char) -> Option<usize> {
334 if let Some(&(pos, maybe)) = self.cur.peek() {
339 let pos = self.to_span_index(pos);
340 let description = format!("expected `'}}'`, found `{:?}`", maybe);
341 let label = "expected `}`".to_owned();
342 let (note, secondary_label) = if c == '}' {
343 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
344 self.last_opening_brace.map(|sp| {
345 ("because of this opening brace".to_owned(), sp)
350 self.errors.push(ParseError {
360 let description = format!("expected `{:?}` but string was terminated", c);
361 // point at closing `"`
362 let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
363 let pos = self.to_span_index(pos);
365 let label = format!("expected `{:?}`", c);
366 let (note, secondary_label) = if c == '}' {
367 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
368 self.last_opening_brace.map(|sp| {
369 ("because of this opening brace".to_owned(), sp)
374 self.errors.push(ParseError {
382 self.err(description, format!("expected `{:?}`", c), pos.to(pos));
388 /// Consumes all whitespace characters until the first non-whitespace character
390 while let Some(&(_, c)) = self.cur.peek() {
391 if c.is_whitespace() {
399 /// Parses all of a string which is to be considered a "raw literal" in a
400 /// format string. This is everything outside of the braces.
401 fn string(&mut self, start: usize) -> &'a str {
402 // we may not consume the character, peek the iterator
403 while let Some(&(pos, c)) = self.cur.peek() {
406 return &self.input[start..pos];
413 &self.input[start..self.input.len()]
416 /// Parses an `Argument` structure, or what's contained within braces inside the format string.
417 fn argument(&mut self) -> Argument<'a> {
418 let pos = self.position();
419 let format = self.format();
421 // Resolve position after parsing format spec.
422 let pos = match pos {
423 Some(position) => position,
427 ArgumentImplicitlyIs(i)
437 /// Parses a positional argument for a format. This could either be an
438 /// integer index of an argument, a named argument, or a blank string.
439 /// Returns `Some(parsed_position)` if the position is not implicitly
440 /// consuming a macro argument, `None` if it's the case.
441 fn position(&mut self) -> Option<Position> {
442 if let Some(i) = self.integer() {
445 match self.cur.peek() {
446 Some(&(_, c)) if rustc_lexer::is_id_start(c) => {
447 Some(ArgumentNamed(Symbol::intern(self.word())))
450 // This is an `ArgumentNext`.
451 // Record the fact and do the resolution after parsing the
452 // format spec, to make things like `{:.*}` work.
458 /// Parses a format specifier at the current position, returning all of the
459 /// relevant information in the `FormatSpec` struct.
460 fn format(&mut self) -> FormatSpec<'a> {
461 let mut spec = FormatSpec {
465 precision: CountImplied,
466 precision_span: None,
469 ty: &self.input[..0],
472 if !self.consume(':') {
477 if let Some(&(_, c)) = self.cur.peek() {
478 match self.cur.clone().nth(1) {
479 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
487 if self.consume('<') {
488 spec.align = AlignLeft;
489 } else if self.consume('>') {
490 spec.align = AlignRight;
491 } else if self.consume('^') {
492 spec.align = AlignCenter;
495 if self.consume('+') {
496 spec.flags |= 1 << (FlagSignPlus as u32);
497 } else if self.consume('-') {
498 spec.flags |= 1 << (FlagSignMinus as u32);
501 if self.consume('#') {
502 spec.flags |= 1 << (FlagAlternate as u32);
504 // Width and precision
505 let mut havewidth = false;
507 if self.consume('0') {
508 // small ambiguity with '0$' as a format string. In theory this is a
509 // '0' flag and then an ill-formatted format string with just a '$'
510 // and no count, but this is better if we instead interpret this as
511 // no '0' flag and '0$' as the width instead.
512 if self.consume('$') {
513 spec.width = CountIsParam(0);
516 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
520 let width_span_start = if let Some((pos, _)) = self.cur.peek() {
525 let (w, sp) = self.count(width_span_start);
527 spec.width_span = sp;
529 if let Some(start) = self.consume_pos('.') {
530 if let Some(end) = self.consume_pos('*') {
531 // Resolve `CountIsNextParam`.
532 // We can do this immediately as `position` is resolved later.
535 spec.precision = CountIsParam(i);
536 spec.precision_span =
537 Some(self.to_span_index(start).to(self.to_span_index(end + 1)));
539 let (p, sp) = self.count(start);
541 spec.precision_span = sp;
544 let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
545 // Optional radix followed by the actual format specifier
546 if self.consume('x') {
547 if self.consume('?') {
548 spec.flags |= 1 << (FlagDebugLowerHex as u32);
553 } else if self.consume('X') {
554 if self.consume('?') {
555 spec.flags |= 1 << (FlagDebugUpperHex as u32);
560 } else if self.consume('?') {
563 spec.ty = self.word();
564 let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
565 if !spec.ty.is_empty() {
566 spec.ty_span = ty_span_start
567 .and_then(|s| ty_span_end.map(|e| (s, e)))
568 .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
574 /// Parses a `Count` parameter at the current position. This does not check
575 /// for 'CountIsNextParam' because that is only used in precision, not
577 fn count(&mut self, start: usize) -> (Count, Option<InnerSpan>) {
578 if let Some(i) = self.integer() {
579 if let Some(end) = self.consume_pos('$') {
580 let span = self.to_span_index(start).to(self.to_span_index(end + 1));
581 (CountIsParam(i), Some(span))
586 let tmp = self.cur.clone();
587 let word = self.word();
591 } else if self.consume('$') {
592 (CountIsName(Symbol::intern(word)), None)
600 /// Parses a word starting at the current position. A word is the same as
601 /// Rust identifier, except that it can't start with `_` character.
602 fn word(&mut self) -> &'a str {
603 let start = match self.cur.peek() {
604 Some(&(pos, c)) if rustc_lexer::is_id_start(c) => {
613 while let Some(&(pos, c)) = self.cur.peek() {
614 if rustc_lexer::is_id_continue(c) {
621 let end = end.unwrap_or(self.input.len());
622 let word = &self.input[start..end];
625 "invalid argument name `_`",
626 "invalid argument name",
627 "argument name cannot be a single underscore",
628 self.to_span_index(start).to(self.to_span_index(end)),
634 /// Optionally parses an integer at the current position. This doesn't deal
635 /// with overflow at all, it's just accumulating digits.
636 fn integer(&mut self) -> Option<usize> {
638 let mut found = false;
639 while let Some(&(_, c)) = self.cur.peek() {
640 if let Some(i) = c.to_digit(10) {
641 cur = cur * 10 + i as usize;