]> git.proxmox.com Git - rustc.git/blame - src/test/ui/fmt/format-args-capture.rs
New upstream version 1.58.1+dfsg1
[rustc.git] / src / test / ui / fmt / format-args-capture.rs
CommitLineData
f035d41b 1// run-pass
29967ef6 2#![feature(cfg_panic)]
f035d41b
XL
3
4fn main() {
5 named_argument_takes_precedence_to_captured();
f035d41b 6 formatting_parameters_can_be_captured();
6a06907d 7 capture_raw_strings_and_idents();
29967ef6
XL
8
9 #[cfg(panic = "unwind")]
10 {
11 panic_with_single_argument_does_not_get_formatted();
12 panic_with_multiple_arguments_is_formatted();
13 }
f035d41b
XL
14}
15
16fn named_argument_takes_precedence_to_captured() {
17 let foo = "captured";
136023e0 18 let s = format!("{foo}", foo = "named");
f035d41b
XL
19 assert_eq!(&s, "named");
20
136023e0 21 let s = format!("{foo}-{foo}-{foo}", foo = "named");
f035d41b
XL
22 assert_eq!(&s, "named-named-named");
23
136023e0 24 let s = format!("{}-{bar}-{foo}", "positional", bar = "named");
f035d41b
XL
25 assert_eq!(&s, "positional-named-captured");
26}
27
6a06907d
XL
28fn 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
29967ef6 38#[cfg(panic = "unwind")]
f035d41b
XL
39fn 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
136023e0 44 #[allow(non_fmt_panics)]
f035d41b
XL
45 let msg = std::panic::catch_unwind(|| {
46 panic!("{foo}");
136023e0
XL
47 })
48 .unwrap_err();
f035d41b
XL
49
50 assert_eq!(msg.downcast_ref::<&str>(), Some(&"{foo}"))
51}
52
29967ef6 53#[cfg(panic = "unwind")]
f035d41b
XL
54fn panic_with_multiple_arguments_is_formatted() {
55 let foo = "captured";
56
57 let msg = std::panic::catch_unwind(|| {
136023e0
XL
58 panic!("{}-{bar}-{foo}", "positional", bar = "named");
59 })
60 .unwrap_err();
f035d41b
XL
61
62 assert_eq!(msg.downcast_ref::<String>(), Some(&"positional-named-captured".to_string()))
63}
64
65fn 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}