1 use crate::utils::{snippet_with_applicability, span_lint, span_lint_and_sugg};
2 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
3 use rustc::{declare_tool_lint, lint_array};
4 use rustc_errors::Applicability;
7 use syntax::parse::{parser, token};
8 use syntax::tokenstream::TokenStream;
10 /// **What it does:** This lint warns when you use `println!("")` to
13 /// **Why is this bad?** You should use `println!()`, which is simpler.
15 /// **Known problems:** None.
21 declare_clippy_lint! {
22 pub PRINTLN_EMPTY_STRING,
24 "using `println!(\"\")` with an empty string"
27 /// **What it does:** This lint warns when you use `print!()` with a format
29 /// ends in a newline.
31 /// **Why is this bad?** You should use `println!()` instead, which appends the
34 /// **Known problems:** None.
38 /// print!("Hello {}!\n", name);
40 /// use println!() instead
42 /// println!("Hello {}!", name);
44 declare_clippy_lint! {
45 pub PRINT_WITH_NEWLINE,
47 "using `print!()` with a format string that ends in a single newline"
50 /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
51 /// is to catch debugging remnants.
53 /// **Why is this bad?** People often print on *stdout* while debugging an
54 /// application and might forget to remove those prints afterward.
56 /// **Known problems:** Only catches `print!` and `println!` calls.
60 /// println!("Hello world!");
62 declare_clippy_lint! {
68 /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
69 /// lint is to catch debugging remnants.
71 /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
72 /// debugging Rust code. It should not be used in in user-facing output.
76 /// println!("{:?}", foo);
78 declare_clippy_lint! {
81 "use of `Debug`-based formatting"
84 /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
86 /// **Why is this bad?** Using literals as `println!` args is inefficient
87 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
88 /// (i.e., just put the literal in the format string)
90 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
91 /// -- e.g., `println!("{}", env!("FOO"))`.
95 /// println!("{}", "foo");
97 /// use the literal without formatting:
101 declare_clippy_lint! {
104 "printing a literal with a format string"
107 /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
110 /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
112 /// **Known problems:** None.
118 declare_clippy_lint! {
119 pub WRITELN_EMPTY_STRING,
121 "using `writeln!(\"\")` with an empty string"
124 /// **What it does:** This lint warns when you use `write!()` with a format
126 /// ends in a newline.
128 /// **Why is this bad?** You should use `writeln!()` instead, which appends the
131 /// **Known problems:** None.
135 /// write!(buf, "Hello {}!\n", name);
137 declare_clippy_lint! {
138 pub WRITE_WITH_NEWLINE,
140 "using `write!()` with a format string that ends in a single newline"
143 /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
145 /// **Why is this bad?** Using literals as `writeln!` args is inefficient
146 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
147 /// (i.e., just put the literal in the format string)
149 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
150 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
154 /// writeln!(buf, "{}", "foo");
156 declare_clippy_lint! {
159 "writing a literal with a format string"
162 #[derive(Copy, Clone, Debug)]
165 impl LintPass for Pass {
166 fn get_lints(&self) -> LintArray {
169 PRINTLN_EMPTY_STRING,
174 WRITELN_EMPTY_STRING,
179 fn name(&self) -> &'static str {
184 impl EarlyLintPass for Pass {
185 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &Mac) {
186 if mac.node.path == "println" {
187 span_lint(cx, PRINT_STDOUT, mac.span, "use of `println!`");
188 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, false).0 {
192 PRINTLN_EMPTY_STRING,
194 "using `println!(\"\")`",
196 "println!()".to_string(),
197 Applicability::MachineApplicable,
201 } else if mac.node.path == "print" {
202 span_lint(cx, PRINT_STDOUT, mac.span, "use of `print!`");
203 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, false).0 {
204 if check_newlines(&fmtstr) {
209 "using `print!()` with a format string that ends in a \
210 single newline, consider using `println!()` instead",
214 } else if mac.node.path == "write" {
215 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, true).0 {
216 if check_newlines(&fmtstr) {
221 "using `write!()` with a format string that ends in a \
222 single newline, consider using `writeln!()` instead",
226 } else if mac.node.path == "writeln" {
227 let check_tts = check_tts(cx, &mac.node.tts, true);
228 if let Some(fmtstr) = check_tts.0 {
230 let mut applicability = Applicability::MachineApplicable;
231 let suggestion = check_tts.1.map_or_else(
233 applicability = Applicability::HasPlaceholders;
236 move |expr| snippet_with_applicability(cx, expr.span, "v", &mut applicability),
241 WRITELN_EMPTY_STRING,
243 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
245 format!("writeln!({})", suggestion),
254 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
255 /// options. The first part of the tuple is `format_str` of the macros. The second part of the tuple
256 /// is in the `write[ln]!` case the expression the `format_str` should be written to.
260 /// Calling this function on
262 /// writeln!(buf, "string to write: {}", something)
266 /// (Some("string to write: {}"), Some(buf))
268 fn check_tts<'a>(cx: &EarlyContext<'a>, tts: &TokenStream, is_write: bool) -> (Option<String>, Option<Expr>) {
270 let tts = tts.clone();
271 let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, None, false, false);
272 let mut expr: Option<Expr> = None;
274 expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
275 Ok(p) => Some(p.into_inner()),
276 Err(_) => return (None, None),
278 // might be `writeln!(foo)`
279 if parser.expect(&token::Comma).map_err(|mut err| err.cancel()).is_err() {
284 let fmtstr = match parser.parse_str().map_err(|mut err| err.cancel()) {
285 Ok(token) => token.0.to_string(),
286 Err(_) => return (None, expr),
288 let tmp = fmtstr.clone();
289 let mut args = vec![];
290 let mut fmt_parser = Parser::new(&tmp, None, Vec::new(), false);
291 while let Some(piece) = fmt_parser.next() {
292 if !fmt_parser.errors.is_empty() {
295 if let Piece::NextArgument(arg) = piece {
296 if arg.format.ty == "?" {
297 // FIXME: modify rustc's fmt string parser to give us the current span
298 span_lint(cx, USE_DEBUG, parser.prev_span, "use of `Debug`-based formatting");
303 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
306 const SIMPLE: FormatSpec<'_> = FormatSpec {
310 precision: CountImplied,
314 if !parser.eat(&token::Comma) {
315 return (Some(fmtstr), expr);
317 let token_expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
319 Err(_) => return (Some(fmtstr), None),
321 match &token_expr.node {
322 ExprKind::Lit(_) => {
323 let mut all_simple = true;
324 let mut seen = false;
327 ArgumentImplicitlyIs(n) | ArgumentIs(n) => {
329 all_simple &= arg.format == SIMPLE;
333 ArgumentNamed(_) => {},
336 if all_simple && seen {
337 span_lint(cx, lint, token_expr.span, "literal with an empty format string");
341 ExprKind::Assign(lhs, rhs) => {
342 if let ExprKind::Lit(_) = rhs.node {
343 if let ExprKind::Path(_, p) = &lhs.node {
344 let mut all_simple = true;
345 let mut seen = false;
348 ArgumentImplicitlyIs(_) | ArgumentIs(_) => {},
349 ArgumentNamed(name) => {
352 all_simple &= arg.format == SIMPLE;
357 if all_simple && seen {
358 span_lint(cx, lint, rhs.span, "literal with an empty format string");
368 // Checks if `s` constains a single newline that terminates it
369 fn check_newlines(s: &str) -> bool {
374 let bytes = s.as_bytes();
375 if bytes[bytes.len() - 2] != b'\\' || bytes[bytes.len() - 1] != b'n' {
379 let mut escaping = false;
380 for (index, &byte) in bytes.iter().enumerate() {
383 return index == bytes.len() - 1;
386 } else if byte == b'\\' {