]> git.lizzy.rs Git - rust.git/blob - src/test/ui/fmt/format-args-capture.rs
e830a5bc9c5c86947d40cbb331377b23beb9b233
[rust.git] / src / test / ui / fmt / format-args-capture.rs
1 // run-pass
2 #![feature(cfg_panic)]
3
4 fn main() {
5     named_argument_takes_precedence_to_captured();
6     formatting_parameters_can_be_captured();
7     capture_raw_strings_and_idents();
8
9     #[cfg(panic = "unwind")]
10     {
11         panic_with_single_argument_does_not_get_formatted();
12         panic_with_multiple_arguments_is_formatted();
13     }
14 }
15
16 fn named_argument_takes_precedence_to_captured() {
17     let foo = "captured";
18     let s = format!("{foo}", foo = "named");
19     assert_eq!(&s, "named");
20
21     let s = format!("{foo}-{foo}-{foo}", foo = "named");
22     assert_eq!(&s, "named-named-named");
23
24     let s = format!("{}-{bar}-{foo}", "positional", bar = "named");
25     assert_eq!(&s, "positional-named-captured");
26 }
27
28 fn capture_raw_strings_and_idents() {
29     let r#type = "apple";
30     let s = format!(r#"The fruit is an {type}"#);
31     assert_eq!(&s, "The fruit is an apple");
32
33     let r#type = "orange";
34     let s = format!(r"The fruit is an {type}");
35     assert_eq!(&s, "The fruit is an orange");
36 }
37
38 #[cfg(panic = "unwind")]
39 fn panic_with_single_argument_does_not_get_formatted() {
40     // panic! with a single argument does not perform string formatting.
41     // RFC #2795 suggests that this may need to change so that captured arguments are formatted.
42     // For stability reasons this will need to part of an edition change.
43
44     #[allow(non_fmt_panics)]
45     let msg = std::panic::catch_unwind(|| {
46         panic!("{foo}");
47     })
48     .unwrap_err();
49
50     assert_eq!(msg.downcast_ref::<&str>(), Some(&"{foo}"))
51 }
52
53 #[cfg(panic = "unwind")]
54 fn panic_with_multiple_arguments_is_formatted() {
55     let foo = "captured";
56
57     let msg = std::panic::catch_unwind(|| {
58         panic!("{}-{bar}-{foo}", "positional", bar = "named");
59     })
60     .unwrap_err();
61
62     assert_eq!(msg.downcast_ref::<String>(), Some(&"positional-named-captured".to_string()))
63 }
64
65 fn formatting_parameters_can_be_captured() {
66     let width = 9;
67     let precision = 3;
68
69     let x = 7.0;
70
71     let s = format!("{x:width$}");
72     assert_eq!(&s, "        7");
73
74     let s = format!("{x:<width$}");
75     assert_eq!(&s, "7        ");
76
77     let s = format!("{x:-^width$}");
78     assert_eq!(&s, "----7----");
79
80     let s = format!("{x:-^width$.precision$}");
81     assert_eq!(&s, "--7.000--");
82 }