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