]> git.lizzy.rs Git - rust.git/blob - src/libfmt_macros/lib.rs
Rollup merge of #63055 - Mark-Simulacrum:save-analysis-clean-2, r=Xanewok
[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, 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, 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, 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 string width requested for the resulting format
68     pub width: Count,
69     /// The descriptor string representing the name of the format desired for
70     /// this argument, this can be empty or any number of characters, although
71     /// it is required to be one word.
72     pub ty: &'a str,
73 }
74
75 /// Enum describing where an argument for a format can be located.
76 #[derive(Copy, Clone, PartialEq)]
77 pub enum Position {
78     /// The argument is implied to be located at an index
79     ArgumentImplicitlyIs(usize),
80     /// The argument is located at a specific index given in the format
81     ArgumentIs(usize),
82     /// The argument has a name.
83     ArgumentNamed(Symbol),
84 }
85
86 impl Position {
87     pub fn index(&self) -> Option<usize> {
88         match self {
89             ArgumentIs(i) | ArgumentImplicitlyIs(i) => Some(*i),
90             _ => None,
91         }
92     }
93 }
94
95 /// Enum of alignments which are supported.
96 #[derive(Copy, Clone, PartialEq)]
97 pub enum Alignment {
98     /// The value will be aligned to the left.
99     AlignLeft,
100     /// The value will be aligned to the right.
101     AlignRight,
102     /// The value will be aligned in the center.
103     AlignCenter,
104     /// The value will take on a default alignment.
105     AlignUnknown,
106 }
107
108 /// Various flags which can be applied to format strings. The meaning of these
109 /// flags is defined by the formatters themselves.
110 #[derive(Copy, Clone, PartialEq)]
111 pub enum Flag {
112     /// A `+` will be used to denote positive numbers.
113     FlagSignPlus,
114     /// A `-` will be used to denote negative numbers. This is the default.
115     FlagSignMinus,
116     /// An alternate form will be used for the value. In the case of numbers,
117     /// this means that the number will be prefixed with the supplied string.
118     FlagAlternate,
119     /// For numbers, this means that the number will be padded with zeroes,
120     /// and the sign (`+` or `-`) will precede them.
121     FlagSignAwareZeroPad,
122     /// For Debug / `?`, format integers in lower-case hexadecimal.
123     FlagDebugLowerHex,
124     /// For Debug / `?`, format integers in upper-case hexadecimal.
125     FlagDebugUpperHex,
126 }
127
128 /// A count is used for the precision and width parameters of an integer, and
129 /// can reference either an argument or a literal integer.
130 #[derive(Copy, Clone, PartialEq)]
131 pub enum Count {
132     /// The count is specified explicitly.
133     CountIs(usize),
134     /// The count is specified by the argument with the given name.
135     CountIsName(Symbol),
136     /// The count is specified by the argument at the given index.
137     CountIsParam(usize),
138     /// The count is implied and cannot be explicitly specified.
139     CountImplied,
140 }
141
142 pub struct ParseError {
143     pub description: string::String,
144     pub note: Option<string::String>,
145     pub label: string::String,
146     pub span: InnerSpan,
147     pub secondary_label: Option<(string::String, InnerSpan)>,
148 }
149
150 /// The parser structure for interpreting the input format string. This is
151 /// modeled as an iterator over `Piece` structures to form a stream of tokens
152 /// being output.
153 ///
154 /// This is a recursive-descent parser for the sake of simplicity, and if
155 /// necessary there's probably lots of room for improvement performance-wise.
156 pub struct Parser<'a> {
157     input: &'a str,
158     cur: iter::Peekable<str::CharIndices<'a>>,
159     /// Error messages accumulated during parsing
160     pub errors: Vec<ParseError>,
161     /// Current position of implicit positional argument pointer
162     curarg: usize,
163     /// `Some(raw count)` when the string is "raw", used to position spans correctly
164     style: Option<usize>,
165     /// Start and end byte offset of every successfully parsed argument
166     pub arg_places: Vec<InnerSpan>,
167     /// Characters that need to be shifted
168     skips: Vec<usize>,
169     /// Span of the last opening brace seen, used for error reporting
170     last_opening_brace: Option<InnerSpan>,
171     /// Wether the source string is comes from `println!` as opposed to `format!` or `print!`
172     append_newline: bool,
173 }
174
175 impl<'a> Iterator for Parser<'a> {
176     type Item = Piece<'a>;
177
178     fn next(&mut self) -> Option<Piece<'a>> {
179         if let Some(&(pos, c)) = self.cur.peek() {
180             match c {
181                 '{' => {
182                     let curr_last_brace = self.last_opening_brace;
183                     let byte_pos = self.to_span_index(pos);
184                     self.last_opening_brace = Some(byte_pos.to(InnerOffset(byte_pos.0 + 1)));
185                     self.cur.next();
186                     if self.consume('{') {
187                         self.last_opening_brace = curr_last_brace;
188
189                         Some(String(self.string(pos + 1)))
190                     } else {
191                         let arg = self.argument();
192                         if let Some(end) = self.must_consume('}') {
193                             let start = self.to_span_index(pos);
194                             let end = self.to_span_index(end + 1);
195                             self.arg_places.push(start.to(end));
196                         }
197                         Some(NextArgument(arg))
198                     }
199                 }
200                 '}' => {
201                     self.cur.next();
202                     if self.consume('}') {
203                         Some(String(self.string(pos + 1)))
204                     } else {
205                         let err_pos = self.to_span_index(pos);
206                         self.err_with_note(
207                             "unmatched `}` found",
208                             "unmatched `}`",
209                             "if you intended to print `}`, you can escape it using `}}`",
210                             err_pos.to(err_pos),
211                         );
212                         None
213                     }
214                 }
215                 '\n' => {
216                     Some(String(self.string(pos)))
217                 }
218                 _ => Some(String(self.string(pos))),
219             }
220         } else {
221             None
222         }
223     }
224 }
225
226 impl<'a> Parser<'a> {
227     /// Creates a new parser for the given format string
228     pub fn new(
229         s: &'a str,
230         style: Option<usize>,
231         skips: Vec<usize>,
232         append_newline: bool,
233     ) -> Parser<'a> {
234         Parser {
235             input: s,
236             cur: s.char_indices().peekable(),
237             errors: vec![],
238             curarg: 0,
239             style,
240             arg_places: vec![],
241             skips,
242             last_opening_brace: None,
243             append_newline,
244         }
245     }
246
247     /// Notifies of an error. The message doesn't actually need to be of type
248     /// String, but I think it does when this eventually uses conditions so it
249     /// might as well start using it now.
250     fn err<S1: Into<string::String>, S2: Into<string::String>>(
251         &mut self,
252         description: S1,
253         label: S2,
254         span: InnerSpan,
255     ) {
256         self.errors.push(ParseError {
257             description: description.into(),
258             note: None,
259             label: label.into(),
260             span,
261             secondary_label: None,
262         });
263     }
264
265     /// Notifies of an error. The message doesn't actually need to be of type
266     /// String, but I think it does when this eventually uses conditions so it
267     /// might as well start using it now.
268     fn err_with_note<S1: Into<string::String>, S2: Into<string::String>, S3: Into<string::String>>(
269         &mut self,
270         description: S1,
271         label: S2,
272         note: S3,
273         span: InnerSpan,
274     ) {
275         self.errors.push(ParseError {
276             description: description.into(),
277             note: Some(note.into()),
278             label: label.into(),
279             span,
280             secondary_label: None,
281         });
282     }
283
284     /// Optionally consumes the specified character. If the character is not at
285     /// the current position, then the current iterator isn't moved and false is
286     /// returned, otherwise the character is consumed and true is returned.
287     fn consume(&mut self, c: char) -> bool {
288         if let Some(&(_, maybe)) = self.cur.peek() {
289             if c == maybe {
290                 self.cur.next();
291                 true
292             } else {
293                 false
294             }
295         } else {
296             false
297         }
298     }
299
300     fn to_span_index(&self, pos: usize) -> InnerOffset {
301         let mut pos = pos;
302         // This handles the raw string case, the raw argument is the number of #
303         // in r###"..."### (we need to add one because of the `r`).
304         let raw = self.style.map(|raw| raw + 1).unwrap_or(0);
305         for skip in &self.skips {
306             if pos > *skip {
307                 pos += 1;
308             } else if pos == *skip && raw == 0 {
309                 pos += 1;
310             } else {
311                 break;
312             }
313         }
314         InnerOffset(raw + pos + 1)
315     }
316
317     /// Forces consumption of the specified character. If the character is not
318     /// found, an error is emitted.
319     fn must_consume(&mut self, c: char) -> Option<usize> {
320         self.ws();
321
322         if let Some(&(pos, maybe)) = self.cur.peek() {
323             if c == maybe {
324                 self.cur.next();
325                 Some(pos)
326             } else {
327                 let pos = self.to_span_index(pos);
328                 let description = format!("expected `'}}'`, found `{:?}`", maybe);
329                 let label = "expected `}`".to_owned();
330                 let (note, secondary_label) = if c == '}' {
331                     (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
332                      self.last_opening_brace.map(|sp| {
333                         ("because of this opening brace".to_owned(), sp)
334                      }))
335                 } else {
336                     (None, None)
337                 };
338                 self.errors.push(ParseError {
339                     description,
340                     note,
341                     label,
342                     span: pos.to(pos),
343                     secondary_label,
344                 });
345                 None
346             }
347         } else {
348             let description = format!("expected `{:?}` but string was terminated", c);
349             // point at closing `"`
350             let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
351             let pos = self.to_span_index(pos);
352             if c == '}' {
353                 let label = format!("expected `{:?}`", c);
354                 let (note, secondary_label) = if c == '}' {
355                     (Some("if you intended to print `{`, you can escape it using `{{`".to_owned()),
356                      self.last_opening_brace.map(|sp| {
357                         ("because of this opening brace".to_owned(), sp)
358                      }))
359                 } else {
360                     (None, None)
361                 };
362                 self.errors.push(ParseError {
363                     description,
364                     note,
365                     label,
366                     span: pos.to(pos),
367                     secondary_label,
368                 });
369             } else {
370                 self.err(description, format!("expected `{:?}`", c), pos.to(pos));
371             }
372             None
373         }
374     }
375
376     /// Consumes all whitespace characters until the first non-whitespace character
377     fn ws(&mut self) {
378         while let Some(&(_, c)) = self.cur.peek() {
379             if c.is_whitespace() {
380                 self.cur.next();
381             } else {
382                 break;
383             }
384         }
385     }
386
387     /// Parses all of a string which is to be considered a "raw literal" in a
388     /// format string. This is everything outside of the braces.
389     fn string(&mut self, start: usize) -> &'a str {
390         // we may not consume the character, peek the iterator
391         while let Some(&(pos, c)) = self.cur.peek() {
392             match c {
393                 '{' | '}' => {
394                     return &self.input[start..pos];
395                 }
396                 _ => {
397                     self.cur.next();
398                 }
399             }
400         }
401         &self.input[start..self.input.len()]
402     }
403
404     /// Parses an Argument structure, or what's contained within braces inside the format string
405     fn argument(&mut self) -> Argument<'a> {
406         let pos = self.position();
407         let format = self.format();
408
409         // Resolve position after parsing format spec.
410         let pos = match pos {
411             Some(position) => position,
412             None => {
413                 let i = self.curarg;
414                 self.curarg += 1;
415                 ArgumentImplicitlyIs(i)
416             }
417         };
418
419         Argument {
420             position: pos,
421             format,
422         }
423     }
424
425     /// Parses a positional argument for a format. This could either be an
426     /// integer index of an argument, a named argument, or a blank string.
427     /// Returns `Some(parsed_position)` if the position is not implicitly
428     /// consuming a macro argument, `None` if it's the case.
429     fn position(&mut self) -> Option<Position> {
430         if let Some(i) = self.integer() {
431             Some(ArgumentIs(i))
432         } else {
433             match self.cur.peek() {
434                 Some(&(_, c)) if c.is_alphabetic() => {
435                     Some(ArgumentNamed(Symbol::intern(self.word())))
436                 }
437                 Some(&(pos, c)) if c == '_' => {
438                     let invalid_name = self.string(pos);
439                     self.err_with_note(format!("invalid argument name `{}`", invalid_name),
440                                        "invalid argument name",
441                                        "argument names cannot start with an underscore",
442                                         self.to_span_index(pos).to(
443                                             self.to_span_index(pos + invalid_name.len())
444                                         ),
445                                         );
446                     Some(ArgumentNamed(Symbol::intern(invalid_name)))
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             width: CountImplied,
466             ty: &self.input[..0],
467         };
468         if !self.consume(':') {
469             return spec;
470         }
471
472         // fill character
473         if let Some(&(_, c)) = self.cur.peek() {
474             match self.cur.clone().nth(1) {
475                 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
476                     spec.fill = Some(c);
477                     self.cur.next();
478                 }
479                 _ => {}
480             }
481         }
482         // Alignment
483         if self.consume('<') {
484             spec.align = AlignLeft;
485         } else if self.consume('>') {
486             spec.align = AlignRight;
487         } else if self.consume('^') {
488             spec.align = AlignCenter;
489         }
490         // Sign flags
491         if self.consume('+') {
492             spec.flags |= 1 << (FlagSignPlus as u32);
493         } else if self.consume('-') {
494             spec.flags |= 1 << (FlagSignMinus as u32);
495         }
496         // Alternate marker
497         if self.consume('#') {
498             spec.flags |= 1 << (FlagAlternate as u32);
499         }
500         // Width and precision
501         let mut havewidth = false;
502         if self.consume('0') {
503             // small ambiguity with '0$' as a format string. In theory this is a
504             // '0' flag and then an ill-formatted format string with just a '$'
505             // and no count, but this is better if we instead interpret this as
506             // no '0' flag and '0$' as the width instead.
507             if self.consume('$') {
508                 spec.width = CountIsParam(0);
509                 havewidth = true;
510             } else {
511                 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
512             }
513         }
514         if !havewidth {
515             spec.width = self.count();
516         }
517         if self.consume('.') {
518             if self.consume('*') {
519                 // Resolve `CountIsNextParam`.
520                 // We can do this immediately as `position` is resolved later.
521                 let i = self.curarg;
522                 self.curarg += 1;
523                 spec.precision = CountIsParam(i);
524             } else {
525                 spec.precision = self.count();
526             }
527         }
528         // Optional radix followed by the actual format specifier
529         if self.consume('x') {
530             if self.consume('?') {
531                 spec.flags |= 1 << (FlagDebugLowerHex as u32);
532                 spec.ty = "?";
533             } else {
534                 spec.ty = "x";
535             }
536         } else if self.consume('X') {
537             if self.consume('?') {
538                 spec.flags |= 1 << (FlagDebugUpperHex as u32);
539                 spec.ty = "?";
540             } else {
541                 spec.ty = "X";
542             }
543         } else if self.consume('?') {
544             spec.ty = "?";
545         } else {
546             spec.ty = self.word();
547         }
548         spec
549     }
550
551     /// Parses a Count parameter at the current position. This does not check
552     /// for 'CountIsNextParam' because that is only used in precision, not
553     /// width.
554     fn count(&mut self) -> Count {
555         if let Some(i) = self.integer() {
556             if self.consume('$') {
557                 CountIsParam(i)
558             } else {
559                 CountIs(i)
560             }
561         } else {
562             let tmp = self.cur.clone();
563             let word = self.word();
564             if word.is_empty() {
565                 self.cur = tmp;
566                 CountImplied
567             } else if self.consume('$') {
568                 CountIsName(Symbol::intern(word))
569             } else {
570                 self.cur = tmp;
571                 CountImplied
572             }
573         }
574     }
575
576     /// Parses a word starting at the current position. A word is considered to
577     /// be an alphabetic character followed by any number of alphanumeric
578     /// characters.
579     fn word(&mut self) -> &'a str {
580         let start = match self.cur.peek() {
581             Some(&(pos, c)) if c.is_xid_start() => {
582                 self.cur.next();
583                 pos
584             }
585             _ => {
586                 return &self.input[..0];
587             }
588         };
589         while let Some(&(pos, c)) = self.cur.peek() {
590             if c.is_xid_continue() {
591                 self.cur.next();
592             } else {
593                 return &self.input[start..pos];
594             }
595         }
596         &self.input[start..self.input.len()]
597     }
598
599     /// Optionally parses an integer at the current position. This doesn't deal
600     /// with overflow at all, it's just accumulating digits.
601     fn integer(&mut self) -> Option<usize> {
602         let mut cur = 0;
603         let mut found = false;
604         while let Some(&(_, c)) = self.cur.peek() {
605             if let Some(i) = c.to_digit(10) {
606                 cur = cur * 10 + i as usize;
607                 found = true;
608                 self.cur.next();
609             } else {
610                 break;
611             }
612         }
613         if found {
614             Some(cur)
615         } else {
616             None
617         }
618     }
619 }
620
621 #[cfg(test)]
622 mod tests;