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