]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/tests/ui/format.rs
New upstream version 1.64.0+dfsg1
[rustc.git] / src / tools / clippy / tests / ui / format.rs
1 // run-rustfix
2
3 #![allow(
4 unused_tuple_struct_fields,
5 clippy::print_literal,
6 clippy::redundant_clone,
7 clippy::to_string_in_format_args,
8 clippy::needless_borrow
9 )]
10 #![warn(clippy::useless_format)]
11
12 struct Foo(pub String);
13
14 macro_rules! foo {
15 ($($t:tt)*) => (Foo(format!($($t)*)))
16 }
17
18 fn main() {
19 format!("foo");
20 format!("{{}}");
21 format!("{{}} abc {{}}");
22 format!(
23 r##"foo {{}}
24 " bar"##
25 );
26
27 let _ = format!("");
28
29 format!("{}", "foo");
30 format!("{:?}", "foo"); // Don't warn about `Debug`.
31 format!("{:8}", "foo");
32 format!("{:width$}", "foo", width = 8);
33 format!("{:+}", "foo"); // Warn when the format makes no difference.
34 format!("{:<}", "foo"); // Warn when the format makes no difference.
35 format!("foo {}", "bar");
36 format!("{} bar", "foo");
37
38 let arg: String = "".to_owned();
39 format!("{}", arg);
40 format!("{:?}", arg); // Don't warn about debug.
41 format!("{:8}", arg);
42 format!("{:width$}", arg, width = 8);
43 format!("{:+}", arg); // Warn when the format makes no difference.
44 format!("{:<}", arg); // Warn when the format makes no difference.
45 format!("foo {}", arg);
46 format!("{} bar", arg);
47
48 // We don’t want to warn for non-string args; see issue #697.
49 format!("{}", 42);
50 format!("{:?}", 42);
51 format!("{:+}", 42);
52 format!("foo {}", 42);
53 format!("{} bar", 42);
54
55 // We only want to warn about `format!` itself.
56 println!("foo");
57 println!("{}", "foo");
58 println!("foo {}", "foo");
59 println!("{}", 42);
60 println!("foo {}", 42);
61
62 // A `format!` inside a macro should not trigger a warning.
63 foo!("should not warn");
64
65 // Precision on string means slicing without panicking on size.
66 format!("{:.1}", "foo"); // Could be `"foo"[..1]`
67 format!("{:.10}", "foo"); // Could not be `"foo"[..10]`
68 format!("{:.prec$}", "foo", prec = 1);
69 format!("{:.prec$}", "foo", prec = 10);
70
71 format!("{}", 42.to_string());
72 let x = std::path::PathBuf::from("/bar/foo/qux");
73 format!("{}", x.display().to_string());
74
75 // False positive
76 let a = "foo".to_string();
77 let _ = Some(format!("{}", a + "bar"));
78
79 // Wrap it with braces
80 let v: Vec<String> = vec!["foo".to_string(), "bar".to_string()];
81 let _s: String = format!("{}", &*v.join("\n"));
82
83 format!("prepend {:+}", "s");
84
85 // Issue #8290
86 let x = "foo";
87 let _ = format!("{x}");
88 let _ = format!("{x:?}"); // Don't lint on debug
89 let _ = format!("{y}", y = x);
90
91 // Issue #9234
92 let abc = "abc";
93 let _ = format!("{abc}");
94 let xx = "xx";
95 let _ = format!("{xx}");
96 }