1 use crate::utils::{snippet_with_applicability, span_lint, span_lint_and_sugg, span_lint_and_then};
2 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
3 use rustc::{declare_lint_pass, declare_tool_lint};
4 use rustc_errors::Applicability;
7 use syntax::parse::{parser, token};
8 use syntax::tokenstream::TokenStream;
9 use syntax_pos::{BytePos, Span};
11 declare_clippy_lint! {
12 /// **What it does:** This lint warns when you use `println!("")` to
15 /// **Why is this bad?** You should use `println!()`, which is simpler.
17 /// **Known problems:** None.
23 pub PRINTLN_EMPTY_STRING,
25 "using `println!(\"\")` with an empty string"
28 declare_clippy_lint! {
29 /// **What it does:** This lint warns when you use `print!()` with a format
31 /// ends in a newline.
33 /// **Why is this bad?** You should use `println!()` instead, which appends the
36 /// **Known problems:** None.
40 /// # let name = "World";
41 /// print!("Hello {}!\n", name);
43 /// use println!() instead
45 /// # let name = "World";
46 /// println!("Hello {}!", name);
48 pub PRINT_WITH_NEWLINE,
50 "using `print!()` with a format string that ends in a single newline"
53 declare_clippy_lint! {
54 /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
55 /// is to catch debugging remnants.
57 /// **Why is this bad?** People often print on *stdout* while debugging an
58 /// application and might forget to remove those prints afterward.
60 /// **Known problems:** Only catches `print!` and `println!` calls.
64 /// println!("Hello world!");
71 declare_clippy_lint! {
72 /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
73 /// lint is to catch debugging remnants.
75 /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
76 /// debugging Rust code. It should not be used in in user-facing output.
80 /// # let foo = "bar";
81 /// println!("{:?}", foo);
85 "use of `Debug`-based formatting"
88 declare_clippy_lint! {
89 /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
91 /// **Why is this bad?** Using literals as `println!` args is inefficient
92 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
93 /// (i.e., just put the literal in the format string)
95 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
96 /// -- e.g., `println!("{}", env!("FOO"))`.
100 /// println!("{}", "foo");
102 /// use the literal without formatting:
108 "printing a literal with a format string"
111 declare_clippy_lint! {
112 /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
115 /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
117 /// **Known problems:** None.
121 /// # use std::fmt::Write;
122 /// # let mut buf = String::new();
123 /// writeln!(buf, "");
125 pub WRITELN_EMPTY_STRING,
127 "using `writeln!(buf, \"\")` with an empty string"
130 declare_clippy_lint! {
131 /// **What it does:** This lint warns when you use `write!()` with a format
133 /// ends in a newline.
135 /// **Why is this bad?** You should use `writeln!()` instead, which appends the
138 /// **Known problems:** None.
142 /// # use std::fmt::Write;
143 /// # let mut buf = String::new();
144 /// # let name = "World";
145 /// write!(buf, "Hello {}!\n", name);
147 pub WRITE_WITH_NEWLINE,
149 "using `write!()` with a format string that ends in a single newline"
152 declare_clippy_lint! {
153 /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
155 /// **Why is this bad?** Using literals as `writeln!` args is inefficient
156 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
157 /// (i.e., just put the literal in the format string)
159 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
160 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
164 /// # use std::fmt::Write;
165 /// # let mut buf = String::new();
166 /// writeln!(buf, "{}", "foo");
170 "writing a literal with a format string"
173 declare_lint_pass!(Write => [
175 PRINTLN_EMPTY_STRING,
180 WRITELN_EMPTY_STRING,
184 impl EarlyLintPass for Write {
185 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &Mac) {
186 if mac.node.path == sym!(println) {
187 span_lint(cx, PRINT_STDOUT, mac.span, "use of `println!`");
188 if let (Some(fmt_str), _) = check_tts(cx, &mac.node.tts, false) {
189 if fmt_str.contents.is_empty() {
192 PRINTLN_EMPTY_STRING,
194 "using `println!(\"\")`",
196 "println!()".to_string(),
197 Applicability::MachineApplicable,
201 } else if mac.node.path == sym!(print) {
202 span_lint(cx, PRINT_STDOUT, mac.span, "use of `print!`");
203 if let (Some(fmt_str), _) = check_tts(cx, &mac.node.tts, false) {
204 if check_newlines(&fmt_str) {
209 "using `print!()` with a format string that ends in a single newline",
211 err.multipart_suggestion(
212 "use `println!` instead",
214 (mac.node.path.span, String::from("println")),
215 (fmt_str.newline_span(), String::new()),
217 Applicability::MachineApplicable,
223 } else if mac.node.path == sym!(write) {
224 if let (Some(fmt_str), _) = check_tts(cx, &mac.node.tts, true) {
225 if check_newlines(&fmt_str) {
230 "using `write!()` with a format string that ends in a single newline",
232 err.multipart_suggestion(
233 "use `writeln!()` instead",
235 (mac.node.path.span, String::from("writeln")),
236 (fmt_str.newline_span(), String::new()),
238 Applicability::MachineApplicable,
244 } else if mac.node.path == sym!(writeln) {
245 if let (Some(fmt_str), expr) = check_tts(cx, &mac.node.tts, true) {
246 if fmt_str.contents.is_empty() {
247 let mut applicability = Applicability::MachineApplicable;
248 let suggestion = expr.map_or_else(
250 applicability = Applicability::HasPlaceholders;
253 move |expr| snippet_with_applicability(cx, expr.span, "v", &mut applicability),
258 WRITELN_EMPTY_STRING,
260 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
262 format!("writeln!({})", suggestion),
271 /// The arguments of a `print[ln]!` or `write[ln]!` invocation.
273 /// The contents of the format string (inside the quotes).
276 /// The span of the format string, including quotes, the raw marker, and any raw hashes.
281 /// Given a format string that ends in a newline and its span, calculates the span of the
283 fn newline_span(&self) -> Span {
286 let newline_sp_hi = sp.hi()
288 StrStyle::Cooked => BytePos(1),
289 StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
292 let newline_sp_len = if self.contents.ends_with('\n') {
294 } else if self.contents.ends_with(r"\n") {
297 panic!("expected format string to contain a newline");
300 sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi)
304 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
305 /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
306 /// the contents of the string, whether it's a raw string, and the span of the literal in the
307 /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
308 /// `format_str` should be written to.
312 /// Calling this function on
314 /// # use std::fmt::Write;
315 /// # let mut buf = String::new();
316 /// # let something = "something";
317 /// writeln!(buf, "string to write: {}", something);
321 /// (Some("string to write: {}"), Some(buf))
323 fn check_tts<'a>(cx: &EarlyContext<'a>, tts: &TokenStream, is_write: bool) -> (Option<FmtStr>, Option<Expr>) {
325 let tts = tts.clone();
327 let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, None, false, false, None);
328 let mut expr: Option<Expr> = None;
330 expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
331 Ok(p) => Some(p.into_inner()),
332 Err(_) => return (None, None),
334 // might be `writeln!(foo)`
335 if parser.expect(&token::Comma).map_err(|mut err| err.cancel()).is_err() {
340 let (fmtstr, fmtstyle) = match parser.parse_str().map_err(|mut err| err.cancel()) {
341 Ok((fmtstr, fmtstyle)) => (fmtstr.to_string(), fmtstyle),
342 Err(_) => return (None, expr),
344 let fmtspan = parser.prev_span;
345 let tmp = fmtstr.clone();
346 let mut args = vec![];
347 let mut fmt_parser = Parser::new(&tmp, None, Vec::new(), false);
348 while let Some(piece) = fmt_parser.next() {
349 if !fmt_parser.errors.is_empty() {
352 if let Piece::NextArgument(arg) = piece {
353 if arg.format.ty == "?" {
354 // FIXME: modify rustc's fmt string parser to give us the current span
355 span_lint(cx, USE_DEBUG, parser.prev_span, "use of `Debug`-based formatting");
360 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
363 const SIMPLE: FormatSpec<'_> = FormatSpec {
367 precision: CountImplied,
368 precision_span: None,
373 if !parser.eat(&token::Comma) {
383 let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
395 match &token_expr.node {
396 ExprKind::Lit(_) => {
397 let mut all_simple = true;
398 let mut seen = false;
401 ArgumentImplicitlyIs(n) | ArgumentIs(n) => {
403 all_simple &= arg.format == SIMPLE;
407 ArgumentNamed(_) => {},
410 if all_simple && seen {
411 span_lint(cx, lint, token_expr.span, "literal with an empty format string");
415 ExprKind::Assign(lhs, rhs) => {
416 if let ExprKind::Lit(_) = rhs.node {
417 if let ExprKind::Path(_, p) = &lhs.node {
418 let mut all_simple = true;
419 let mut seen = false;
422 ArgumentImplicitlyIs(_) | ArgumentIs(_) => {},
423 ArgumentNamed(name) => {
426 all_simple &= arg.format == SIMPLE;
431 if all_simple && seen {
432 span_lint(cx, lint, rhs.span, "literal with an empty format string");
442 /// Checks if the format string constains a single newline that terminates it.
444 /// Literal and escaped newlines are both checked (only literal for raw strings).
445 fn check_newlines(fmt_str: &FmtStr) -> bool {
446 let s = &fmt_str.contents;
448 if s.ends_with('\n') {
450 } else if let StrStyle::Raw(_) = fmt_str.style {
458 let bytes = s.as_bytes();
459 if bytes[bytes.len() - 2] != b'\\' || bytes[bytes.len() - 1] != b'n' {
463 let mut escaping = false;
464 for (index, &byte) in bytes.iter().enumerate() {
467 return index == bytes.len() - 1;
470 } else if byte == b'\\' {