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::{symbol::Symbol, 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 /// println!("{:?}", foo);
84 "use of `Debug`-based formatting"
87 declare_clippy_lint! {
88 /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
90 /// **Why is this bad?** Using literals as `println!` args is inefficient
91 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
92 /// (i.e., just put the literal in the format string)
94 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
95 /// -- e.g., `println!("{}", env!("FOO"))`.
99 /// println!("{}", "foo");
101 /// use the literal without formatting:
107 "printing a literal with a format string"
110 declare_clippy_lint! {
111 /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
114 /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
116 /// **Known problems:** None.
120 /// # use std::fmt::Write;
121 /// # let mut buf = String::new();
122 /// writeln!(buf, "");
124 pub WRITELN_EMPTY_STRING,
126 "using `writeln!(buf, \"\")` with an empty string"
129 declare_clippy_lint! {
130 /// **What it does:** This lint warns when you use `write!()` with a format
132 /// ends in a newline.
134 /// **Why is this bad?** You should use `writeln!()` instead, which appends the
137 /// **Known problems:** None.
141 /// # use std::fmt::Write;
142 /// # let mut buf = String::new();
143 /// # let name = "World";
144 /// write!(buf, "Hello {}!\n", name);
146 pub WRITE_WITH_NEWLINE,
148 "using `write!()` with a format string that ends in a single newline"
151 declare_clippy_lint! {
152 /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
154 /// **Why is this bad?** Using literals as `writeln!` args is inefficient
155 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
156 /// (i.e., just put the literal in the format string)
158 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
159 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
163 /// # use std::fmt::Write;
164 /// # let mut buf = String::new();
165 /// writeln!(buf, "{}", "foo");
169 "writing a literal with a format string"
172 declare_lint_pass!(Write => [
174 PRINTLN_EMPTY_STRING,
179 WRITELN_EMPTY_STRING,
183 impl EarlyLintPass for Write {
184 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &Mac) {
185 if mac.node.path == sym!(println) {
186 span_lint(cx, PRINT_STDOUT, mac.span, "use of `println!`");
187 if let (Some(fmt_str), _) = check_tts(cx, &mac.node.tts, false) {
188 if fmt_str.contents.is_empty() {
191 PRINTLN_EMPTY_STRING,
193 "using `println!(\"\")`",
195 "println!()".to_string(),
196 Applicability::MachineApplicable,
200 } else if mac.node.path == sym!(print) {
201 span_lint(cx, PRINT_STDOUT, mac.span, "use of `print!`");
202 if let (Some(fmt_str), _) = check_tts(cx, &mac.node.tts, false) {
203 if check_newlines(&fmt_str) {
208 "using `print!()` with a format string that ends in a single newline",
210 err.multipart_suggestion(
211 "use `println!` instead",
213 (mac.node.path.span, String::from("println")),
214 (fmt_str.newline_span(), String::new()),
216 Applicability::MachineApplicable,
222 } else if mac.node.path == sym!(write) {
223 if let (Some(fmt_str), _) = check_tts(cx, &mac.node.tts, true) {
224 if check_newlines(&fmt_str) {
229 "using `write!()` with a format string that ends in a single newline",
231 err.multipart_suggestion(
232 "use `writeln!()` instead",
234 (mac.node.path.span, String::from("writeln")),
235 (fmt_str.newline_span(), String::new()),
237 Applicability::MachineApplicable,
243 } else if mac.node.path == sym!(writeln) {
244 if let (Some(fmt_str), expr) = check_tts(cx, &mac.node.tts, true) {
245 if fmt_str.contents.is_empty() {
246 let mut applicability = Applicability::MachineApplicable;
247 let suggestion = expr.map_or_else(
249 applicability = Applicability::HasPlaceholders;
252 move |expr| snippet_with_applicability(cx, expr.span, "v", &mut applicability),
257 WRITELN_EMPTY_STRING,
259 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
261 format!("writeln!({})", suggestion),
270 /// The arguments of a `print[ln]!` or `write[ln]!` invocation.
272 /// The contents of the format string (inside the quotes).
275 /// The span of the format string, including quotes, the raw marker, and any raw hashes.
280 /// Given a format string that ends in a newline and its span, calculates the span of the
282 fn newline_span(&self) -> Span {
285 let newline_sp_hi = sp.hi()
287 StrStyle::Cooked => BytePos(1),
288 StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
291 let newline_sp_len = if self.contents.ends_with('\n') {
293 } else if self.contents.ends_with(r"\n") {
296 panic!("expected format string to contain a newline");
299 sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi)
303 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
304 /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
305 /// the contents of the string, whether it's a raw string, and the span of the literal in the
306 /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
307 /// `format_str` should be written to.
311 /// Calling this function on
313 /// # use std::fmt::Write;
314 /// # let mut buf = String::new();
315 /// # let something = "something";
316 /// writeln!(buf, "string to write: {}", something);
320 /// (Some("string to write: {}"), Some(buf))
322 fn check_tts<'a>(cx: &EarlyContext<'a>, tts: &TokenStream, is_write: bool) -> (Option<FmtStr>, Option<Expr>) {
324 let tts = tts.clone();
326 let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, None, false, false, None);
327 let mut expr: Option<Expr> = None;
329 expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
330 Ok(p) => Some(p.into_inner()),
331 Err(_) => return (None, None),
333 // might be `writeln!(foo)`
334 if parser.expect(&token::Comma).map_err(|mut err| err.cancel()).is_err() {
339 let (fmtstr, fmtstyle) = match parser.parse_str().map_err(|mut err| err.cancel()) {
340 Ok((fmtstr, fmtstyle)) => (fmtstr.to_string(), fmtstyle),
341 Err(_) => return (None, expr),
343 let fmtspan = parser.prev_span;
344 let tmp = fmtstr.clone();
345 let mut args = vec![];
346 let mut fmt_parser = Parser::new(&tmp, None, Vec::new(), false);
347 while let Some(piece) = fmt_parser.next() {
348 if !fmt_parser.errors.is_empty() {
351 if let Piece::NextArgument(arg) = piece {
352 if arg.format.ty == "?" {
353 // FIXME: modify rustc's fmt string parser to give us the current span
354 span_lint(cx, USE_DEBUG, parser.prev_span, "use of `Debug`-based formatting");
359 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
362 const SIMPLE: FormatSpec<'_> = FormatSpec {
366 precision: CountImplied,
370 if !parser.eat(&token::Comma) {
380 let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
392 match &token_expr.node {
393 ExprKind::Lit(_) => {
394 let mut all_simple = true;
395 let mut seen = false;
398 ArgumentImplicitlyIs(n) | ArgumentIs(n) => {
400 all_simple &= arg.format == SIMPLE;
404 ArgumentNamed(_) => {},
407 if all_simple && seen {
408 span_lint(cx, lint, token_expr.span, "literal with an empty format string");
412 ExprKind::Assign(lhs, rhs) => {
413 if let ExprKind::Lit(_) = rhs.node {
414 if let ExprKind::Path(_, p) = &lhs.node {
415 let mut all_simple = true;
416 let mut seen = false;
419 ArgumentImplicitlyIs(_) | ArgumentIs(_) => {},
420 ArgumentNamed(name) => {
421 if *p == Symbol::intern(name) {
423 all_simple &= arg.format == SIMPLE;
428 if all_simple && seen {
429 span_lint(cx, lint, rhs.span, "literal with an empty format string");
439 /// Checks if the format string constains a single newline that terminates it.
441 /// Literal and escaped newlines are both checked (only literal for raw strings).
442 fn check_newlines(fmt_str: &FmtStr) -> bool {
443 let s = &fmt_str.contents;
445 if s.ends_with('\n') {
447 } else if let StrStyle::Raw(_) = fmt_str.style {
455 let bytes = s.as_bytes();
456 if bytes[bytes.len() - 2] != b'\\' || bytes[bytes.len() - 1] != b'n' {
460 let mut escaping = false;
461 for (index, &byte) in bytes.iter().enumerate() {
464 return index == bytes.len() - 1;
467 } else if byte == b'\\' {