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)]
25 use syntax_pos::{InnerSpan, Symbol};
27 #[derive(Copy, Clone)]
28 struct InnerOffset(usize);
31 fn to(self, end: InnerOffset) -> InnerSpan {
32 InnerSpan::new(self.0, end.0)
36 /// A piece is a portion of the format string which represents the next part
37 /// to emit. These are emitted as a stream by the `Parser` class.
38 #[derive(Copy, Clone, PartialEq)]
40 /// A literal string which should directly be emitted
42 /// This describes that formatting should process the next argument (as
43 /// specified inside) for emission.
44 NextArgument(Argument<'a>),
47 /// Representation of an argument specification.
48 #[derive(Copy, Clone, PartialEq)]
49 pub struct Argument<'a> {
50 /// Where to find this argument
51 pub position: Position,
52 /// How to format the argument
53 pub format: FormatSpec<'a>,
56 /// Specification for the formatting of an argument in the format string.
57 #[derive(Copy, Clone, PartialEq)]
58 pub struct FormatSpec<'a> {
59 /// Optionally specified character to fill alignment with.
60 pub fill: Option<char>,
61 /// Optionally specified alignment.
63 /// Packed version of various flags provided.
65 /// The integer precision to use.
67 /// The span of the precision formatting flag (for diagnostics).
68 pub precision_span: Option<InnerSpan>,
69 /// The string width requested for the resulting format.
71 /// The span of the width formatting flag (for diagnostics).
72 pub width_span: Option<InnerSpan>,
73 /// The descriptor string representing the name of the format desired for
74 /// this argument, this can be empty or any number of characters, although
75 /// it is required to be one word.
79 /// Enum describing where an argument for a format can be located.
80 #[derive(Copy, Clone, PartialEq)]
82 /// The argument is implied to be located at an index
83 ArgumentImplicitlyIs(usize),
84 /// The argument is located at a specific index given in the format
86 /// The argument has a name.
87 ArgumentNamed(Symbol),
91 pub fn index(&self) -> Option<usize> {
93 ArgumentIs(i) | ArgumentImplicitlyIs(i) => Some(*i),
99 /// Enum of alignments which are supported.
100 #[derive(Copy, Clone, PartialEq)]
102 /// The value will be aligned to the left.
104 /// The value will be aligned to the right.
106 /// The value will be aligned in the center.
108 /// The value will take on a default alignment.
112 /// Various flags which can be applied to format strings. The meaning of these
113 /// flags is defined by the formatters themselves.
114 #[derive(Copy, Clone, PartialEq)]
116 /// A `+` will be used to denote positive numbers.
118 /// A `-` will be used to denote negative numbers. This is the default.
120 /// An alternate form will be used for the value. In the case of numbers,
121 /// this means that the number will be prefixed with the supplied string.
123 /// For numbers, this means that the number will be padded with zeroes,
124 /// and the sign (`+` or `-`) will precede them.
125 FlagSignAwareZeroPad,
126 /// For Debug / `?`, format integers in lower-case hexadecimal.
128 /// For Debug / `?`, format integers in upper-case hexadecimal.
132 /// A count is used for the precision and width parameters of an integer, and
133 /// can reference either an argument or a literal integer.
134 #[derive(Copy, Clone, PartialEq)]
136 /// The count is specified explicitly.
138 /// The count is specified by the argument with the given name.
140 /// The count is specified by the argument at the given index.
142 /// The count is implied and cannot be explicitly specified.
146 pub struct ParseError {
147 pub description: string::String,
148 pub note: Option<string::String>,
149 pub label: string::String,
151 pub secondary_label: Option<(string::String, InnerSpan)>,
154 /// The parser structure for interpreting the input format string. This is
155 /// modeled as an iterator over `Piece` structures to form a stream of tokens
158 /// This is a recursive-descent parser for the sake of simplicity, and if
159 /// necessary there's probably lots of room for improvement performance-wise.
160 pub struct Parser<'a> {
162 cur: iter::Peekable<str::CharIndices<'a>>,
163 /// Error messages accumulated during parsing
164 pub errors: Vec<ParseError>,
165 /// Current position of implicit positional argument pointer
167 /// `Some(raw count)` when the string is "raw", used to position spans correctly
168 style: Option<usize>,
169 /// Start and end byte offset of every successfully parsed argument
170 pub arg_places: Vec<InnerSpan>,
171 /// Characters that need to be shifted
173 /// Span of the last opening brace seen, used for error reporting
174 last_opening_brace: Option<InnerSpan>,
175 /// Wether the source string is comes from `println!` as opposed to `format!` or `print!`
176 append_newline: bool,
179 impl<'a> Iterator for Parser<'a> {
180 type Item = Piece<'a>;
182 fn next(&mut self) -> Option<Piece<'a>> {
183 if let Some(&(pos, c)) = self.cur.peek() {
186 let curr_last_brace = self.last_opening_brace;
187 let byte_pos = self.to_span_index(pos);
188 self.last_opening_brace = Some(byte_pos.to(InnerOffset(byte_pos.0 + 1)));
190 if self.consume('{') {
191 self.last_opening_brace = curr_last_brace;
193 Some(String(self.string(pos + 1)))
195 let arg = self.argument();
196 if let Some(end) = self.must_consume('}') {
197 let start = self.to_span_index(pos);
198 let end = self.to_span_index(end + 1);
199 self.arg_places.push(start.to(end));
201 Some(NextArgument(arg))
206 if self.consume('}') {
207 Some(String(self.string(pos + 1)))
209 let err_pos = self.to_span_index(pos);
211 "unmatched `}` found",
213 "if you intended to print `}`, you can escape it using `}}`",
220 Some(String(self.string(pos)))
222 _ => Some(String(self.string(pos))),
230 impl<'a> Parser<'a> {
231 /// Creates a new parser for the given format string
234 style: Option<usize>,
236 append_newline: bool,
240 cur: s.char_indices().peekable(),
246 last_opening_brace: None,
251 /// Notifies of an error. The message doesn't actually need to be of type
252 /// String, but I think it does when this eventually uses conditions so it
253 /// might as well start using it now.
254 fn err<S1: Into<string::String>, S2: Into<string::String>>(
260 self.errors.push(ParseError {
261 description: description.into(),
265 secondary_label: None,
269 /// Notifies of an error. The message doesn't actually need to be of type
270 /// String, but I think it does when this eventually uses conditions so it
271 /// might as well start using it now.
272 fn err_with_note<S1: Into<string::String>, S2: Into<string::String>, S3: Into<string::String>>(
279 self.errors.push(ParseError {
280 description: description.into(),
281 note: Some(note.into()),
284 secondary_label: None,
288 /// Optionally consumes the specified character. If the character is not at
289 /// the current position, then the current iterator isn't moved and `false` is
290 /// returned, otherwise the character is consumed and `true` is returned.
291 fn consume(&mut self, c: char) -> bool {
292 self.consume_pos(c).is_some()
295 /// Optionally consumes the specified character. If the character is not at
296 /// the current position, then the current iterator isn't moved and `None` is
297 /// returned, otherwise the character is consumed and the current position is
299 fn consume_pos(&mut self, c: char) -> Option<usize> {
300 if let Some(&(pos, maybe)) = self.cur.peek() {
309 fn to_span_index(&self, pos: usize) -> InnerOffset {
311 // This handles the raw string case, the raw argument is the number of #
312 // in r###"..."### (we need to add one because of the `r`).
313 let raw = self.style.map(|raw| raw + 1).unwrap_or(0);
314 for skip in &self.skips {
317 } else if pos == *skip && raw == 0 {
323 InnerOffset(raw + pos + 1)
326 /// Forces consumption of the specified character. If the character is not
327 /// found, an error is emitted.
328 fn must_consume(&mut self, c: char) -> Option<usize> {
331 if let Some(&(pos, maybe)) = self.cur.peek() {
336 let pos = self.to_span_index(pos);
337 let description = format!("expected `'}}'`, found `{:?}`", maybe);
338 let label = "expected `}`".to_owned();
339 let (note, secondary_label) = if c == '}' {
340 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
341 self.last_opening_brace.map(|sp| {
342 ("because of this opening brace".to_owned(), sp)
347 self.errors.push(ParseError {
357 let description = format!("expected `{:?}` but string was terminated", c);
358 // point at closing `"`
359 let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
360 let pos = self.to_span_index(pos);
362 let label = format!("expected `{:?}`", c);
363 let (note, secondary_label) = if c == '}' {
364 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
365 self.last_opening_brace.map(|sp| {
366 ("because of this opening brace".to_owned(), sp)
371 self.errors.push(ParseError {
379 self.err(description, format!("expected `{:?}`", c), pos.to(pos));
385 /// Consumes all whitespace characters until the first non-whitespace character
387 while let Some(&(_, c)) = self.cur.peek() {
388 if c.is_whitespace() {
396 /// Parses all of a string which is to be considered a "raw literal" in a
397 /// format string. This is everything outside of the braces.
398 fn string(&mut self, start: usize) -> &'a str {
399 // we may not consume the character, peek the iterator
400 while let Some(&(pos, c)) = self.cur.peek() {
403 return &self.input[start..pos];
410 &self.input[start..self.input.len()]
413 /// Parses an `Argument` structure, or what's contained within braces inside the format string.
414 fn argument(&mut self) -> Argument<'a> {
415 let pos = self.position();
416 let format = self.format();
418 // Resolve position after parsing format spec.
419 let pos = match pos {
420 Some(position) => position,
424 ArgumentImplicitlyIs(i)
434 /// Parses a positional argument for a format. This could either be an
435 /// integer index of an argument, a named argument, or a blank string.
436 /// Returns `Some(parsed_position)` if the position is not implicitly
437 /// consuming a macro argument, `None` if it's the case.
438 fn position(&mut self) -> Option<Position> {
439 if let Some(i) = self.integer() {
442 match self.cur.peek() {
443 Some(&(_, c)) if c.is_alphabetic() => {
444 Some(ArgumentNamed(Symbol::intern(self.word())))
446 Some(&(pos, c)) if c == '_' => {
447 let invalid_name = self.string(pos);
448 self.err_with_note(format!("invalid argument name `{}`", invalid_name),
449 "invalid argument name",
450 "argument names cannot start with an underscore",
451 self.to_span_index(pos).to(
452 self.to_span_index(pos + invalid_name.len())
455 Some(ArgumentNamed(Symbol::intern(invalid_name)))
458 // This is an `ArgumentNext`.
459 // Record the fact and do the resolution after parsing the
460 // format spec, to make things like `{:.*}` work.
466 /// Parses a format specifier at the current position, returning all of the
467 /// relevant information in the `FormatSpec` struct.
468 fn format(&mut self) -> FormatSpec<'a> {
469 let mut spec = FormatSpec {
473 precision: CountImplied,
474 precision_span: None,
477 ty: &self.input[..0],
479 if !self.consume(':') {
484 if let Some(&(_, c)) = self.cur.peek() {
485 match self.cur.clone().nth(1) {
486 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
494 if self.consume('<') {
495 spec.align = AlignLeft;
496 } else if self.consume('>') {
497 spec.align = AlignRight;
498 } else if self.consume('^') {
499 spec.align = AlignCenter;
502 if self.consume('+') {
503 spec.flags |= 1 << (FlagSignPlus as u32);
504 } else if self.consume('-') {
505 spec.flags |= 1 << (FlagSignMinus as u32);
508 if self.consume('#') {
509 spec.flags |= 1 << (FlagAlternate as u32);
511 // Width and precision
512 let mut havewidth = false;
514 if self.consume('0') {
515 // small ambiguity with '0$' as a format string. In theory this is a
516 // '0' flag and then an ill-formatted format string with just a '$'
517 // and no count, but this is better if we instead interpret this as
518 // no '0' flag and '0$' as the width instead.
519 if self.consume('$') {
520 spec.width = CountIsParam(0);
523 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
527 let width_span_start = if let Some((pos, _)) = self.cur.peek() {
532 let (w, sp) = self.count(width_span_start);
534 spec.width_span = sp;
536 if let Some(start) = self.consume_pos('.') {
537 if let Some(end) = self.consume_pos('*') {
538 // Resolve `CountIsNextParam`.
539 // We can do this immediately as `position` is resolved later.
542 spec.precision = CountIsParam(i);
543 spec.precision_span =
544 Some(self.to_span_index(start).to(self.to_span_index(end + 1)));
546 let (p, sp) = self.count(start);
548 spec.precision_span = sp;
551 // Optional radix followed by the actual format specifier
552 if self.consume('x') {
553 if self.consume('?') {
554 spec.flags |= 1 << (FlagDebugLowerHex as u32);
559 } else if self.consume('X') {
560 if self.consume('?') {
561 spec.flags |= 1 << (FlagDebugUpperHex as u32);
566 } else if self.consume('?') {
569 spec.ty = self.word();
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 c != '_' && rustc_lexer::is_id_start(c) => {
609 return &self.input[..0];
612 while let Some(&(pos, c)) = self.cur.peek() {
613 if rustc_lexer::is_id_continue(c) {
616 return &self.input[start..pos];
619 &self.input[start..self.input.len()]
622 /// Optionally parses an integer at the current position. This doesn't deal
623 /// with overflow at all, it's just accumulating digits.
624 fn integer(&mut self) -> Option<usize> {
626 let mut found = false;
627 while let Some(&(_, c)) = self.cur.peek() {
628 if let Some(i) = c.to_digit(10) {
629 cur = cur * 10 + i as usize;