Debian Codegraph @

third_party/rust/derive_more-impl/src/fmt/parsing.rs

raw
1 //! Parsing of [Rust `fmt` syntax][0].
2 //!
3 //! [0]: std::fmt#syntax
4
5 use std::{convert::identity, iter};
6
7 use unicode_xid::UnicodeXID as XID;
8
9 /// Output of the [`format_string`] parser.
10 #[derive(Debug, Clone, Eq, PartialEq)]
11 pub(crate) struct FormatString<'a> {
12 pub(crate) formats: Vec<Format<'a>>,
13 }
14
15 /// Output of the [`format`] parser.
16 ///
17 /// [`format`]: fn@format
18 #[derive(Debug, Clone, Copy, Eq, PartialEq)]
19 pub(crate) struct Format<'a> {
20 pub(crate) arg: Option<Argument<'a>>,
21 pub(crate) spec: Option<FormatSpec<'a>>,
22 }
23
24 /// Output of the [`format_spec`] parser.
25 #[derive(Debug, Clone, Copy, Eq, PartialEq)]
26 pub(crate) struct FormatSpec<'a> {
27 pub(crate) width: Option<Width<'a>>,
28 pub(crate) precision: Option<Precision<'a>>,
29 pub(crate) ty: Type,
30 }
31
32 /// Output of the [`argument`] parser.
33 #[derive(Debug, Clone, Copy, Eq, PartialEq)]
34 pub(crate) enum Argument<'a> {
35 Integer(usize),
36 Identifier(&'a str),
37 }
38
39 /// Output of the [`precision`] parser.
40 #[derive(Debug, Clone, Copy, Eq, PartialEq)]
41 pub(crate) enum Precision<'a> {
42 Count(Count<'a>),
43 Star,
44 }
45
46 /// Output of the [`count`] parser.
47 #[derive(Debug, Clone, Copy, Eq, PartialEq)]
48 pub(crate) enum Count<'a> {
49 Integer(usize),
50 Parameter(Parameter<'a>),
51 }
52
53 /// Output of the [`type_`] parser. See [formatting traits][1] for more info.
54 ///
55 /// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#formatting-traits
56 #[derive(Debug, Clone, Copy, Eq, PartialEq)]
57 pub(crate) enum Type {
58 Display,
59 Debug,
60 LowerDebug,
61 UpperDebug,
62 Octal,
63 LowerHex,
64 UpperHex,
65 Pointer,
66 Binary,
67 LowerExp,
68 UpperExp,
69 }
70
71 impl Type {
72 /// Returns trait name of this [`Type`].
73 pub(crate) fn trait_name(&self) -> &'static str {
74 match self {
75 Type::Display => "Display",
76 Type::Debug | Type::LowerDebug | Type::UpperDebug => "Debug",
77 Type::Octal => "Octal",
78 Type::LowerHex => "LowerHex",
79 Type::UpperHex => "UpperHex",
80 Type::Pointer => "Pointer",
81 Type::Binary => "Binary",
82 Type::LowerExp => "LowerExp",
83 Type::UpperExp => "UpperExp",
84 }
85 }
86 }
87
88 /// Type alias for the [`FormatSpec::width`].
89 type Width<'a> = Count<'a>;
90
91 /// Output of the [`maybe_format`] parser.
92 type MaybeFormat<'a> = Option<Format<'a>>;
93
94 /// Output of the [`identifier`] parser.
95 type Identifier<'a> = &'a str;
96
97 /// Output of the [`parameter`] parser.
98 type Parameter<'a> = Argument<'a>;
99
100 /// [`str`] left to parse.
101 ///
102 /// [`str`]: prim@str
103 type LeftToParse<'a> = &'a str;
104
105 /// Parses a `format_string` as defined in the [grammar spec][1].
106 ///
107 /// # Grammar
108 ///
109 /// [`format_string`]` := `[`text`]` [`[`maybe_format text`]`] *`
110 ///
111 /// # Example
112 ///
113 /// ```text
114 /// Hello
115 /// Hello, {}!
116 /// {:?}
117 /// Hello {people}!
118 /// {} {}
119 /// {:04}
120 /// {par:-^#.0$?}
121 /// ```
122 ///
123 /// # Return value
124 ///
125 /// - [`Some`] in case of successful parse.
126 /// - [`None`] otherwise (not all characters are consumed by underlying
127 /// parsers).
128 ///
129 /// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#syntax
130 pub(crate) fn format_string(input: &str) -> Option<FormatString<'_>> {
131 let (mut input, _) = optional_result(text)(input);
132
133 let formats = iter::repeat(())
134 .scan(&mut input, |input, _| {
135 let (curr, format) =
136 alt(&mut [&mut maybe_format, &mut map(text, |(i, _)| (i, None))])(
137 input,
138 )?;
139 **input = curr;
140 Some(format)
141 })
142 .flatten()
143 .collect();
144
145 // Should consume all tokens for a successful parse.
146 input.is_empty().then_some(FormatString { formats })
147 }
148
149 /// Parses a `maybe_format` as defined in the [grammar spec][1].
150 ///
151 /// # Grammar
152 ///
153 /// [`maybe_format`]` := '{' '{' | '}' '}' | `[`format`]
154 ///
155 /// # Example
156 ///
157 /// ```text
158 /// {{
159 /// }}
160 /// {:04}
161 /// {:#?}
162 /// {par:-^#.0$?}
163 /// ```
164 ///
165 /// [`format`]: fn@format
166 /// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#syntax
167 fn maybe_format(input: &str) -> Option<(LeftToParse<'_>, MaybeFormat<'_>)> {
168 alt(&mut [
169 &mut map(str("{{"), |i| (i, None)),
170 &mut map(str("}}"), |i| (i, None)),
171 &mut map(format, |(i, format)| (i, Some(format))),
172 ])(input)
173 }
174
175 /// Parses a `format` as defined in the [grammar spec][1].
176 ///
177 /// # Grammar
178 ///
179 /// [`format`]` := '{' [`[`argument`]`] [':' `[`format_spec`]`] '}'`
180 ///
181 /// # Example
182 ///
183 /// ```text
184 /// {par}
185 /// {:#?}
186 /// {par:-^#.0$?}
187 /// ```
188 ///
189 /// [`format`]: fn@format
190 /// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#syntax
191 fn format(input: &str) -> Option<(LeftToParse<'_>, Format<'_>)> {
192 let input = char('{')(input)?;
193
194 let (input, arg) = optional_result(argument)(input);
195
196 let (input, spec) = map_or_else(
197 char(':'),
198 |i| Some((i, None)),
199 map(format_spec, |(i, s)| (i, Some(s))),
200 )(input)?;
201
202 let input = char('}')(input)?;
203
204 Some((input, Format { arg, spec }))
205 }
206
207 /// Parses an `argument` as defined in the [grammar spec][1].
208 ///
209 /// # Grammar
210 ///
211 /// [`argument`]` := `[`integer`]` | `[`identifier`]
212 ///
213 /// # Example
214 ///
215 /// ```text
216 /// 0
217 /// ident
218 /// Минск
219 /// ```
220 ///
221 /// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#syntax
222 fn argument(input: &str) -> Option<(LeftToParse<'_>, Argument)> {
223 alt(&mut [
224 &mut map(identifier, |(i, ident)| (i, Argument::Identifier(ident))),
225 &mut map(integer, |(i, int)| (i, Argument::Integer(int))),
226 ])(input)
227 }
228
229 /// Parses a `format_spec` as defined in the [grammar spec][1].
230 ///
231 /// # Grammar
232 ///
233 /// [`format_spec`]` := [[fill]align][sign]['#']['0'][width]`
234 /// `['.' `[`precision`]`]`[`type`]
235 ///
236 /// # Example
237 ///
238 /// ```text
239 /// ^
240 /// <^
241 /// ->+#0width$.precision$x?
242 /// ```
243 ///
244 /// [`type`]: type_
245 /// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#syntax
246 fn format_spec(input: &str) -> Option<(LeftToParse<'_>, FormatSpec<'_>)> {
247 let input = unwrap_or_else(
248 alt(&mut [
249 &mut try_seq(&mut [&mut any_char, &mut one_of("<^>")]),
250 &mut one_of("<^>"),
251 ]),
252 identity,
253 )(input);
254
255 let input = seq(&mut [
256 &mut optional(one_of("+-")),
257 &mut optional(char('#')),
258 &mut optional(try_seq(&mut [
259 &mut char('0'),
260 &mut lookahead(check_char(|c| !matches!(c, '$'))),
261 ])),
262 ])(input);
263
264 let (input, width) = optional_result(count)(input);
265
266 let (input, precision) = map_or_else(
267 char('.'),
268 |i| Some((i, None)),
269 map(precision, |(i, p)| (i, Some(p))),
270 )(input)?;
271
272 let (input, ty) = type_(input)?;
273
274 Some((
275 input,
276 FormatSpec {
277 width,
278 precision,
279 ty,
280 },
281 ))
282 }
283
284 /// Parses a `precision` as defined in the [grammar spec][1].
285 ///
286 /// # Grammar
287 ///
288 /// [`precision`]` := `[`count`]` | '*'`
289 ///
290 /// # Example
291 ///
292 /// ```text
293 /// 0
294 /// 42$
295 /// par$
296 /// *
297 /// ```
298 ///
299 /// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#syntax
300 fn precision(input: &str) -> Option<(LeftToParse<'_>, Precision<'_>)> {
301 alt(&mut [
302 &mut map(count, |(i, c)| (i, Precision::Count(c))),
303 &mut map(char('*'), |i| (i, Precision::Star)),
304 ])(input)
305 }
306
307 /// Parses a `type` as defined in the [grammar spec][1].
308 ///
309 /// # Grammar
310 ///
311 /// [`type`]` := '' | '?' | 'x?' | 'X?' | identifier`
312 ///
313 /// # Example
314 ///
315 /// All possible [`Type`]s.
316 ///
317 /// ```text
318 /// ?
319 /// x?
320 /// X?
321 /// o
322 /// x
323 /// X
324 /// p
325 /// b
326 /// e
327 /// E
328 /// ```
329 ///
330 /// [`type`]: type_
331 /// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#syntax
332 fn type_(input: &str) -> Option<(&str, Type)> {
333 alt(&mut [
334 &mut map(str("x?"), |i| (i, Type::LowerDebug)),
335 &mut map(str("X?"), |i| (i, Type::UpperDebug)),
336 &mut map(char('?'), |i| (i, Type::Debug)),
337 &mut map(char('o'), |i| (i, Type::Octal)),
338 &mut map(char('x'), |i| (i, Type::LowerHex)),
339 &mut map(char('X'), |i| (i, Type::UpperHex)),
340 &mut map(char('p'), |i| (i, Type::Pointer)),
341 &mut map(char('b'), |i| (i, Type::Binary)),
342 &mut map(char('e'), |i| (i, Type::LowerExp)),
343 &mut map(char('E'), |i| (i, Type::UpperExp)),
344 &mut map(lookahead(char('}')), |i| (i, Type::Display)),
345 ])(input)
346 }
347
348 /// Parses a `count` as defined in the [grammar spec][1].
349 ///
350 /// # Grammar
351 ///
352 /// [`count`]` := `[`parameter`]` | `[`integer`]
353 ///
354 /// # Example
355 ///
356 /// ```text
357 /// 0
358 /// 42$
359 /// par$
360 /// ```
361 ///
362 /// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#syntax
363 fn count(input: &str) -> Option<(LeftToParse<'_>, Count<'_>)> {
364 alt(&mut [
365 &mut map(parameter, |(i, p)| (i, Count::Parameter(p))),
366 &mut map(integer, |(i, int)| (i, Count::Integer(int))),
367 ])(input)
368 }
369
370 /// Parses a `parameter` as defined in the [grammar spec][1].
371 ///
372 /// # Grammar
373 ///
374 /// [`parameter`]` := `[`argument`]` '$'`
375 ///
376 /// # Example
377 ///
378 /// ```text
379 /// 42$
380 /// par$
381 /// ```
382 ///
383 /// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#syntax
384 fn parameter(input: &str) -> Option<(LeftToParse<'_>, Parameter<'_>)> {
385 and_then(argument, |(i, arg)| map(char('$'), |i| (i, arg))(i))(input)
386 }
387
388 /// Parses an `identifier` as defined in the [grammar spec][1].
389 ///
390 /// # Grammar
391 ///
392 /// `IDENTIFIER_OR_KEYWORD : XID_Start XID_Continue* | _ XID_Continue+`
393 ///
394 /// See [rust reference][2] for more info.
395 ///
396 /// # Example
397 ///
398 /// ```text
399 /// identifier
400 /// Минск
401 /// ```
402 ///
403 /// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#syntax
404 /// [2]: https://doc.rust-lang.org/reference/identifiers.html
405 fn identifier(input: &str) -> Option<(LeftToParse<'_>, Identifier<'_>)> {
406 map(
407 alt(&mut [
408 &mut map(
409 check_char(XID::is_xid_start),
410 take_while0(check_char(XID::is_xid_continue)),
411 ),
412 &mut and_then(char('_'), take_while1(check_char(XID::is_xid_continue))),
413 ]),
414 |(i, _)| (i, &input[..(input.as_bytes().len() - i.as_bytes().len())]),
415 )(input)
416 }
417
418 /// Parses an `integer` as defined in the [grammar spec][1].
419 ///
420 /// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#syntax
421 fn integer(input: &str) -> Option<(LeftToParse<'_>, usize)> {
422 and_then(
423 take_while1(check_char(|c| c.is_ascii_digit())),
424 |(i, int)| int.parse().ok().map(|int| (i, int)),
425 )(input)
426 }
427
428 /// Parses a `text` as defined in the [grammar spec][1].
429 ///
430 /// [1]: https://doc.rust-lang.org/stable/std/fmt/index.html#syntax
431 fn text(input: &str) -> Option<(LeftToParse<'_>, &str)> {
432 take_until1(any_char, one_of("{}"))(input)
433 }
434
435 type Parser<'p> = &'p mut dyn FnMut(&str) -> &str;
436
437 /// Applies non-failing parsers in sequence.
438 fn seq<'p>(parsers: &'p mut [Parser<'p>]) -> impl FnMut(&str) -> LeftToParse<'_> + 'p {
439 move |input| parsers.iter_mut().fold(input, |i, p| (**p)(i))
440 }
441
442 type FallibleParser<'p> = &'p mut dyn FnMut(&str) -> Option<&str>;
443
444 /// Tries to apply parsers in sequence. Returns [`None`] in case one of them
445 /// returned [`None`].
446 fn try_seq<'p>(
447 parsers: &'p mut [FallibleParser<'p>],
448 ) -> impl FnMut(&str) -> Option<LeftToParse<'_>> + 'p {
449 move |input| parsers.iter_mut().try_fold(input, |i, p| (**p)(i))
450 }
451
452 /// Returns first successful parser or [`None`] in case all of them returned
453 /// [`None`].
454 fn alt<'p, 'i, T: 'i>(
455 parsers: &'p mut [&'p mut dyn FnMut(&'i str) -> Option<T>],
456 ) -> impl FnMut(&'i str) -> Option<T> + 'p {
457 move |input| parsers.iter_mut().find_map(|p| (**p)(input))
458 }
459
460 /// Maps output of the parser in case it returned [`Some`].
461 fn map<'i, I: 'i, O: 'i>(
462 mut parser: impl FnMut(&'i str) -> Option<I>,
463 mut f: impl FnMut(I) -> O,
464 ) -> impl FnMut(&'i str) -> Option<O> {
465 move |input| parser(input).map(&mut f)
466 }
467
468 /// Maps output of the parser in case it returned [`Some`] or uses `default`.
469 fn map_or_else<'i, I: 'i, O: 'i>(
470 mut parser: impl FnMut(&'i str) -> Option<I>,
471 mut default: impl FnMut(&'i str) -> O,
472 mut f: impl FnMut(I) -> O,
473 ) -> impl FnMut(&'i str) -> O {
474 move |input| parser(input).map_or_else(|| default(input), &mut f)
475 }
476
477 /// Returns the contained [`Some`] value or computes it from a closure.
478 fn unwrap_or_else<'i, O: 'i>(
479 mut parser: impl FnMut(&'i str) -> Option<O>,
480 mut f: impl FnMut(&'i str) -> O,
481 ) -> impl FnMut(&'i str) -> O {
482 move |input| parser(input).unwrap_or_else(|| f(input))
483 }
484
485 /// Returns [`None`] if the parser returned is [`None`], otherwise calls `f`
486 /// with the wrapped value and returns the result.
487 fn and_then<'i, I: 'i, O: 'i>(
488 mut parser: impl FnMut(&'i str) -> Option<I>,
489 mut f: impl FnMut(I) -> Option<O>,
490 ) -> impl FnMut(&'i str) -> Option<O> {
491 move |input| parser(input).and_then(&mut f)
492 }
493
494 /// Checks whether `parser` is successful while not advancing the original
495 /// `input`.
496 fn lookahead(
497 mut parser: impl FnMut(&str) -> Option<&str>,
498 ) -> impl FnMut(&str) -> Option<LeftToParse<'_>> {
499 move |input| map(&mut parser, |_| input)(input)
500 }
501
502 /// Makes underlying `parser` optional by returning the original `input` in case
503 /// it returned [`None`].
504 fn optional(
505 mut parser: impl FnMut(&str) -> Option<&str>,
506 ) -> impl FnMut(&str) -> LeftToParse<'_> {
507 move |input: &str| parser(input).unwrap_or(input)
508 }
509
510 /// Makes underlying `parser` optional by returning the original `input` and
511 /// [`None`] in case it returned [`None`].
512 fn optional_result<'i, T: 'i>(
513 mut parser: impl FnMut(&'i str) -> Option<(&'i str, T)>,
514 ) -> impl FnMut(&'i str) -> (LeftToParse<'i>, Option<T>) {
515 move |input: &str| {
516 map_or_else(&mut parser, |i| (i, None), |(i, c)| (i, Some(c)))(input)
517 }
518 }
519
520 /// Parses while `parser` is successful. Never fails.
521 fn take_while0(
522 mut parser: impl FnMut(&str) -> Option<&str>,
523 ) -> impl FnMut(&str) -> (LeftToParse<'_>, &str) {
524 move |input| {
525 let mut cur = input;
526 while let Some(step) = parser(cur) {
527 cur = step;
528 }
529 (
530 cur,
531 &input[..(input.as_bytes().len() - cur.as_bytes().len())],
532 )
533 }
534 }
535
536 /// Parses while `parser` is successful. Returns [`None`] in case `parser` never
537 /// succeeded.
538 fn take_while1(
539 mut parser: impl FnMut(&str) -> Option<&str>,
540 ) -> impl FnMut(&str) -> Option<(LeftToParse<'_>, &str)> {
541 move |input| {
542 let mut cur = parser(input)?;
543 while let Some(step) = parser(cur) {
544 cur = step;
545 }
546 Some((
547 cur,
548 &input[..(input.as_bytes().len() - cur.as_bytes().len())],
549 ))
550 }
551 }
552
553 /// Parses with `basic` while `until` returns [`None`]. Returns [`None`] in case
554 /// `until` succeeded initially or `basic` never succeeded. Doesn't consume
555 /// [`char`]s parsed by `until`.
556 ///
557 /// [`char`]: fn@char
558 fn take_until1(
559 mut basic: impl FnMut(&str) -> Option<&str>,
560 mut until: impl FnMut(&str) -> Option<&str>,
561 ) -> impl FnMut(&str) -> Option<(LeftToParse<'_>, &str)> {
562 move |input: &str| {
563 if until(input).is_some() {
564 return None;
565 }
566 let mut cur = basic(input)?;
567 loop {
568 if until(cur).is_some() {
569 break;
570 }
571 let Some(b) = basic(cur) else {
572 break;
573 };
574 cur = b;
575 }
576
577 Some((
578 cur,
579 &input[..(input.as_bytes().len() - cur.as_bytes().len())],
580 ))
581 }
582 }
583
584 /// Checks whether `input` starts with `s`.
585 fn str(s: &str) -> impl FnMut(&str) -> Option<LeftToParse<'_>> + '_ {
586 move |input| input.starts_with(s).then(|| &input[s.as_bytes().len()..])
587 }
588
589 /// Checks whether `input` starts with `c`.
590 fn char(c: char) -> impl FnMut(&str) -> Option<LeftToParse<'_>> {
591 move |input| input.starts_with(c).then(|| &input[c.len_utf8()..])
592 }
593
594 /// Checks whether first [`char`] suits `check`.
595 ///
596 /// [`char`]: fn@char
597 fn check_char(
598 mut check: impl FnMut(char) -> bool,
599 ) -> impl FnMut(&str) -> Option<LeftToParse<'_>> {
600 move |input| {
601 input
602 .chars()
603 .next()
604 .and_then(|c| check(c).then(|| &input[c.len_utf8()..]))
605 }
606 }
607
608 /// Checks whether first [`char`] of input is present in `chars`.
609 ///
610 /// [`char`]: fn@char
611 fn one_of(chars: &str) -> impl FnMut(&str) -> Option<LeftToParse<'_>> + '_ {
612 move |input: &str| chars.chars().find_map(|c| char(c)(input))
613 }
614
615 /// Parses any [`char`].
616 ///
617 /// [`char`]: fn@char
618 fn any_char(input: &str) -> Option<LeftToParse<'_>> {
619 input.chars().next().map(|c| &input[c.len_utf8()..])
620 }
621
622 #[cfg(test)]
623 mod tests {
624 use super::*;
625
626 #[test]
627 fn text() {
628 assert_eq!(format_string(""), Some(FormatString { formats: vec![] }));
629 assert_eq!(
630 format_string("test"),
631 Some(FormatString { formats: vec![] }),
632 );
633 assert_eq!(
634 format_string("Минск"),
635 Some(FormatString { formats: vec![] }),
636 );
637 assert_eq!(format_string("🦀"), Some(FormatString { formats: vec![] }));
638 }
639
640 #[test]
641 fn argument() {
642 assert_eq!(
643 format_string("{}"),
644 Some(FormatString {
645 formats: vec![Format {
646 arg: None,
647 spec: None,
648 }],
649 }),
650 );
651 assert_eq!(
652 format_string("{0}"),
653 Some(FormatString {
654 formats: vec![Format {
655 arg: Some(Argument::Integer(0)),
656 spec: None,
657 }],
658 }),
659 );
660 assert_eq!(
661 format_string("{par}"),
662 Some(FormatString {
663 formats: vec![Format {
664 arg: Some(Argument::Identifier("par")),
665 spec: None,
666 }],
667 }),
668 );
669 assert_eq!(
670 format_string("{Минск}"),
671 Some(FormatString {
672 formats: vec![Format {
673 arg: Some(Argument::Identifier("Минск")),
674 spec: None,
675 }],
676 }),
677 );
678 }
679
680 #[test]
681 fn spec() {
682 assert_eq!(
683 format_string("{:}"),
684 Some(FormatString {
685 formats: vec![Format {
686 arg: None,
687 spec: Some(FormatSpec {
688 width: None,
689 precision: None,
690 ty: Type::Display,
691 }),
692 }],
693 }),
694 );
695 assert_eq!(
696 format_string("{:^}"),
697 Some(FormatString {
698 formats: vec![Format {
699 arg: None,
700 spec: Some(FormatSpec {
701 width: None,
702 precision: None,
703 ty: Type::Display,
704 }),
705 }],
706 }),
707 );
708 assert_eq!(
709 format_string("{:-<}"),
710 Some(FormatString {
711 formats: vec![Format {
712 arg: None,
713 spec: Some(FormatSpec {
714 width: None,
715 precision: None,
716 ty: Type::Display,
717 }),
718 }],
719 }),
720 );
721 assert_eq!(
722 format_string("{: <}"),
723 Some(FormatString {
724 formats: vec![Format {
725 arg: None,
726 spec: Some(FormatSpec {
727 width: None,
728 precision: None,
729 ty: Type::Display,
730 }),
731 }],
732 }),
733 );
734 assert_eq!(
735 format_string("{:^<}"),
736 Some(FormatString {
737 formats: vec![Format {
738 arg: None,
739 spec: Some(FormatSpec {
740 width: None,
741 precision: None,
742 ty: Type::Display,
743 }),
744 }],
745 }),
746 );
747 assert_eq!(
748 format_string("{:+}"),
749 Some(FormatString {
750 formats: vec![Format {
751 arg: None,
752 spec: Some(FormatSpec {
753 width: None,
754 precision: None,
755 ty: Type::Display,
756 }),
757 }],
758 }),
759 );
760 assert_eq!(
761 format_string("{:^<-}"),
762 Some(FormatString {
763 formats: vec![Format {
764 arg: None,
765 spec: Some(FormatSpec {
766 width: None,
767 precision: None,
768 ty: Type::Display,
769 }),
770 }],
771 }),
772 );
773 assert_eq!(
774 format_string("{:#}"),
775 Some(FormatString {
776 formats: vec![Format {
777 arg: None,
778 spec: Some(FormatSpec {
779 width: None,
780 precision: None,
781 ty: Type::Display,
782 }),
783 }],
784 }),
785 );
786 assert_eq!(
787 format_string("{:+#}"),
788 Some(FormatString {
789 formats: vec![Format {
790 arg: None,
791 spec: Some(FormatSpec {
792 width: None,
793 precision: None,
794 ty: Type::Display,
795 }),
796 }],
797 }),
798 );
799 assert_eq!(
800 format_string("{:-<#}"),
801 Some(FormatString {
802 formats: vec![Format {
803 arg: None,
804 spec: Some(FormatSpec {
805 width: None,
806 precision: None,
807 ty: Type::Display,
808 }),
809 }],
810 }),
811 );
812 assert_eq!(
813 format_string("{:^<-#}"),
814 Some(FormatString {
815 formats: vec![Format {
816 arg: None,
817 spec: Some(FormatSpec {
818 width: None,
819 precision: None,
820 ty: Type::Display,
821 }),
822 }],
823 }),
824 );
825 assert_eq!(
826 format_string("{:0}"),
827 Some(FormatString {
828 formats: vec![Format {
829 arg: None,
830 spec: Some(FormatSpec {
831 width: None,
832 precision: None,
833 ty: Type::Display,
834 }),
835 }],
836 }),
837 );
838 assert_eq!(
839 format_string("{:#0}"),
840 Some(FormatString {
841 formats: vec![Format {
842 arg: None,
843 spec: Some(FormatSpec {
844 width: None,
845 precision: None,
846 ty: Type::Display,
847 }),
848 }],
849 }),
850 );
851 assert_eq!(
852 format_string("{:-0}"),
853 Some(FormatString {
854 formats: vec![Format {
855 arg: None,
856 spec: Some(FormatSpec {
857 width: None,
858 precision: None,
859 ty: Type::Display,
860 }),
861 }],
862 }),
863 );
864 assert_eq!(
865 format_string("{:^<0}"),
866 Some(FormatString {
867 formats: vec![Format {
868 arg: None,
869 spec: Some(FormatSpec {
870 width: None,
871 precision: None,
872 ty: Type::Display,
873 }),
874 }],
875 }),
876 );
877 assert_eq!(
878 format_string("{:^<+#0}"),
879 Some(FormatString {
880 formats: vec![Format {
881 arg: None,
882 spec: Some(FormatSpec {
883 width: None,
884 precision: None,
885 ty: Type::Display,
886 }),
887 }],
888 }),
889 );
890 assert_eq!(
891 format_string("{:1}"),
892 Some(FormatString {
893 formats: vec![Format {
894 arg: None,
895 spec: Some(FormatSpec {
896 width: Some(Count::Integer(1)),
897 precision: None,
898 ty: Type::Display,
899 }),
900 }],
901 }),
902 );
903 assert_eq!(
904 format_string("{:1$}"),
905 Some(FormatString {
906 formats: vec![Format {
907 arg: None,
908 spec: Some(FormatSpec {
909 width: Some(Count::Parameter(Argument::Integer(1))),
910 precision: None,
911 ty: Type::Display,
912 }),
913 }],
914 }),
915 );
916 assert_eq!(
917 format_string("{:par$}"),
918 Some(FormatString {
919 formats: vec![Format {
920 arg: None,
921 spec: Some(FormatSpec {
922 width: Some(Count::Parameter(Argument::Identifier("par"))),
923 precision: None,
924 ty: Type::Display,
925 }),
926 }],
927 }),
928 );
929 assert_eq!(
930 format_string("{:-^-#0Минск$}"),
931 Some(FormatString {
932 formats: vec![Format {
933 arg: None,
934 spec: Some(FormatSpec {
935 width: Some(Count::Parameter(Argument::Identifier("Минск"))),
936 precision: None,
937 ty: Type::Display,
938 }),
939 }],
940 }),
941 );
942 assert_eq!(
943 format_string("{:.*}"),
944 Some(FormatString {
945 formats: vec![Format {
946 arg: None,
947 spec: Some(FormatSpec {
948 width: None,
949 precision: Some(Precision::Star),
950 ty: Type::Display,
951 }),
952 }],
953 }),
954 );
955 assert_eq!(
956 format_string("{:.0}"),
957 Some(FormatString {
958 formats: vec![Format {
959 arg: None,
960 spec: Some(FormatSpec {
961 width: None,
962 precision: Some(Precision::Count(Count::Integer(0))),
963 ty: Type::Display,
964 }),
965 }],
966 }),
967 );
968 assert_eq!(
969 format_string("{:.0$}"),
970 Some(FormatString {
971 formats: vec![Format {
972 arg: None,
973 spec: Some(FormatSpec {
974 width: None,
975 precision: Some(Precision::Count(Count::Parameter(
976 Argument::Integer(0),
977 ))),
978 ty: Type::Display,
979 }),
980 }],
981 }),
982 );
983 assert_eq!(
984 format_string("{:.par$}"),
985 Some(FormatString {
986 formats: vec![Format {
987 arg: None,
988 spec: Some(FormatSpec {
989 width: None,
990 precision: Some(Precision::Count(Count::Parameter(
991 Argument::Identifier("par"),
992 ))),
993 ty: Type::Display,
994 }),
995 }],
996 }),
997 );
998 assert_eq!(
999 format_string("{: >+#2$.par$}"),
1000 Some(FormatString {
1001 formats: vec![Format {
1002 arg: None,
1003 spec: Some(FormatSpec {
1004 width: Some(Count::Parameter(Argument::Integer(2))),
1005 precision: Some(Precision::Count(Count::Parameter(
1006 Argument::Identifier("par"),
1007 ))),
1008 ty: Type::Display,
1009 }),
1010 }],
1011 }),
1012 );
1013 assert_eq!(
1014 format_string("{:x?}"),
1015 Some(FormatString {
1016 formats: vec![Format {
1017 arg: None,
1018 spec: Some(FormatSpec {
1019 width: None,
1020 precision: None,
1021 ty: Type::LowerDebug,
1022 }),
1023 }],
1024 }),
1025 );
1026 assert_eq!(
1027 format_string("{:E}"),
1028 Some(FormatString {
1029 formats: vec![Format {
1030 arg: None,
1031 spec: Some(FormatSpec {
1032 width: None,
1033 precision: None,
1034 ty: Type::UpperExp,
1035 }),
1036 }],
1037 }),
1038 );
1039 assert_eq!(
1040 format_string("{: >+#par$.par$X?}"),
1041 Some(FormatString {
1042 formats: vec![Format {
1043 arg: None,
1044 spec: Some(FormatSpec {
1045 width: Some(Count::Parameter(Argument::Identifier("par"))),
1046 precision: Some(Precision::Count(Count::Parameter(
1047 Argument::Identifier("par"),
1048 ))),
1049 ty: Type::UpperDebug,
1050 }),
1051 }],
1052 }),
1053 );
1054 }
1055
1056 #[test]
1057 fn full() {
1058 assert_eq!(
1059 format_string("prefix{{{0:#?}postfix{par:-^par$.a$}}}"),
1060 Some(FormatString {
1061 formats: vec![
1062 Format {
1063 arg: Some(Argument::Integer(0)),
1064 spec: Some(FormatSpec {
1065 width: None,
1066 precision: None,
1067 ty: Type::Debug,
1068 }),
1069 },
1070 Format {
1071 arg: Some(Argument::Identifier("par")),
1072 spec: Some(FormatSpec {
1073 width: Some(Count::Parameter(Argument::Identifier("par"))),
1074 precision: Some(Precision::Count(Count::Parameter(
1075 Argument::Identifier("a"),
1076 ))),
1077 ty: Type::Display,
1078 }),
1079 },
1080 ],
1081 }),
1082 );
1083 }
1084
1085 #[test]
1086 fn error() {
1087 assert_eq!(format_string("{"), None);
1088 assert_eq!(format_string("}"), None);
1089 assert_eq!(format_string("{{}"), None);
1090 assert_eq!(format_string("{:x?"), None);
1091 assert_eq!(format_string("{:.}"), None);
1092 assert_eq!(format_string("{:q}"), None);
1093 assert_eq!(format_string("{:par}"), None);
1094 assert_eq!(format_string("{⚙️}"), None);
1095 }
1096 }