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