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