]> git.lizzy.rs Git - rust.git/blob - src/libfmt_macros/lib.rs
Auto merge of #53088 - matthewjasper:closure-region-spans, r=nikomatsakis
[rust.git] / src / libfmt_macros / lib.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Macro support for format strings
12 //!
13 //! These structures are used when parsing format strings for the compiler.
14 //! Parsing does not happen at runtime: structures of `std::fmt::rt` are
15 //! generated instead.
16
17 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
18        html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
19        html_root_url = "https://doc.rust-lang.org/nightly/",
20        html_playground_url = "https://play.rust-lang.org/",
21        test(attr(deny(warnings))))]
22
23 pub use self::Piece::*;
24 pub use self::Position::*;
25 pub use self::Alignment::*;
26 pub use self::Flag::*;
27 pub use self::Count::*;
28
29 use std::str;
30 use std::string;
31 use std::iter;
32
33 /// A piece is a portion of the format string which represents the next part
34 /// to emit. These are emitted as a stream by the `Parser` class.
35 #[derive(Copy, Clone, PartialEq)]
36 pub enum Piece<'a> {
37     /// A literal string which should directly be emitted
38     String(&'a str),
39     /// This describes that formatting should process the next argument (as
40     /// specified inside) for emission.
41     NextArgument(Argument<'a>),
42 }
43
44 /// Representation of an argument specification.
45 #[derive(Copy, Clone, PartialEq)]
46 pub struct Argument<'a> {
47     /// Where to find this argument
48     pub position: Position<'a>,
49     /// How to format the argument
50     pub format: FormatSpec<'a>,
51 }
52
53 /// Specification for the formatting of an argument in the format string.
54 #[derive(Copy, Clone, PartialEq)]
55 pub struct FormatSpec<'a> {
56     /// Optionally specified character to fill alignment with
57     pub fill: Option<char>,
58     /// Optionally specified alignment
59     pub align: Alignment,
60     /// Packed version of various flags provided
61     pub flags: u32,
62     /// The integer precision to use
63     pub precision: Count<'a>,
64     /// The string width requested for the resulting format
65     pub width: Count<'a>,
66     /// The descriptor string representing the name of the format desired for
67     /// this argument, this can be empty or any number of characters, although
68     /// it is required to be one word.
69     pub ty: &'a str,
70 }
71
72 /// Enum describing where an argument for a format can be located.
73 #[derive(Copy, Clone, PartialEq)]
74 pub enum Position<'a> {
75     /// The argument is implied to be located at an index
76     ArgumentImplicitlyIs(usize),
77     /// The argument is located at a specific index given in the format
78     ArgumentIs(usize),
79     /// The argument has a name.
80     ArgumentNamed(&'a str),
81 }
82
83 /// Enum of alignments which are supported.
84 #[derive(Copy, Clone, PartialEq)]
85 pub enum Alignment {
86     /// The value will be aligned to the left.
87     AlignLeft,
88     /// The value will be aligned to the right.
89     AlignRight,
90     /// The value will be aligned in the center.
91     AlignCenter,
92     /// The value will take on a default alignment.
93     AlignUnknown,
94 }
95
96 /// Various flags which can be applied to format strings. The meaning of these
97 /// flags is defined by the formatters themselves.
98 #[derive(Copy, Clone, PartialEq)]
99 pub enum Flag {
100     /// A `+` will be used to denote positive numbers.
101     FlagSignPlus,
102     /// A `-` will be used to denote negative numbers. This is the default.
103     FlagSignMinus,
104     /// An alternate form will be used for the value. In the case of numbers,
105     /// this means that the number will be prefixed with the supplied string.
106     FlagAlternate,
107     /// For numbers, this means that the number will be padded with zeroes,
108     /// and the sign (`+` or `-`) will precede them.
109     FlagSignAwareZeroPad,
110     /// For Debug / `?`, format integers in lower-case hexadecimal.
111     FlagDebugLowerHex,
112     /// For Debug / `?`, format integers in upper-case hexadecimal.
113     FlagDebugUpperHex,
114 }
115
116 /// A count is used for the precision and width parameters of an integer, and
117 /// can reference either an argument or a literal integer.
118 #[derive(Copy, Clone, PartialEq)]
119 pub enum Count<'a> {
120     /// The count is specified explicitly.
121     CountIs(usize),
122     /// The count is specified by the argument with the given name.
123     CountIsName(&'a str),
124     /// The count is specified by the argument at the given index.
125     CountIsParam(usize),
126     /// The count is implied and cannot be explicitly specified.
127     CountImplied,
128 }
129
130 pub struct ParseError {
131     pub description: string::String,
132     pub note: Option<string::String>,
133     pub label: string::String,
134     pub start: usize,
135     pub end: usize,
136 }
137
138 /// The parser structure for interpreting the input format string. This is
139 /// modeled as an iterator over `Piece` structures to form a stream of tokens
140 /// being output.
141 ///
142 /// This is a recursive-descent parser for the sake of simplicity, and if
143 /// necessary there's probably lots of room for improvement performance-wise.
144 pub struct Parser<'a> {
145     input: &'a str,
146     cur: iter::Peekable<str::CharIndices<'a>>,
147     /// Error messages accumulated during parsing
148     pub errors: Vec<ParseError>,
149     /// Current position of implicit positional argument pointer
150     curarg: usize,
151     /// `Some(raw count)` when the string is "raw", used to position spans correctly
152     style: Option<usize>,
153     /// How many newlines have been seen in the string so far, to adjust the error spans
154     seen_newlines: usize,
155     /// Start and end byte offset of every successfuly parsed argument
156     pub arg_places: Vec<(usize, usize)>,
157 }
158
159 impl<'a> Iterator for Parser<'a> {
160     type Item = Piece<'a>;
161
162     fn next(&mut self) -> Option<Piece<'a>> {
163         let raw = self.style.map(|raw| raw + self.seen_newlines).unwrap_or(0);
164         if let Some(&(pos, c)) = self.cur.peek() {
165             match c {
166                 '{' => {
167                     self.cur.next();
168                     if self.consume('{') {
169                         Some(String(self.string(pos + 1)))
170                     } else {
171                         let arg = self.argument();
172                         if let Some(arg_pos) = self.must_consume('}').map(|end| {
173                             (pos + raw + 1, end + raw + 2)
174                         }) {
175                             self.arg_places.push(arg_pos);
176                         }
177                         Some(NextArgument(arg))
178                     }
179                 }
180                 '}' => {
181                     self.cur.next();
182                     if self.consume('}') {
183                         Some(String(self.string(pos + 1)))
184                     } else {
185                         let err_pos = pos + raw + 1;
186                         self.err_with_note(
187                             "unmatched `}` found",
188                             "unmatched `}`",
189                             "if you intended to print `}`, you can escape it using `}}`",
190                             err_pos,
191                             err_pos,
192                         );
193                         None
194                     }
195                 }
196                 '\n' => {
197                     self.seen_newlines += 1;
198                     Some(String(self.string(pos)))
199                 }
200                 _ => Some(String(self.string(pos))),
201             }
202         } else {
203             None
204         }
205     }
206 }
207
208 impl<'a> Parser<'a> {
209     /// Creates a new parser for the given format string
210     pub fn new(s: &'a str, style: Option<usize>) -> Parser<'a> {
211         Parser {
212             input: s,
213             cur: s.char_indices().peekable(),
214             errors: vec![],
215             curarg: 0,
216             style,
217             seen_newlines: 0,
218             arg_places: vec![],
219         }
220     }
221
222     /// Notifies of an error. The message doesn't actually need to be of type
223     /// String, but I think it does when this eventually uses conditions so it
224     /// might as well start using it now.
225     fn err<S1: Into<string::String>, S2: Into<string::String>>(
226         &mut self,
227         description: S1,
228         label: S2,
229         start: usize,
230         end: usize,
231     ) {
232         self.errors.push(ParseError {
233             description: description.into(),
234             note: None,
235             label: label.into(),
236             start,
237             end,
238         });
239     }
240
241     /// Notifies of an error. The message doesn't actually need to be of type
242     /// String, but I think it does when this eventually uses conditions so it
243     /// might as well start using it now.
244     fn err_with_note<S1: Into<string::String>, S2: Into<string::String>, S3: Into<string::String>>(
245         &mut self,
246         description: S1,
247         label: S2,
248         note: S3,
249         start: usize,
250         end: usize,
251     ) {
252         self.errors.push(ParseError {
253             description: description.into(),
254             note: Some(note.into()),
255             label: label.into(),
256             start,
257             end,
258         });
259     }
260
261     /// Optionally consumes the specified character. If the character is not at
262     /// the current position, then the current iterator isn't moved and false is
263     /// returned, otherwise the character is consumed and true is returned.
264     fn consume(&mut self, c: char) -> bool {
265         if let Some(&(_, maybe)) = self.cur.peek() {
266             if c == maybe {
267                 self.cur.next();
268                 true
269             } else {
270                 false
271             }
272         } else {
273             false
274         }
275     }
276
277     /// Forces consumption of the specified character. If the character is not
278     /// found, an error is emitted.
279     fn must_consume(&mut self, c: char) -> Option<usize> {
280         self.ws();
281         let raw = self.style.unwrap_or(0);
282
283         let padding = raw + self.seen_newlines;
284         if let Some(&(pos, maybe)) = self.cur.peek() {
285             if c == maybe {
286                 self.cur.next();
287                 Some(pos)
288             } else {
289                 let pos = pos + padding + 1;
290                 self.err(format!("expected `{:?}`, found `{:?}`", c, maybe),
291                          format!("expected `{}`", c),
292                          pos,
293                          pos);
294                 None
295             }
296         } else {
297             let msg = format!("expected `{:?}` but string was terminated", c);
298             // point at closing `"`, unless the last char is `\n` to account for `println`
299             let pos = match self.input.chars().last() {
300                 Some('\n') => self.input.len(),
301                 _ => self.input.len() + 1,
302             };
303             if c == '}' {
304                 self.err_with_note(msg,
305                                    format!("expected `{:?}`", c),
306                                    "if you intended to print `{`, you can escape it using `{{`",
307                                    pos + padding,
308                                    pos + padding);
309             } else {
310                 self.err(msg, format!("expected `{:?}`", c), pos, pos);
311             }
312             None
313         }
314     }
315
316     /// Consumes all whitespace characters until the first non-whitespace
317     /// character
318     fn ws(&mut self) {
319         while let Some(&(_, c)) = self.cur.peek() {
320             if c.is_whitespace() {
321                 self.cur.next();
322             } else {
323                 break;
324             }
325         }
326     }
327
328     /// Parses all of a string which is to be considered a "raw literal" in a
329     /// format string. This is everything outside of the braces.
330     fn string(&mut self, start: usize) -> &'a str {
331         // we may not consume the character, peek the iterator
332         while let Some(&(pos, c)) = self.cur.peek() {
333             match c {
334                 '{' | '}' => {
335                     return &self.input[start..pos];
336                 }
337                 _ => {
338                     self.cur.next();
339                 }
340             }
341         }
342         &self.input[start..self.input.len()]
343     }
344
345     /// Parses an Argument structure, or what's contained within braces inside
346     /// the format string
347     fn argument(&mut self) -> Argument<'a> {
348         let pos = self.position();
349         let format = self.format();
350
351         // Resolve position after parsing format spec.
352         let pos = match pos {
353             Some(position) => position,
354             None => {
355                 let i = self.curarg;
356                 self.curarg += 1;
357                 ArgumentImplicitlyIs(i)
358             }
359         };
360
361         Argument {
362             position: pos,
363             format,
364         }
365     }
366
367     /// Parses a positional argument for a format. This could either be an
368     /// integer index of an argument, a named argument, or a blank string.
369     /// Returns `Some(parsed_position)` if the position is not implicitly
370     /// consuming a macro argument, `None` if it's the case.
371     fn position(&mut self) -> Option<Position<'a>> {
372         if let Some(i) = self.integer() {
373             Some(ArgumentIs(i))
374         } else {
375             match self.cur.peek() {
376                 Some(&(_, c)) if c.is_alphabetic() => Some(ArgumentNamed(self.word())),
377                 Some(&(pos, c)) if c == '_' => {
378                     let invalid_name = self.string(pos);
379                     self.err_with_note(format!("invalid argument name `{}`", invalid_name),
380                                        "invalid argument name",
381                                        "argument names cannot start with an underscore",
382                                        pos + 1, // add 1 to account for leading `{`
383                                        pos + 1 + invalid_name.len());
384                     Some(ArgumentNamed(invalid_name))
385                 },
386
387                 // This is an `ArgumentNext`.
388                 // Record the fact and do the resolution after parsing the
389                 // format spec, to make things like `{:.*}` work.
390                 _ => None,
391             }
392         }
393     }
394
395     /// Parses a format specifier at the current position, returning all of the
396     /// relevant information in the FormatSpec struct.
397     fn format(&mut self) -> FormatSpec<'a> {
398         let mut spec = FormatSpec {
399             fill: None,
400             align: AlignUnknown,
401             flags: 0,
402             precision: CountImplied,
403             width: CountImplied,
404             ty: &self.input[..0],
405         };
406         if !self.consume(':') {
407             return spec;
408         }
409
410         // fill character
411         if let Some(&(_, c)) = self.cur.peek() {
412             match self.cur.clone().skip(1).next() {
413                 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
414                     spec.fill = Some(c);
415                     self.cur.next();
416                 }
417                 _ => {}
418             }
419         }
420         // Alignment
421         if self.consume('<') {
422             spec.align = AlignLeft;
423         } else if self.consume('>') {
424             spec.align = AlignRight;
425         } else if self.consume('^') {
426             spec.align = AlignCenter;
427         }
428         // Sign flags
429         if self.consume('+') {
430             spec.flags |= 1 << (FlagSignPlus as u32);
431         } else if self.consume('-') {
432             spec.flags |= 1 << (FlagSignMinus as u32);
433         }
434         // Alternate marker
435         if self.consume('#') {
436             spec.flags |= 1 << (FlagAlternate as u32);
437         }
438         // Width and precision
439         let mut havewidth = false;
440         if self.consume('0') {
441             // small ambiguity with '0$' as a format string. In theory this is a
442             // '0' flag and then an ill-formatted format string with just a '$'
443             // and no count, but this is better if we instead interpret this as
444             // no '0' flag and '0$' as the width instead.
445             if self.consume('$') {
446                 spec.width = CountIsParam(0);
447                 havewidth = true;
448             } else {
449                 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
450             }
451         }
452         if !havewidth {
453             spec.width = self.count();
454         }
455         if self.consume('.') {
456             if self.consume('*') {
457                 // Resolve `CountIsNextParam`.
458                 // We can do this immediately as `position` is resolved later.
459                 let i = self.curarg;
460                 self.curarg += 1;
461                 spec.precision = CountIsParam(i);
462             } else {
463                 spec.precision = self.count();
464             }
465         }
466         // Optional radix followed by the actual format specifier
467         if self.consume('x') {
468             if self.consume('?') {
469                 spec.flags |= 1 << (FlagDebugLowerHex as u32);
470                 spec.ty = "?";
471             } else {
472                 spec.ty = "x";
473             }
474         } else if self.consume('X') {
475             if self.consume('?') {
476                 spec.flags |= 1 << (FlagDebugUpperHex as u32);
477                 spec.ty = "?";
478             } else {
479                 spec.ty = "X";
480             }
481         } else if self.consume('?') {
482             spec.ty = "?";
483         } else {
484             spec.ty = self.word();
485         }
486         spec
487     }
488
489     /// Parses a Count parameter at the current position. This does not check
490     /// for 'CountIsNextParam' because that is only used in precision, not
491     /// width.
492     fn count(&mut self) -> Count<'a> {
493         if let Some(i) = self.integer() {
494             if self.consume('$') {
495                 CountIsParam(i)
496             } else {
497                 CountIs(i)
498             }
499         } else {
500             let tmp = self.cur.clone();
501             let word = self.word();
502             if word.is_empty() {
503                 self.cur = tmp;
504                 CountImplied
505             } else {
506                 if self.consume('$') {
507                     CountIsName(word)
508                 } else {
509                     self.cur = tmp;
510                     CountImplied
511                 }
512             }
513         }
514     }
515
516     /// Parses a word starting at the current position. A word is considered to
517     /// be an alphabetic character followed by any number of alphanumeric
518     /// characters.
519     fn word(&mut self) -> &'a str {
520         let start = match self.cur.peek() {
521             Some(&(pos, c)) if c.is_xid_start() => {
522                 self.cur.next();
523                 pos
524             }
525             _ => {
526                 return &self.input[..0];
527             }
528         };
529         while let Some(&(pos, c)) = self.cur.peek() {
530             if c.is_xid_continue() {
531                 self.cur.next();
532             } else {
533                 return &self.input[start..pos];
534             }
535         }
536         &self.input[start..self.input.len()]
537     }
538
539     /// Optionally parses an integer at the current position. This doesn't deal
540     /// with overflow at all, it's just accumulating digits.
541     fn integer(&mut self) -> Option<usize> {
542         let mut cur = 0;
543         let mut found = false;
544         while let Some(&(_, c)) = self.cur.peek() {
545             if let Some(i) = c.to_digit(10) {
546                 cur = cur * 10 + i as usize;
547                 found = true;
548                 self.cur.next();
549             } else {
550                 break;
551             }
552         }
553         if found {
554             Some(cur)
555         } else {
556             None
557         }
558     }
559 }
560
561 #[cfg(test)]
562 mod tests {
563     use super::*;
564
565     fn same(fmt: &'static str, p: &[Piece<'static>]) {
566         let parser = Parser::new(fmt, None);
567         assert!(parser.collect::<Vec<Piece<'static>>>() == p);
568     }
569
570     fn fmtdflt() -> FormatSpec<'static> {
571         return FormatSpec {
572             fill: None,
573             align: AlignUnknown,
574             flags: 0,
575             precision: CountImplied,
576             width: CountImplied,
577             ty: "",
578         };
579     }
580
581     fn musterr(s: &str) {
582         let mut p = Parser::new(s, None);
583         p.next();
584         assert!(!p.errors.is_empty());
585     }
586
587     #[test]
588     fn simple() {
589         same("asdf", &[String("asdf")]);
590         same("a{{b", &[String("a"), String("{b")]);
591         same("a}}b", &[String("a"), String("}b")]);
592         same("a}}", &[String("a"), String("}")]);
593         same("}}", &[String("}")]);
594         same("\\}}", &[String("\\"), String("}")]);
595     }
596
597     #[test]
598     fn invalid01() {
599         musterr("{")
600     }
601     #[test]
602     fn invalid02() {
603         musterr("}")
604     }
605     #[test]
606     fn invalid04() {
607         musterr("{3a}")
608     }
609     #[test]
610     fn invalid05() {
611         musterr("{:|}")
612     }
613     #[test]
614     fn invalid06() {
615         musterr("{:>>>}")
616     }
617
618     #[test]
619     fn format_nothing() {
620         same("{}",
621              &[NextArgument(Argument {
622                    position: ArgumentImplicitlyIs(0),
623                    format: fmtdflt(),
624                })]);
625     }
626     #[test]
627     fn format_position() {
628         same("{3}",
629              &[NextArgument(Argument {
630                    position: ArgumentIs(3),
631                    format: fmtdflt(),
632                })]);
633     }
634     #[test]
635     fn format_position_nothing_else() {
636         same("{3:}",
637              &[NextArgument(Argument {
638                    position: ArgumentIs(3),
639                    format: fmtdflt(),
640                })]);
641     }
642     #[test]
643     fn format_type() {
644         same("{3:a}",
645              &[NextArgument(Argument {
646                    position: ArgumentIs(3),
647                    format: FormatSpec {
648                        fill: None,
649                        align: AlignUnknown,
650                        flags: 0,
651                        precision: CountImplied,
652                        width: CountImplied,
653                        ty: "a",
654                    },
655                })]);
656     }
657     #[test]
658     fn format_align_fill() {
659         same("{3:>}",
660              &[NextArgument(Argument {
661                    position: ArgumentIs(3),
662                    format: FormatSpec {
663                        fill: None,
664                        align: AlignRight,
665                        flags: 0,
666                        precision: CountImplied,
667                        width: CountImplied,
668                        ty: "",
669                    },
670                })]);
671         same("{3:0<}",
672              &[NextArgument(Argument {
673                    position: ArgumentIs(3),
674                    format: FormatSpec {
675                        fill: Some('0'),
676                        align: AlignLeft,
677                        flags: 0,
678                        precision: CountImplied,
679                        width: CountImplied,
680                        ty: "",
681                    },
682                })]);
683         same("{3:*<abcd}",
684              &[NextArgument(Argument {
685                    position: ArgumentIs(3),
686                    format: FormatSpec {
687                        fill: Some('*'),
688                        align: AlignLeft,
689                        flags: 0,
690                        precision: CountImplied,
691                        width: CountImplied,
692                        ty: "abcd",
693                    },
694                })]);
695     }
696     #[test]
697     fn format_counts() {
698         same("{:10s}",
699              &[NextArgument(Argument {
700                    position: ArgumentImplicitlyIs(0),
701                    format: FormatSpec {
702                        fill: None,
703                        align: AlignUnknown,
704                        flags: 0,
705                        precision: CountImplied,
706                        width: CountIs(10),
707                        ty: "s",
708                    },
709                })]);
710         same("{:10$.10s}",
711              &[NextArgument(Argument {
712                    position: ArgumentImplicitlyIs(0),
713                    format: FormatSpec {
714                        fill: None,
715                        align: AlignUnknown,
716                        flags: 0,
717                        precision: CountIs(10),
718                        width: CountIsParam(10),
719                        ty: "s",
720                    },
721                })]);
722         same("{:.*s}",
723              &[NextArgument(Argument {
724                    position: ArgumentImplicitlyIs(1),
725                    format: FormatSpec {
726                        fill: None,
727                        align: AlignUnknown,
728                        flags: 0,
729                        precision: CountIsParam(0),
730                        width: CountImplied,
731                        ty: "s",
732                    },
733                })]);
734         same("{:.10$s}",
735              &[NextArgument(Argument {
736                    position: ArgumentImplicitlyIs(0),
737                    format: FormatSpec {
738                        fill: None,
739                        align: AlignUnknown,
740                        flags: 0,
741                        precision: CountIsParam(10),
742                        width: CountImplied,
743                        ty: "s",
744                    },
745                })]);
746         same("{:a$.b$s}",
747              &[NextArgument(Argument {
748                    position: ArgumentImplicitlyIs(0),
749                    format: FormatSpec {
750                        fill: None,
751                        align: AlignUnknown,
752                        flags: 0,
753                        precision: CountIsName("b"),
754                        width: CountIsName("a"),
755                        ty: "s",
756                    },
757                })]);
758     }
759     #[test]
760     fn format_flags() {
761         same("{:-}",
762              &[NextArgument(Argument {
763                    position: ArgumentImplicitlyIs(0),
764                    format: FormatSpec {
765                        fill: None,
766                        align: AlignUnknown,
767                        flags: (1 << FlagSignMinus as u32),
768                        precision: CountImplied,
769                        width: CountImplied,
770                        ty: "",
771                    },
772                })]);
773         same("{:+#}",
774              &[NextArgument(Argument {
775                    position: ArgumentImplicitlyIs(0),
776                    format: FormatSpec {
777                        fill: None,
778                        align: AlignUnknown,
779                        flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32),
780                        precision: CountImplied,
781                        width: CountImplied,
782                        ty: "",
783                    },
784                })]);
785     }
786     #[test]
787     fn format_mixture() {
788         same("abcd {3:a} efg",
789              &[String("abcd "),
790                NextArgument(Argument {
791                    position: ArgumentIs(3),
792                    format: FormatSpec {
793                        fill: None,
794                        align: AlignUnknown,
795                        flags: 0,
796                        precision: CountImplied,
797                        width: CountImplied,
798                        ty: "a",
799                    },
800                }),
801                String(" efg")]);
802     }
803 }