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