]> git.proxmox.com Git - rustc.git/blame - src/test/ui/fmt/format-args-capture.rs
New upstream version 1.52.0~beta.3+dfsg1
[rustc.git] / src / test / ui / fmt / format-args-capture.rs
CommitLineData
f035d41b 1// run-pass
f035d41b 2#![feature(format_args_capture)]
29967ef6 3#![feature(cfg_panic)]
f035d41b
XL
4
5fn main() {
6 named_argument_takes_precedence_to_captured();
f035d41b 7 formatting_parameters_can_be_captured();
6a06907d 8 capture_raw_strings_and_idents();
29967ef6
XL
9
10 #[cfg(panic = "unwind")]
11 {
12 panic_with_single_argument_does_not_get_formatted();
13 panic_with_multiple_arguments_is_formatted();
14 }
f035d41b
XL
15}
16
17fn 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
6a06907d
XL
29fn 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
29967ef6 39#[cfg(panic = "unwind")]
f035d41b
XL
40fn 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
fc512014 45 #[allow(non_fmt_panic)]
f035d41b
XL
46 let msg = std::panic::catch_unwind(|| {
47 panic!("{foo}");
48 }).unwrap_err();
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(|| {
58 panic!("{}-{bar}-{foo}", "positional", bar="named");
59 }).unwrap_err();
60
61 assert_eq!(msg.downcast_ref::<String>(), Some(&"positional-named-captured".to_string()))
62}
63
64fn formatting_parameters_can_be_captured() {
65 let width = 9;
66 let precision = 3;
67
68 let x = 7.0;
69
70 let s = format!("{x:width$}");
71 assert_eq!(&s, " 7");
72
73 let s = format!("{x:<width$}");
74 assert_eq!(&s, "7 ");
75
76 let s = format!("{x:-^width$}");
77 assert_eq!(&s, "----7----");
78
79 let s = format!("{x:-^width$.precision$}");
80 assert_eq!(&s, "--7.000--");
81}