1 use crate::utils::{snippet, span_lint, span_lint_and_sugg};
2 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
3 use rustc::{declare_tool_lint, lint_array};
6 use syntax::parse::{parser, token};
7 use syntax::tokenstream::{ThinTokenStream, TokenStream};
9 /// **What it does:** This lint warns when you use `println!("")` to
12 /// **Why is this bad?** You should use `println!()`, which is simpler.
14 /// **Known problems:** None.
20 declare_clippy_lint! {
21 pub PRINTLN_EMPTY_STRING,
23 "using `println!(\"\")` with an empty string"
26 /// **What it does:** This lint warns when you use `print!()` with a format
28 /// ends in a newline.
30 /// **Why is this bad?** You should use `println!()` instead, which appends the
33 /// **Known problems:** None.
37 /// print!("Hello {}!\n", name);
39 /// use println!() instead
41 /// println!("Hello {}!", name);
43 declare_clippy_lint! {
44 pub PRINT_WITH_NEWLINE,
46 "using `print!()` with a format string that ends in a single newline"
49 /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
50 /// is to catch debugging remnants.
52 /// **Why is this bad?** People often print on *stdout* while debugging an
53 /// application and might forget to remove those prints afterward.
55 /// **Known problems:** Only catches `print!` and `println!` calls.
59 /// println!("Hello world!");
61 declare_clippy_lint! {
67 /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
68 /// lint is to catch debugging remnants.
70 /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
71 /// debugging Rust code. It should not be used in in user-facing output.
75 /// println!("{:?}", foo);
77 declare_clippy_lint! {
80 "use of `Debug`-based formatting"
83 /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
85 /// **Why is this bad?** Using literals as `println!` args is inefficient
86 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
87 /// (i.e., just put the literal in the format string)
89 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
90 /// -- e.g., `println!("{}", env!("FOO"))`.
94 /// println!("{}", "foo");
96 /// use the literal without formatting:
100 declare_clippy_lint! {
103 "printing a literal with a format string"
106 /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
109 /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
111 /// **Known problems:** None.
117 declare_clippy_lint! {
118 pub WRITELN_EMPTY_STRING,
120 "using `writeln!(\"\")` with an empty string"
123 /// **What it does:** This lint warns when you use `write!()` with a format
125 /// ends in a newline.
127 /// **Why is this bad?** You should use `writeln!()` instead, which appends the
130 /// **Known problems:** None.
134 /// write!(buf, "Hello {}!\n", name);
136 declare_clippy_lint! {
137 pub WRITE_WITH_NEWLINE,
139 "using `write!()` with a format string that ends in a single newline"
142 /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
144 /// **Why is this bad?** Using literals as `writeln!` args is inefficient
145 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
146 /// (i.e., just put the literal in the format string)
148 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
149 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
153 /// writeln!(buf, "{}", "foo");
155 declare_clippy_lint! {
158 "writing a literal with a format string"
161 #[derive(Copy, Clone, Debug)]
164 impl LintPass for Pass {
165 fn get_lints(&self) -> LintArray {
168 PRINTLN_EMPTY_STRING,
173 WRITELN_EMPTY_STRING,
179 impl EarlyLintPass for Pass {
180 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &Mac) {
181 if mac.node.path == "println" {
182 span_lint(cx, PRINT_STDOUT, mac.span, "use of `println!`");
183 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, false).0 {
187 PRINTLN_EMPTY_STRING,
189 "using `println!(\"\")`",
191 "println!()".to_string(),
195 } else if mac.node.path == "print" {
196 span_lint(cx, PRINT_STDOUT, mac.span, "use of `print!`");
197 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, false).0 {
198 if fmtstr.ends_with("\\n") &&
199 // don't warn about strings with several `\n`s (#3126)
200 fmtstr.matches("\\n").count() == 1
206 "using `print!()` with a format string that ends in a \
207 single newline, consider using `println!()` instead",
211 } else if mac.node.path == "write" {
212 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, true).0 {
213 if fmtstr.ends_with("\\n") &&
214 // don't warn about strings with several `\n`s (#3126)
215 fmtstr.matches("\\n").count() == 1
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 suggestion = check_tts
232 .map_or(Cow::Borrowed("v"), |expr| snippet(cx, expr.span, "v"));
236 WRITELN_EMPTY_STRING,
238 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
240 format!("writeln!({})", suggestion),
248 fn check_tts<'a>(cx: &EarlyContext<'a>, tts: &ThinTokenStream, is_write: bool) -> (Option<String>, Option<Expr>) {
249 let tts = TokenStream::from(tts.clone());
250 let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, None, false, false);
251 let mut expr: Option<Expr> = None;
253 expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
254 Ok(p) => Some(p.into_inner()),
255 Err(_) => return (None, None),
257 // might be `writeln!(foo)`
258 if parser.expect(&token::Comma).map_err(|mut err| err.cancel()).is_err() {
263 let fmtstr = match parser.parse_str().map_err(|mut err| err.cancel()) {
264 Ok(token) => token.0.to_string(),
265 Err(_) => return (None, expr),
268 let tmp = fmtstr.clone();
269 let mut args = vec![];
270 let mut fmt_parser = Parser::new(&tmp, None);
271 while let Some(piece) = fmt_parser.next() {
272 if !fmt_parser.errors.is_empty() {
275 if let Piece::NextArgument(arg) = piece {
276 if arg.format.ty == "?" {
277 // FIXME: modify rustc's fmt string parser to give us the current span
278 span_lint(cx, USE_DEBUG, parser.prev_span, "use of `Debug`-based formatting");
283 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
286 if !parser.eat(&token::Comma) {
287 assert!(parser.eat(&token::Eof));
288 return (Some(fmtstr), expr);
290 let token_expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
292 Err(_) => return (Some(fmtstr), None),
294 const SIMPLE: FormatSpec<'_> = FormatSpec {
298 precision: CountImplied,
302 match &token_expr.node {
303 ExprKind::Lit(_) => {
304 let mut all_simple = true;
305 let mut seen = false;
308 ArgumentImplicitlyIs(n) | ArgumentIs(n) => if n == idx {
309 all_simple &= arg.format == SIMPLE;
312 ArgumentNamed(_) => {},
315 if all_simple && seen {
316 span_lint(cx, lint, token_expr.span, "literal with an empty format string");
320 ExprKind::Assign(lhs, rhs) => {
321 if let ExprKind::Lit(_) = rhs.node {
322 if let ExprKind::Path(_, p) = &lhs.node {
323 let mut all_simple = true;
324 let mut seen = false;
327 ArgumentImplicitlyIs(_) | ArgumentIs(_) => {},
328 ArgumentNamed(name) => if *p == name {
330 all_simple &= arg.format == SIMPLE;
334 if all_simple && seen {
335 span_lint(cx, lint, rhs.span, "literal with an empty format string");