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