]> git.lizzy.rs Git - rust.git/blob - src/libfmt_macros/lib.rs
Rollup merge of #66789 - eddyb:mir-source-scope-local-data, r=oli-obk
[rust.git] / src / libfmt_macros / lib.rs
1 //! Macro support for format strings
2 //!
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
5 //! generated instead.
6
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))))]
10
11 #![feature(nll)]
12 #![feature(rustc_private)]
13 #![feature(unicode_internals)]
14
15 pub use Piece::*;
16 pub use Position::*;
17 pub use Alignment::*;
18 pub use Flag::*;
19 pub use Count::*;
20
21 use std::str;
22 use std::string;
23 use std::iter;
24
25 use syntax_pos::{InnerSpan, Symbol};
26
27 #[derive(Copy, Clone)]
28 struct InnerOffset(usize);
29
30 impl InnerOffset {
31     fn to(self, end: InnerOffset) -> InnerSpan {
32         InnerSpan::new(self.0, end.0)
33     }
34 }
35
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)]
39 pub enum Piece<'a> {
40     /// A literal string which should directly be emitted
41     String(&'a str),
42     /// This describes that formatting should process the next argument (as
43     /// specified inside) for emission.
44     NextArgument(Argument<'a>),
45 }
46
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>,
54 }
55
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.
62     pub align: Alignment,
63     /// Packed version of various flags provided.
64     pub flags: u32,
65     /// The integer precision to use.
66     pub precision: Count,
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.
70     pub width: Count,
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.
76     pub ty: &'a str,
77     /// The span of the descriptor string (for diagnostics).
78     pub ty_span: Option<InnerSpan>,
79 }
80
81 /// Enum describing where an argument for a format can be located.
82 #[derive(Copy, Clone, Debug, PartialEq)]
83 pub enum Position {
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
87     ArgumentIs(usize),
88     /// The argument has a name.
89     ArgumentNamed(Symbol),
90 }
91
92 impl Position {
93     pub fn index(&self) -> Option<usize> {
94         match self {
95             ArgumentIs(i) | ArgumentImplicitlyIs(i) => Some(*i),
96             _ => None,
97         }
98     }
99 }
100
101 /// Enum of alignments which are supported.
102 #[derive(Copy, Clone, Debug, PartialEq)]
103 pub enum Alignment {
104     /// The value will be aligned to the left.
105     AlignLeft,
106     /// The value will be aligned to the right.
107     AlignRight,
108     /// The value will be aligned in the center.
109     AlignCenter,
110     /// The value will take on a default alignment.
111     AlignUnknown,
112 }
113
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)]
117 pub enum Flag {
118     /// A `+` will be used to denote positive numbers.
119     FlagSignPlus,
120     /// A `-` will be used to denote negative numbers. This is the default.
121     FlagSignMinus,
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.
124     FlagAlternate,
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.
129     FlagDebugLowerHex,
130     /// For Debug / `?`, format integers in upper-case hexadecimal.
131     FlagDebugUpperHex,
132 }
133
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)]
137 pub enum Count {
138     /// The count is specified explicitly.
139     CountIs(usize),
140     /// The count is specified by the argument with the given name.
141     CountIsName(Symbol),
142     /// The count is specified by the argument at the given index.
143     CountIsParam(usize),
144     /// The count is implied and cannot be explicitly specified.
145     CountImplied,
146 }
147
148 pub struct ParseError {
149     pub description: string::String,
150     pub note: Option<string::String>,
151     pub label: string::String,
152     pub span: InnerSpan,
153     pub secondary_label: Option<(string::String, InnerSpan)>,
154 }
155
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
158 /// being output.
159 ///
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> {
163     input: &'a str,
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
168     curarg: usize,
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
174     skips: Vec<usize>,
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,
179 }
180
181 impl<'a> Iterator for Parser<'a> {
182     type Item = Piece<'a>;
183
184     fn next(&mut self) -> Option<Piece<'a>> {
185         if let Some(&(pos, c)) = self.cur.peek() {
186             match c {
187                 '{' => {
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)));
191                     self.cur.next();
192                     if self.consume('{') {
193                         self.last_opening_brace = curr_last_brace;
194
195                         Some(String(self.string(pos + 1)))
196                     } else {
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));
202                         }
203                         Some(NextArgument(arg))
204                     }
205                 }
206                 '}' => {
207                     self.cur.next();
208                     if self.consume('}') {
209                         Some(String(self.string(pos + 1)))
210                     } else {
211                         let err_pos = self.to_span_index(pos);
212                         self.err_with_note(
213                             "unmatched `}` found",
214                             "unmatched `}`",
215                             "if you intended to print `}`, you can escape it using `}}`",
216                             err_pos.to(err_pos),
217                         );
218                         None
219                     }
220                 }
221                 '\n' => {
222                     Some(String(self.string(pos)))
223                 }
224                 _ => Some(String(self.string(pos))),
225             }
226         } else {
227             None
228         }
229     }
230 }
231
232 impl<'a> Parser<'a> {
233     /// Creates a new parser for the given format string
234     pub fn new(
235         s: &'a str,
236         style: Option<usize>,
237         skips: Vec<usize>,
238         append_newline: bool,
239     ) -> Parser<'a> {
240         Parser {
241             input: s,
242             cur: s.char_indices().peekable(),
243             errors: vec![],
244             curarg: 0,
245             style,
246             arg_places: vec![],
247             skips,
248             last_opening_brace: None,
249             append_newline,
250         }
251     }
252
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>>(
257         &mut self,
258         description: S1,
259         label: S2,
260         span: InnerSpan,
261     ) {
262         self.errors.push(ParseError {
263             description: description.into(),
264             note: None,
265             label: label.into(),
266             span,
267             secondary_label: None,
268         });
269     }
270
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>>(
275         &mut self,
276         description: S1,
277         label: S2,
278         note: S3,
279         span: InnerSpan,
280     ) {
281         self.errors.push(ParseError {
282             description: description.into(),
283             note: Some(note.into()),
284             label: label.into(),
285             span,
286             secondary_label: None,
287         });
288     }
289
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()
295     }
296
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
300     /// returned.
301     fn consume_pos(&mut self, c: char) -> Option<usize> {
302         if let Some(&(pos, maybe)) = self.cur.peek() {
303             if c == maybe {
304                 self.cur.next();
305                 return Some(pos);
306             }
307         }
308         None
309     }
310
311     fn to_span_index(&self, pos: usize) -> InnerOffset {
312         let mut pos = pos;
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 {
317             if pos > *skip {
318                 pos += 1;
319             } else if pos == *skip && raw == 0 {
320                 pos += 1;
321             } else {
322                 break;
323             }
324         }
325         InnerOffset(raw + pos + 1)
326     }
327
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> {
331         self.ws();
332
333         if let Some(&(pos, maybe)) = self.cur.peek() {
334             if c == maybe {
335                 self.cur.next();
336                 Some(pos)
337             } else {
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)
345                      }))
346                 } else {
347                     (None, None)
348                 };
349                 self.errors.push(ParseError {
350                     description,
351                     note,
352                     label,
353                     span: pos.to(pos),
354                     secondary_label,
355                 });
356                 None
357             }
358         } else {
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);
363             if c == '}' {
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)
369                      }))
370                 } else {
371                     (None, None)
372                 };
373                 self.errors.push(ParseError {
374                     description,
375                     note,
376                     label,
377                     span: pos.to(pos),
378                     secondary_label,
379                 });
380             } else {
381                 self.err(description, format!("expected `{:?}`", c), pos.to(pos));
382             }
383             None
384         }
385     }
386
387     /// Consumes all whitespace characters until the first non-whitespace character
388     fn ws(&mut self) {
389         while let Some(&(_, c)) = self.cur.peek() {
390             if c.is_whitespace() {
391                 self.cur.next();
392             } else {
393                 break;
394             }
395         }
396     }
397
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() {
403             match c {
404                 '{' | '}' => {
405                     return &self.input[start..pos];
406                 }
407                 _ => {
408                     self.cur.next();
409                 }
410             }
411         }
412         &self.input[start..self.input.len()]
413     }
414
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();
419
420         // Resolve position after parsing format spec.
421         let pos = match pos {
422             Some(position) => position,
423             None => {
424                 let i = self.curarg;
425                 self.curarg += 1;
426                 ArgumentImplicitlyIs(i)
427             }
428         };
429
430         Argument {
431             position: pos,
432             format,
433         }
434     }
435
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() {
442             Some(ArgumentIs(i))
443         } else {
444             match self.cur.peek() {
445                 Some(&(_, c)) if rustc_lexer::is_id_start(c) => {
446                     Some(ArgumentNamed(Symbol::intern(self.word())))
447                 }
448
449                 // This is an `ArgumentNext`.
450                 // Record the fact and do the resolution after parsing the
451                 // format spec, to make things like `{:.*}` work.
452                 _ => None,
453             }
454         }
455     }
456
457     /// Parses a format specifier at the current position, returning all of the
458     /// relevant information in the `FormatSpec` struct.
459     fn format(&mut self) -> FormatSpec<'a> {
460         let mut spec = FormatSpec {
461             fill: None,
462             align: AlignUnknown,
463             flags: 0,
464             precision: CountImplied,
465             precision_span: None,
466             width: CountImplied,
467             width_span: None,
468             ty: &self.input[..0],
469             ty_span: None,
470         };
471         if !self.consume(':') {
472             return spec;
473         }
474
475         // fill character
476         if let Some(&(_, c)) = self.cur.peek() {
477             match self.cur.clone().nth(1) {
478                 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
479                     spec.fill = Some(c);
480                     self.cur.next();
481                 }
482                 _ => {}
483             }
484         }
485         // Alignment
486         if self.consume('<') {
487             spec.align = AlignLeft;
488         } else if self.consume('>') {
489             spec.align = AlignRight;
490         } else if self.consume('^') {
491             spec.align = AlignCenter;
492         }
493         // Sign flags
494         if self.consume('+') {
495             spec.flags |= 1 << (FlagSignPlus as u32);
496         } else if self.consume('-') {
497             spec.flags |= 1 << (FlagSignMinus as u32);
498         }
499         // Alternate marker
500         if self.consume('#') {
501             spec.flags |= 1 << (FlagAlternate as u32);
502         }
503         // Width and precision
504         let mut havewidth = false;
505
506         if self.consume('0') {
507             // small ambiguity with '0$' as a format string. In theory this is a
508             // '0' flag and then an ill-formatted format string with just a '$'
509             // and no count, but this is better if we instead interpret this as
510             // no '0' flag and '0$' as the width instead.
511             if self.consume('$') {
512                 spec.width = CountIsParam(0);
513                 havewidth = true;
514             } else {
515                 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
516             }
517         }
518         if !havewidth {
519             let width_span_start = if let Some((pos, _)) = self.cur.peek() {
520                 *pos
521             } else {
522                 0
523             };
524             let (w, sp) = self.count(width_span_start);
525             spec.width = w;
526             spec.width_span = sp;
527         }
528         if let Some(start) = self.consume_pos('.') {
529             if let Some(end) = self.consume_pos('*') {
530                 // Resolve `CountIsNextParam`.
531                 // We can do this immediately as `position` is resolved later.
532                 let i = self.curarg;
533                 self.curarg += 1;
534                 spec.precision = CountIsParam(i);
535                 spec.precision_span =
536                     Some(self.to_span_index(start).to(self.to_span_index(end + 1)));
537             } else {
538                 let (p, sp) = self.count(start);
539                 spec.precision = p;
540                 spec.precision_span = sp;
541             }
542         }
543         let ty_span_start = self.cur.peek().map(|(pos, _)| *pos);
544         // Optional radix followed by the actual format specifier
545         if self.consume('x') {
546             if self.consume('?') {
547                 spec.flags |= 1 << (FlagDebugLowerHex as u32);
548                 spec.ty = "?";
549             } else {
550                 spec.ty = "x";
551             }
552         } else if self.consume('X') {
553             if self.consume('?') {
554                 spec.flags |= 1 << (FlagDebugUpperHex as u32);
555                 spec.ty = "?";
556             } else {
557                 spec.ty = "X";
558             }
559         } else if self.consume('?') {
560             spec.ty = "?";
561         } else {
562             spec.ty = self.word();
563             let ty_span_end = self.cur.peek().map(|(pos, _)| *pos);
564             if !spec.ty.is_empty() {
565                 spec.ty_span = ty_span_start
566                     .and_then(|s| ty_span_end.map(|e| (s, e)))
567                     .map(|(start, end)| self.to_span_index(start).to(self.to_span_index(end)));
568             }
569         }
570         spec
571     }
572
573     /// Parses a `Count` parameter at the current position. This does not check
574     /// for 'CountIsNextParam' because that is only used in precision, not
575     /// width.
576     fn count(&mut self, start: usize) -> (Count, Option<InnerSpan>) {
577         if let Some(i) = self.integer() {
578             if let Some(end) = self.consume_pos('$') {
579                 let span = self.to_span_index(start).to(self.to_span_index(end + 1));
580                 (CountIsParam(i), Some(span))
581             } else {
582                 (CountIs(i), None)
583             }
584         } else {
585             let tmp = self.cur.clone();
586             let word = self.word();
587             if word.is_empty() {
588                 self.cur = tmp;
589                 (CountImplied, None)
590             } else if self.consume('$') {
591                 (CountIsName(Symbol::intern(word)), None)
592             } else {
593                 self.cur = tmp;
594                 (CountImplied, None)
595             }
596         }
597     }
598
599     /// Parses a word starting at the current position. A word is the same as
600     /// Rust identifier, except that it can't start with `_` character.
601     fn word(&mut self) -> &'a str {
602         let start = match self.cur.peek() {
603             Some(&(pos, c)) if rustc_lexer::is_id_start(c) => {
604                 self.cur.next();
605                 pos
606             }
607             _ => {
608                 return "";
609             }
610         };
611         let mut end = None;
612         while let Some(&(pos, c)) = self.cur.peek() {
613             if rustc_lexer::is_id_continue(c) {
614                 self.cur.next();
615             } else {
616                 end = Some(pos);
617                 break;
618             }
619         }
620         let end = end.unwrap_or(self.input.len());
621         let word = &self.input[start..end];
622         if word == "_" {
623             self.err_with_note(
624                 "invalid argument name `_`",
625                 "invalid argument name",
626                 "argument name cannot be a single underscore",
627                 self.to_span_index(start).to(self.to_span_index(end)),
628             );
629         }
630         word
631     }
632
633     /// Optionally parses an integer at the current position. This doesn't deal
634     /// with overflow at all, it's just accumulating digits.
635     fn integer(&mut self) -> Option<usize> {
636         let mut cur = 0;
637         let mut found = false;
638         while let Some(&(_, c)) = self.cur.peek() {
639             if let Some(i) = c.to_digit(10) {
640                 cur = cur * 10 + i as usize;
641                 found = true;
642                 self.cur.next();
643             } else {
644                 break;
645             }
646         }
647         if found {
648             Some(cur)
649         } else {
650             None
651         }
652     }
653 }
654
655 #[cfg(test)]
656 mod tests;