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, Debug, 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, Debug, 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, Debug, 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.
77 /// The span of the descriptor string (for diagnostics).
78 pub ty_span: Option<InnerSpan>,
81 /// Enum describing where an argument for a format can be located.
82 #[derive(Copy, Clone, Debug, PartialEq)]
84 /// The argument is implied to be located at an index
85 ArgumentImplicitlyIs(usize),
86 /// The argument is located at a specific index given in the format
88 /// The argument has a name.
89 ArgumentNamed(Symbol),
93 pub fn index(&self) -> Option<usize> {
95 ArgumentIs(i) | ArgumentImplicitlyIs(i) => Some(*i),
101 /// Enum of alignments which are supported.
102 #[derive(Copy, Clone, Debug, PartialEq)]
104 /// The value will be aligned to the left.
106 /// The value will be aligned to the right.
108 /// The value will be aligned in the center.
110 /// The value will take on a default alignment.
114 /// Various flags which can be applied to format strings. The meaning of these
115 /// flags is defined by the formatters themselves.
116 #[derive(Copy, Clone, Debug, PartialEq)]
118 /// A `+` will be used to denote positive numbers.
120 /// A `-` will be used to denote negative numbers. This is the default.
122 /// An alternate form will be used for the value. In the case of numbers,
123 /// this means that the number will be prefixed with the supplied string.
125 /// For numbers, this means that the number will be padded with zeroes,
126 /// and the sign (`+` or `-`) will precede them.
127 FlagSignAwareZeroPad,
128 /// For Debug / `?`, format integers in lower-case hexadecimal.
130 /// For Debug / `?`, format integers in upper-case hexadecimal.
134 /// A count is used for the precision and width parameters of an integer, and
135 /// can reference either an argument or a literal integer.
136 #[derive(Copy, Clone, Debug, PartialEq)]
138 /// The count is specified explicitly.
140 /// The count is specified by the argument with the given name.
142 /// The count is specified by the argument at the given index.
144 /// The count is implied and cannot be explicitly specified.
148 pub struct ParseError {
149 pub description: string::String,
150 pub note: Option<string::String>,
151 pub label: string::String,
153 pub secondary_label: Option<(string::String, InnerSpan)>,
156 /// The parser structure for interpreting the input format string. This is
157 /// modeled as an iterator over `Piece` structures to form a stream of tokens
160 /// This is a recursive-descent parser for the sake of simplicity, and if
161 /// necessary there's probably lots of room for improvement performance-wise.
162 pub struct Parser<'a> {
164 cur: iter::Peekable<str::CharIndices<'a>>,
165 /// Error messages accumulated during parsing
166 pub errors: Vec<ParseError>,
167 /// Current position of implicit positional argument pointer
169 /// `Some(raw count)` when the string is "raw", used to position spans correctly
170 style: Option<usize>,
171 /// Start and end byte offset of every successfully parsed argument
172 pub arg_places: Vec<InnerSpan>,
173 /// Characters that need to be shifted
175 /// Span of the last opening brace seen, used for error reporting
176 last_opening_brace: Option<InnerSpan>,
177 /// Wether the source string is comes from `println!` as opposed to `format!` or `print!`
178 append_newline: bool,
181 impl<'a> Iterator for Parser<'a> {
182 type Item = Piece<'a>;
184 fn next(&mut self) -> Option<Piece<'a>> {
185 if let Some(&(pos, c)) = self.cur.peek() {
188 let curr_last_brace = self.last_opening_brace;
189 let byte_pos = self.to_span_index(pos);
190 self.last_opening_brace = Some(byte_pos.to(InnerOffset(byte_pos.0 + 1)));
192 if self.consume('{') {
193 self.last_opening_brace = curr_last_brace;
195 Some(String(self.string(pos + 1)))
197 let arg = self.argument();
198 if let Some(end) = self.must_consume('}') {
199 let start = self.to_span_index(pos);
200 let end = self.to_span_index(end + 1);
201 self.arg_places.push(start.to(end));
203 Some(NextArgument(arg))
208 if self.consume('}') {
209 Some(String(self.string(pos + 1)))
211 let err_pos = self.to_span_index(pos);
213 "unmatched `}` found",
215 "if you intended to print `}`, you can escape it using `}}`",
222 Some(String(self.string(pos)))
224 _ => Some(String(self.string(pos))),
232 impl<'a> Parser<'a> {
233 /// Creates a new parser for the given format string
236 style: Option<usize>,
238 append_newline: bool,
242 cur: s.char_indices().peekable(),
248 last_opening_brace: None,
253 /// Notifies of an error. The message doesn't actually need to be of type
254 /// String, but I think it does when this eventually uses conditions so it
255 /// might as well start using it now.
256 fn err<S1: Into<string::String>, S2: Into<string::String>>(
262 self.errors.push(ParseError {
263 description: description.into(),
267 secondary_label: None,
271 /// Notifies of an error. The message doesn't actually need to be of type
272 /// String, but I think it does when this eventually uses conditions so it
273 /// might as well start using it now.
274 fn err_with_note<S1: Into<string::String>, S2: Into<string::String>, S3: Into<string::String>>(
281 self.errors.push(ParseError {
282 description: description.into(),
283 note: Some(note.into()),
286 secondary_label: None,
290 /// Optionally consumes the specified character. If the character is not at
291 /// the current position, then the current iterator isn't moved and `false` is
292 /// returned, otherwise the character is consumed and `true` is returned.
293 fn consume(&mut self, c: char) -> bool {
294 self.consume_pos(c).is_some()
297 /// Optionally consumes the specified character. If the character is not at
298 /// the current position, then the current iterator isn't moved and `None` is
299 /// returned, otherwise the character is consumed and the current position is
301 fn consume_pos(&mut self, c: char) -> Option<usize> {
302 if let Some(&(pos, maybe)) = self.cur.peek() {
311 fn to_span_index(&self, pos: usize) -> InnerOffset {
313 // This handles the raw string case, the raw argument is the number of #
314 // in r###"..."### (we need to add one because of the `r`).
315 let raw = self.style.map(|raw| raw + 1).unwrap_or(0);
316 for skip in &self.skips {
319 } else if pos == *skip && raw == 0 {
325 InnerOffset(raw + pos + 1)
328 /// Forces consumption of the specified character. If the character is not
329 /// found, an error is emitted.
330 fn must_consume(&mut self, c: char) -> Option<usize> {
333 if let Some(&(pos, maybe)) = self.cur.peek() {
338 let pos = self.to_span_index(pos);
339 let description = format!("expected `'}}'`, found `{:?}`", maybe);
340 let label = "expected `}`".to_owned();
341 let (note, secondary_label) = if c == '}' {
342 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
343 self.last_opening_brace.map(|sp| {
344 ("because of this opening brace".to_owned(), sp)
349 self.errors.push(ParseError {
359 let description = format!("expected `{:?}` but string was terminated", c);
360 // point at closing `"`
361 let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
362 let pos = self.to_span_index(pos);
364 let label = format!("expected `{:?}`", c);
365 let (note, secondary_label) = if c == '}' {
366 (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
367 self.last_opening_brace.map(|sp| {
368 ("because of this opening brace".to_owned(), sp)
373 self.errors.push(ParseError {
381 self.err(description, format!("expected `{:?}`", c), pos.to(pos));
387 /// Consumes all whitespace characters until the first non-whitespace character
389 while let Some(&(_, c)) = self.cur.peek() {
390 if c.is_whitespace() {
398 /// Parses all of a string which is to be considered a "raw literal" in a
399 /// format string. This is everything outside of the braces.
400 fn string(&mut self, start: usize) -> &'a str {
401 // we may not consume the character, peek the iterator
402 while let Some(&(pos, c)) = self.cur.peek() {
405 return &self.input[start..pos];
412 &self.input[start..self.input.len()]
415 /// Parses an `Argument` structure, or what's contained within braces inside the format string.
416 fn argument(&mut self) -> Argument<'a> {
417 let pos = self.position();
418 let format = self.format();
420 // Resolve position after parsing format spec.
421 let pos = match pos {
422 Some(position) => position,
426 ArgumentImplicitlyIs(i)
436 /// Parses a positional argument for a format. This could either be an
437 /// integer index of an argument, a named argument, or a blank string.
438 /// Returns `Some(parsed_position)` if the position is not implicitly
439 /// consuming a macro argument, `None` if it's the case.
440 fn position(&mut self) -> Option<Position> {
441 if let Some(i) = self.integer() {
444 match self.cur.peek() {
445 Some(&(_, c)) if c.is_alphabetic() => {
446 Some(ArgumentNamed(Symbol::intern(self.word())))
448 Some(&(pos, c)) if c == '_' => {
449 let invalid_name = self.string(pos);
450 self.err_with_note(format!("invalid argument name `{}`", invalid_name),
451 "invalid argument name",
452 "argument names cannot start with an underscore",
453 self.to_span_index(pos).to(
454 self.to_span_index(pos + invalid_name.len())
457 Some(ArgumentNamed(Symbol::intern(invalid_name)))
460 // This is an `ArgumentNext`.
461 // Record the fact and do the resolution after parsing the
462 // format spec, to make things like `{:.*}` work.
468 /// Parses a format specifier at the current position, returning all of the
469 /// relevant information in the `FormatSpec` struct.
470 fn format(&mut self) -> FormatSpec<'a> {
471 let mut spec = FormatSpec {
475 precision: CountImplied,
476 precision_span: None,
479 ty: &self.input[..0],
482 if !self.consume(':') {
487 if let Some(&(_, c)) = self.cur.peek() {
488 match self.cur.clone().nth(1) {
489 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
497 if self.consume('<') {
498 spec.align = AlignLeft;
499 } else if self.consume('>') {
500 spec.align = AlignRight;
501 } else if self.consume('^') {
502 spec.align = AlignCenter;
505 if self.consume('+') {
506 spec.flags |= 1 << (FlagSignPlus as u32);
507 } else if self.consume('-') {
508 spec.flags |= 1 << (FlagSignMinus as u32);
511 if self.consume('#') {
512 spec.flags |= 1 << (FlagAlternate as u32);
514 // Width and precision
515 let mut havewidth = false;
517 if self.consume('0') {
518 // small ambiguity with '0$' as a format string. In theory this is a
519 // '0' flag and then an ill-formatted format string with just a '$'
520 // and no count, but this is better if we instead interpret this as
521 // no '0' flag and '0$' as the width instead.
522 if self.consume('$') {
523 spec.width = CountIsParam(0);
526 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
530 let width_span_start = if let Some((pos, _)) = self.cur.peek() {
535 let (w, sp) = self.count(width_span_start);
537 spec.width_span = sp;
539 if let Some(start) = self.consume_pos('.') {
540 if let Some(end) = self.consume_pos('*') {
541 // Resolve `CountIsNextParam`.
542 // We can do this immediately as `position` is resolved later.
545 spec.precision = CountIsParam(i);
546 spec.precision_span =
547 Some(self.to_span_index(start).to(self.to_span_index(end + 1)));
549 let (p, sp) = self.count(start);
551 spec.precision_span = sp;
554 let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
555 // Optional radix followed by the actual format specifier
556 if self.consume('x') {
557 if self.consume('?') {
558 spec.flags |= 1 << (FlagDebugLowerHex as u32);
563 } else if self.consume('X') {
564 if self.consume('?') {
565 spec.flags |= 1 << (FlagDebugUpperHex as u32);
570 } else if self.consume('?') {
573 spec.ty = self.word();
574 let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
575 if !spec.ty.is_empty() {
576 spec.ty_span = ty_span_start
577 .and_then(|s| ty_span_end.map(|e| (s, e)))
578 .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
584 /// Parses a `Count` parameter at the current position. This does not check
585 /// for 'CountIsNextParam' because that is only used in precision, not
587 fn count(&mut self, start: usize) -> (Count, Option<InnerSpan>) {
588 if let Some(i) = self.integer() {
589 if let Some(end) = self.consume_pos('$') {
590 let span = self.to_span_index(start).to(self.to_span_index(end + 1));
591 (CountIsParam(i), Some(span))
596 let tmp = self.cur.clone();
597 let word = self.word();
601 } else if self.consume('$') {
602 (CountIsName(Symbol::intern(word)), None)
610 /// Parses a word starting at the current position. A word is the same as
611 /// Rust identifier, except that it can't start with `_` character.
612 fn word(&mut self) -> &'a str {
613 let start = match self.cur.peek() {
614 Some(&(pos, c)) if c != '_' && rustc_lexer::is_id_start(c) => {
619 return &self.input[..0];
622 while let Some(&(pos, c)) = self.cur.peek() {
623 if rustc_lexer::is_id_continue(c) {
626 return &self.input[start..pos];
629 &self.input[start..self.input.len()]
632 /// Optionally parses an integer at the current position. This doesn't deal
633 /// with overflow at all, it's just accumulating digits.
634 fn integer(&mut self) -> Option<usize> {
636 let mut found = false;
637 while let Some(&(_, c)) = self.cur.peek() {
638 if let Some(i) = c.to_digit(10) {
639 cur = cur * 10 + i as usize;