4 use crate::utils::{snippet_with_applicability, span_lint, span_lint_and_sugg, span_lint_and_then};
5 use if_chain::if_chain;
6 use rustc_ast::ast::{Expr, ExprKind, Item, ItemKind, LitKind, MacCall, StrLit, StrStyle};
8 use rustc_ast::tokenstream::TokenStream;
9 use rustc_errors::Applicability;
10 use rustc_lexer::unescape::{self, EscapeError};
11 use rustc_lint::{EarlyContext, EarlyLintPass};
12 use rustc_parse::parser;
13 use rustc_session::{declare_tool_lint, impl_lint_pass};
14 use rustc_span::symbol::kw;
15 use rustc_span::{sym, BytePos, Span};
17 declare_clippy_lint! {
18 /// **What it does:** This lint warns when you use `println!("")` to
21 /// **Why is this bad?** You should use `println!()`, which is simpler.
23 /// **Known problems:** None.
33 pub PRINTLN_EMPTY_STRING,
35 "using `println!(\"\")` with an empty string"
38 declare_clippy_lint! {
39 /// **What it does:** This lint warns when you use `print!()` with a format
40 /// string that ends in a newline.
42 /// **Why is this bad?** You should use `println!()` instead, which appends the
45 /// **Known problems:** None.
49 /// # let name = "World";
50 /// print!("Hello {}!\n", name);
52 /// use println!() instead
54 /// # let name = "World";
55 /// println!("Hello {}!", name);
57 pub PRINT_WITH_NEWLINE,
59 "using `print!()` with a format string that ends in a single newline"
62 declare_clippy_lint! {
63 /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
64 /// is to catch debugging remnants.
66 /// **Why is this bad?** People often print on *stdout* while debugging an
67 /// application and might forget to remove those prints afterward.
69 /// **Known problems:** Only catches `print!` and `println!` calls.
73 /// println!("Hello world!");
80 declare_clippy_lint! {
81 /// **What it does:** Checks for printing on *stderr*. The purpose of this lint
82 /// is to catch debugging remnants.
84 /// **Why is this bad?** People often print on *stderr* while debugging an
85 /// application and might forget to remove those prints afterward.
87 /// **Known problems:** Only catches `eprint!` and `eprintln!` calls.
91 /// eprintln!("Hello world!");
98 declare_clippy_lint! {
99 /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
100 /// lint is to catch debugging remnants.
102 /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
103 /// debugging Rust code. It should not be used in user-facing output.
107 /// # let foo = "bar";
108 /// println!("{:?}", foo);
112 "use of `Debug`-based formatting"
115 declare_clippy_lint! {
116 /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
118 /// **Why is this bad?** Using literals as `println!` args is inefficient
119 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
120 /// (i.e., just put the literal in the format string)
122 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
123 /// -- e.g., `println!("{}", env!("FOO"))`.
127 /// println!("{}", "foo");
129 /// use the literal without formatting:
135 "printing a literal with a format string"
138 declare_clippy_lint! {
139 /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
142 /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
144 /// **Known problems:** None.
148 /// # use std::fmt::Write;
149 /// # let mut buf = String::new();
152 /// writeln!(buf, "");
157 pub WRITELN_EMPTY_STRING,
159 "using `writeln!(buf, \"\")` with an empty string"
162 declare_clippy_lint! {
163 /// **What it does:** This lint warns when you use `write!()` with a format
165 /// ends in a newline.
167 /// **Why is this bad?** You should use `writeln!()` instead, which appends the
170 /// **Known problems:** None.
174 /// # use std::fmt::Write;
175 /// # let mut buf = String::new();
176 /// # let name = "World";
179 /// write!(buf, "Hello {}!\n", name);
182 /// writeln!(buf, "Hello {}!", name);
184 pub WRITE_WITH_NEWLINE,
186 "using `write!()` with a format string that ends in a single newline"
189 declare_clippy_lint! {
190 /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
192 /// **Why is this bad?** Using literals as `writeln!` args is inefficient
193 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
194 /// (i.e., just put the literal in the format string)
196 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
197 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
201 /// # use std::fmt::Write;
202 /// # let mut buf = String::new();
205 /// writeln!(buf, "{}", "foo");
208 /// writeln!(buf, "foo");
212 "writing a literal with a format string"
220 impl_lint_pass!(Write => [
222 PRINTLN_EMPTY_STRING,
228 WRITELN_EMPTY_STRING,
232 impl EarlyLintPass for Write {
233 fn check_item(&mut self, _: &EarlyContext<'_>, item: &Item) {
234 if let ItemKind::Impl {
235 of_trait: Some(trait_ref),
239 let trait_name = trait_ref
244 .expect("path has at least one segment")
247 if trait_name == sym::Debug {
248 self.in_debug_impl = true;
253 fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &Item) {
254 self.in_debug_impl = false;
257 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &MacCall) {
258 fn is_build_script(cx: &EarlyContext<'_>) -> bool {
259 // Cargo sets the crate name for build scripts to `build_script_build`
264 .map_or(false, |crate_name| crate_name == "build_script_build")
267 if mac.path == sym!(print) {
268 if !is_build_script(cx) {
269 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`");
271 self.lint_print_with_newline(cx, mac);
272 } else if mac.path == sym!(println) {
273 if !is_build_script(cx) {
274 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`");
276 self.lint_println_empty_string(cx, mac);
277 } else if mac.path == sym!(eprint) {
278 span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprint!`");
279 self.lint_print_with_newline(cx, mac);
280 } else if mac.path == sym!(eprintln) {
281 span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprintln!`");
282 self.lint_println_empty_string(cx, mac);
283 } else if mac.path == sym!(write) {
284 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), true) {
285 if check_newlines(&fmt_str) {
290 "using `write!()` with a format string that ends in a single newline",
292 err.multipart_suggestion(
293 "use `writeln!()` instead",
295 (mac.path.span, String::from("writeln")),
296 (newline_span(&fmt_str), String::new()),
298 Applicability::MachineApplicable,
304 } else if mac.path == sym!(writeln) {
305 if let (Some(fmt_str), expr) = self.check_tts(cx, mac.args.inner_tokens(), true) {
306 if fmt_str.symbol == kw::Empty {
307 let mut applicability = Applicability::MachineApplicable;
308 // FIXME: remove this `#[allow(...)]` once the issue #5822 gets fixed
309 #[allow(clippy::option_if_let_else)]
310 let suggestion = if let Some(e) = expr {
311 snippet_with_applicability(cx, e.span, "v", &mut applicability)
313 applicability = Applicability::HasPlaceholders;
319 WRITELN_EMPTY_STRING,
321 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
323 format!("writeln!({})", suggestion),
332 /// Given a format string that ends in a newline and its span, calculates the span of the
333 /// newline, or the format string itself if the format string consists solely of a newline.
334 fn newline_span(fmtstr: &StrLit) -> Span {
335 let sp = fmtstr.span;
336 let contents = &fmtstr.symbol.as_str();
338 if *contents == r"\n" {
342 let newline_sp_hi = sp.hi()
343 - match fmtstr.style {
344 StrStyle::Cooked => BytePos(1),
345 StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
348 let newline_sp_len = if contents.ends_with('\n') {
350 } else if contents.ends_with(r"\n") {
353 panic!("expected format string to contain a newline");
356 sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi)
360 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
361 /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
362 /// the contents of the string, whether it's a raw string, and the span of the literal in the
363 /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
364 /// `format_str` should be written to.
368 /// Calling this function on
370 /// # use std::fmt::Write;
371 /// # let mut buf = String::new();
372 /// # let something = "something";
373 /// writeln!(buf, "string to write: {}", something);
377 /// (Some("string to write: {}"), Some(buf))
379 #[allow(clippy::too_many_lines)]
380 fn check_tts<'a>(&self, cx: &EarlyContext<'a>, tts: TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
381 use rustc_parse_format::{
382 AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied, FormatSpec, ParseMode, Parser,
386 let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, false, None);
387 let mut expr: Option<Expr> = None;
389 expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
390 Ok(p) => Some(p.into_inner()),
391 Err(_) => return (None, None),
393 // might be `writeln!(foo)`
394 if parser.expect(&token::Comma).map_err(|mut err| err.cancel()).is_err() {
399 let fmtstr = match parser.parse_str_lit() {
400 Ok(fmtstr) => fmtstr,
401 Err(_) => return (None, expr),
403 let tmp = fmtstr.symbol.as_str();
404 let mut args = vec![];
405 let mut fmt_parser = Parser::new(&tmp, None, None, false, ParseMode::Format);
406 while let Some(piece) = fmt_parser.next() {
407 if !fmt_parser.errors.is_empty() {
410 if let Piece::NextArgument(arg) = piece {
411 if !self.in_debug_impl && arg.format.ty == "?" {
412 // FIXME: modify rustc's fmt string parser to give us the current span
413 span_lint(cx, USE_DEBUG, parser.prev_token.span, "use of `Debug`-based formatting");
418 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
421 const SIMPLE: FormatSpec<'_> = FormatSpec {
425 precision: CountImplied,
426 precision_span: None,
432 if !parser.eat(&token::Comma) {
433 return (Some(fmtstr), expr);
435 let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
438 return (Some(fmtstr), None);
440 match &token_expr.kind {
441 ExprKind::Lit(lit) if !matches!(lit.kind, LitKind::Int(..) | LitKind::Float(..)) => {
442 let mut all_simple = true;
443 let mut seen = false;
446 ArgumentImplicitlyIs(n) | ArgumentIs(n) => {
448 all_simple &= arg.format == SIMPLE;
452 ArgumentNamed(_) => {},
455 if all_simple && seen {
456 span_lint(cx, lint, token_expr.span, "literal with an empty format string");
460 ExprKind::Assign(lhs, rhs, _) => {
462 if let ExprKind::Lit(ref lit) = rhs.kind;
463 if !matches!(lit.kind, LitKind::Int(..) | LitKind::Float(..));
464 if let ExprKind::Path(_, p) = &lhs.kind;
466 let mut all_simple = true;
467 let mut seen = false;
470 ArgumentImplicitlyIs(_) | ArgumentIs(_) => {},
471 ArgumentNamed(name) => {
474 all_simple &= arg.format == SIMPLE;
479 if all_simple && seen {
480 span_lint(cx, lint, rhs.span, "literal with an empty format string");
490 fn lint_println_empty_string(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
491 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
492 if fmt_str.symbol == kw::Empty {
493 let name = mac.path.segments[0].ident.name;
496 PRINTLN_EMPTY_STRING,
498 &format!("using `{}!(\"\")`", name),
500 format!("{}!()", name),
501 Applicability::MachineApplicable,
507 fn lint_print_with_newline(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
508 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
509 if check_newlines(&fmt_str) {
510 let name = mac.path.segments[0].ident.name;
511 let suggested = format!("{}ln", name);
516 &format!("using `{}!()` with a format string that ends in a single newline", name),
518 err.multipart_suggestion(
519 &format!("use `{}!` instead", suggested),
520 vec![(mac.path.span, suggested), (newline_span(&fmt_str), String::new())],
521 Applicability::MachineApplicable,
530 /// Checks if the format string contains a single newline that terminates it.
532 /// Literal and escaped newlines are both checked (only literal for raw strings).
533 fn check_newlines(fmtstr: &StrLit) -> bool {
534 let mut has_internal_newline = false;
535 let mut last_was_cr = false;
536 let mut should_lint = false;
538 let contents = &fmtstr.symbol.as_str();
540 let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
543 if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
546 last_was_cr = c == '\r';
548 has_internal_newline = true;
554 StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb),
555 StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb),