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