2 use rustc::{declare_lint, lint_array};
4 use syntax::tokenstream::{ThinTokenStream, TokenStream};
5 use syntax::parse::{token, parser};
6 use crate::utils::{span_lint, span_lint_and_sugg};
8 /// **What it does:** This lint warns when you use `println!("")` to
11 /// **Why is this bad?** You should use `println!()`, which is simpler.
13 /// **Known problems:** None.
19 declare_clippy_lint! {
20 pub PRINTLN_EMPTY_STRING,
22 "using `println!(\"\")` with an empty string"
25 /// **What it does:** This lint warns when you use `print!()` with a format
27 /// ends in a newline.
29 /// **Why is this bad?** You should use `println!()` instead, which appends the
32 /// **Known problems:** None.
36 /// print!("Hello {}!\n", name);
38 declare_clippy_lint! {
39 pub PRINT_WITH_NEWLINE,
41 "using `print!()` with a format string that ends in a newline"
44 /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
45 /// is to catch debugging remnants.
47 /// **Why is this bad?** People often print on *stdout* while debugging an
48 /// application and might forget to remove those prints afterward.
50 /// **Known problems:** Only catches `print!` and `println!` calls.
54 /// println!("Hello world!");
56 declare_clippy_lint! {
62 /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
63 /// lint is to catch debugging remnants.
65 /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
66 /// debugging Rust code. It should not be used in in user-facing output.
70 /// println!("{:?}", foo);
72 declare_clippy_lint! {
75 "use of `Debug`-based formatting"
78 /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
80 /// **Why is this bad?** Using literals as `println!` args is inefficient
81 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
82 /// (i.e., just put the literal in the format string)
84 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
85 /// -- e.g., `println!("{}", env!("FOO"))`.
89 /// println!("{}", "foo");
91 declare_clippy_lint! {
94 "printing a literal with a format string"
97 /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
100 /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
102 /// **Known problems:** None.
108 declare_clippy_lint! {
109 pub WRITELN_EMPTY_STRING,
111 "using `writeln!(\"\")` with an empty string"
114 /// **What it does:** This lint warns when you use `write!()` with a format
116 /// ends in a newline.
118 /// **Why is this bad?** You should use `writeln!()` instead, which appends the
121 /// **Known problems:** None.
125 /// write!(buf, "Hello {}!\n", name);
127 declare_clippy_lint! {
128 pub WRITE_WITH_NEWLINE,
130 "using `write!()` with a format string that ends in a newline"
133 /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
135 /// **Why is this bad?** Using literals as `writeln!` args is inefficient
136 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
137 /// (i.e., just put the literal in the format string)
139 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
140 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
144 /// writeln!(buf, "{}", "foo");
146 declare_clippy_lint! {
149 "writing a literal with a format string"
152 #[derive(Copy, Clone, Debug)]
155 impl LintPass for Pass {
156 fn get_lints(&self) -> LintArray {
159 PRINTLN_EMPTY_STRING,
164 WRITELN_EMPTY_STRING,
170 impl EarlyLintPass for Pass {
171 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &Mac) {
172 if mac.node.path == "println" {
173 span_lint(cx, PRINT_STDOUT, mac.span, "use of `println!`");
174 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, false) {
178 PRINTLN_EMPTY_STRING,
180 "using `println!(\"\")`",
182 "println!()".to_string(),
186 } else if mac.node.path == "print" {
187 span_lint(cx, PRINT_STDOUT, mac.span, "use of `print!`");
188 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, false) {
189 if fmtstr.ends_with("\\n") {
190 span_lint(cx, PRINT_WITH_NEWLINE, mac.span,
191 "using `print!()` with a format string that ends in a \
192 newline, consider using `println!()` instead");
195 } else if mac.node.path == "write" {
196 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, true) {
197 if fmtstr.ends_with("\\n") {
198 span_lint(cx, WRITE_WITH_NEWLINE, mac.span,
199 "using `write!()` with a format string that ends in a \
200 newline, consider using `writeln!()` instead");
203 } else if mac.node.path == "writeln" {
204 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, true) {
208 WRITELN_EMPTY_STRING,
210 "using `writeln!(v, \"\")`",
212 "writeln!(v)".to_string(),
220 fn check_tts(cx: &EarlyContext<'a>, tts: &ThinTokenStream, is_write: bool) -> Option<String> {
221 let tts = TokenStream::from(tts.clone());
222 let mut parser = parser::Parser::new(
230 // skip the initial write target
231 parser.parse_expr().map_err(|mut err| err.cancel()).ok()?;
232 // might be `writeln!(foo)`
233 parser.expect(&token::Comma).map_err(|mut err| err.cancel()).ok()?;
235 let fmtstr = parser.parse_str().map_err(|mut err| err.cancel()).ok()?.0.to_string();
237 let tmp = fmtstr.clone();
238 let mut args = vec![];
239 let mut fmt_parser = Parser::new(&tmp, None);
240 while let Some(piece) = fmt_parser.next() {
241 if !fmt_parser.errors.is_empty() {
244 if let Piece::NextArgument(arg) = piece {
245 if arg.format.ty == "?" {
246 // FIXME: modify rustc's fmt string parser to give us the current span
247 span_lint(cx, USE_DEBUG, parser.prev_span, "use of `Debug`-based formatting");
252 let lint = if is_write {
259 if !parser.eat(&token::Comma) {
260 assert!(parser.eat(&token::Eof));
263 let expr = parser.parse_expr().map_err(|mut err| err.cancel()).ok()?;
264 const SIMPLE: FormatSpec<'_> = FormatSpec {
268 precision: CountImplied,
273 ExprKind::Lit(_) => {
274 let mut all_simple = true;
275 let mut seen = false;
278 | ArgumentImplicitlyIs(n)
281 all_simple &= arg.format == SIMPLE;
284 ArgumentNamed(_) => {},
287 if all_simple && seen {
288 span_lint(cx, lint, expr.span, "literal with an empty format string");
292 ExprKind::Assign(lhs, rhs) => {
293 if let ExprKind::Lit(_) = rhs.node {
294 if let ExprKind::Path(_, p) = &lhs.node {
295 let mut all_simple = true;
296 let mut seen = false;
299 | ArgumentImplicitlyIs(_)
302 ArgumentNamed(name) => if *p == name {
304 all_simple &= arg.format == SIMPLE;
308 if all_simple && seen {
309 span_lint(cx, lint, rhs.span, "literal with an empty format string");