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