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