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