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