4 use crate::utils::{snippet_with_applicability, span_lint, span_lint_and_sugg, span_lint_and_then};
5 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
6 use rustc::{declare_lint_pass, declare_tool_lint};
7 use rustc_errors::Applicability;
8 use rustc_lexer::unescape::{self, EscapeError};
9 use rustc_parse::parser;
11 use syntax::symbol::Symbol;
13 use syntax::tokenstream::TokenStream;
14 use syntax_pos::{BytePos, Span};
16 declare_clippy_lint! {
17 /// **What it does:** This lint warns when you use `println!("")` to
20 /// **Why is this bad?** You should use `println!()`, which is simpler.
22 /// **Known problems:** None.
28 pub PRINTLN_EMPTY_STRING,
30 "using `println!(\"\")` with an empty string"
33 declare_clippy_lint! {
34 /// **What it does:** This lint warns when you use `print!()` with a format
36 /// ends in a newline.
38 /// **Why is this bad?** You should use `println!()` instead, which appends the
41 /// **Known problems:** None.
45 /// # let name = "World";
46 /// print!("Hello {}!\n", name);
48 /// use println!() instead
50 /// # let name = "World";
51 /// println!("Hello {}!", name);
53 pub PRINT_WITH_NEWLINE,
55 "using `print!()` with a format string that ends in a single newline"
58 declare_clippy_lint! {
59 /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
60 /// is to catch debugging remnants.
62 /// **Why is this bad?** People often print on *stdout* while debugging an
63 /// application and might forget to remove those prints afterward.
65 /// **Known problems:** Only catches `print!` and `println!` calls.
69 /// println!("Hello world!");
76 declare_clippy_lint! {
77 /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
78 /// lint is to catch debugging remnants.
80 /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
81 /// debugging Rust code. It should not be used in user-facing output.
85 /// # let foo = "bar";
86 /// println!("{:?}", foo);
90 "use of `Debug`-based formatting"
93 declare_clippy_lint! {
94 /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
96 /// **Why is this bad?** Using literals as `println!` args is inefficient
97 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
98 /// (i.e., just put the literal in the format string)
100 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
101 /// -- e.g., `println!("{}", env!("FOO"))`.
105 /// println!("{}", "foo");
107 /// use the literal without formatting:
113 "printing a literal with a format string"
116 declare_clippy_lint! {
117 /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
120 /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
122 /// **Known problems:** None.
126 /// # use std::fmt::Write;
127 /// # let mut buf = String::new();
128 /// writeln!(buf, "");
130 pub WRITELN_EMPTY_STRING,
132 "using `writeln!(buf, \"\")` with an empty string"
135 declare_clippy_lint! {
136 /// **What it does:** This lint warns when you use `write!()` with a format
138 /// ends in a newline.
140 /// **Why is this bad?** You should use `writeln!()` instead, which appends the
143 /// **Known problems:** None.
147 /// # use std::fmt::Write;
148 /// # let mut buf = String::new();
149 /// # let name = "World";
150 /// write!(buf, "Hello {}!\n", name);
152 pub WRITE_WITH_NEWLINE,
154 "using `write!()` with a format string that ends in a single newline"
157 declare_clippy_lint! {
158 /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
160 /// **Why is this bad?** Using literals as `writeln!` args is inefficient
161 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
162 /// (i.e., just put the literal in the format string)
164 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
165 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
169 /// # use std::fmt::Write;
170 /// # let mut buf = String::new();
171 /// writeln!(buf, "{}", "foo");
175 "writing a literal with a format string"
178 declare_lint_pass!(Write => [
180 PRINTLN_EMPTY_STRING,
185 WRITELN_EMPTY_STRING,
189 impl EarlyLintPass for Write {
190 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &Mac) {
191 if mac.path == sym!(println) {
192 span_lint(cx, PRINT_STDOUT, mac.span, "use of `println!`");
193 if let (Some(fmt_str), _) = check_tts(cx, &mac.tts, false) {
194 if fmt_str.symbol == Symbol::intern("") {
197 PRINTLN_EMPTY_STRING,
199 "using `println!(\"\")`",
201 "println!()".to_string(),
202 Applicability::MachineApplicable,
206 } else if mac.path == sym!(print) {
207 span_lint(cx, PRINT_STDOUT, mac.span, "use of `print!`");
208 if let (Some(fmt_str), _) = check_tts(cx, &mac.tts, false) {
209 if check_newlines(&fmt_str) {
214 "using `print!()` with a format string that ends in a single newline",
216 err.multipart_suggestion(
217 "use `println!` instead",
219 (mac.path.span, String::from("println")),
220 (newline_span(&fmt_str), String::new()),
222 Applicability::MachineApplicable,
228 } else if mac.path == sym!(write) {
229 if let (Some(fmt_str), _) = check_tts(cx, &mac.tts, true) {
230 if check_newlines(&fmt_str) {
235 "using `write!()` with a format string that ends in a single newline",
237 err.multipart_suggestion(
238 "use `writeln!()` instead",
240 (mac.path.span, String::from("writeln")),
241 (newline_span(&fmt_str), String::new()),
243 Applicability::MachineApplicable,
249 } else if mac.path == sym!(writeln) {
250 if let (Some(fmt_str), expr) = check_tts(cx, &mac.tts, true) {
251 if fmt_str.symbol == Symbol::intern("") {
252 let mut applicability = Applicability::MachineApplicable;
253 let suggestion = expr.map_or_else(
255 applicability = Applicability::HasPlaceholders;
258 move |expr| snippet_with_applicability(cx, expr.span, "v", &mut applicability),
263 WRITELN_EMPTY_STRING,
265 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
267 format!("writeln!({})", suggestion),
276 /// Given a format string that ends in a newline and its span, calculates the span of the
278 fn newline_span(fmtstr: &StrLit) -> Span {
279 let sp = fmtstr.span;
280 let contents = &fmtstr.symbol.as_str();
282 let newline_sp_hi = sp.hi()
283 - match fmtstr.style {
284 StrStyle::Cooked => BytePos(1),
285 StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
288 let newline_sp_len = if contents.ends_with('\n') {
290 } else if contents.ends_with(r"\n") {
293 panic!("expected format string to contain a newline");
296 sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi)
299 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
300 /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
301 /// the contents of the string, whether it's a raw string, and the span of the literal in the
302 /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
303 /// `format_str` should be written to.
307 /// Calling this function on
309 /// # use std::fmt::Write;
310 /// # let mut buf = String::new();
311 /// # let something = "something";
312 /// writeln!(buf, "string to write: {}", something);
316 /// (Some("string to write: {}"), Some(buf))
318 #[allow(clippy::too_many_lines)]
319 fn check_tts<'a>(cx: &EarlyContext<'a>, tts: &TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
321 let tts = tts.clone();
323 let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, None, false, false, None);
324 let mut expr: Option<Expr> = None;
326 expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
327 Ok(p) => Some(p.into_inner()),
328 Err(_) => return (None, None),
330 // might be `writeln!(foo)`
331 if parser.expect(&token::Comma).map_err(|mut err| err.cancel()).is_err() {
336 let fmtstr = match parser.parse_str_lit() {
337 Ok(fmtstr) => fmtstr,
338 Err(_) => return (None, expr),
340 let tmp = fmtstr.symbol.as_str();
341 let mut args = vec![];
342 let mut fmt_parser = Parser::new(&tmp, None, Vec::new(), false);
343 while let Some(piece) = fmt_parser.next() {
344 if !fmt_parser.errors.is_empty() {
347 if let Piece::NextArgument(arg) = piece {
348 if arg.format.ty == "?" {
349 // FIXME: modify rustc's fmt string parser to give us the current span
350 span_lint(cx, USE_DEBUG, parser.prev_span, "use of `Debug`-based formatting");
355 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
358 const SIMPLE: FormatSpec<'_> = FormatSpec {
362 precision: CountImplied,
363 precision_span: None,
369 if !parser.eat(&token::Comma) {
370 return (Some(fmtstr), expr);
372 let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
375 return (Some(fmtstr), None);
377 match &token_expr.kind {
378 ExprKind::Lit(_) => {
379 let mut all_simple = true;
380 let mut seen = false;
383 ArgumentImplicitlyIs(n) | ArgumentIs(n) => {
385 all_simple &= arg.format == SIMPLE;
389 ArgumentNamed(_) => {},
392 if all_simple && seen {
393 span_lint(cx, lint, token_expr.span, "literal with an empty format string");
397 ExprKind::Assign(lhs, rhs) => {
398 if let ExprKind::Lit(_) = rhs.kind {
399 if let ExprKind::Path(_, p) = &lhs.kind {
400 let mut all_simple = true;
401 let mut seen = false;
404 ArgumentImplicitlyIs(_) | ArgumentIs(_) => {},
405 ArgumentNamed(name) => {
408 all_simple &= arg.format == SIMPLE;
413 if all_simple && seen {
414 span_lint(cx, lint, rhs.span, "literal with an empty format string");
424 /// Checks if the format string contains a single newline that terminates it.
426 /// Literal and escaped newlines are both checked (only literal for raw strings).
427 fn check_newlines(fmtstr: &StrLit) -> bool {
428 let mut has_internal_newline = false;
429 let mut last_was_cr = false;
430 let mut should_lint = false;
432 let contents = &fmtstr.symbol.as_str();
434 let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
437 if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
440 last_was_cr = c == '\r';
442 has_internal_newline = true;
448 StrStyle::Cooked => unescape::unescape_str(contents, &mut cb),
449 StrStyle::Raw(_) => unescape::unescape_raw_str(contents, &mut cb),