4 use crate::utils::{snippet_with_applicability, span_lint, span_lint_and_sugg, span_lint_and_then};
5 use if_chain::if_chain;
7 Expr, ExprKind, ImplKind, Item, ItemKind, LitKind, MacCall, StrLit, StrStyle,
10 use rustc_ast::tokenstream::TokenStream;
11 use rustc_errors::Applicability;
12 use rustc_lexer::unescape::{self, EscapeError};
13 use rustc_lint::{EarlyContext, EarlyLintPass};
14 use rustc_parse::parser;
15 use rustc_session::{declare_tool_lint, impl_lint_pass};
16 use rustc_span::symbol::kw;
17 use rustc_span::{sym, BytePos, Span};
19 declare_clippy_lint! {
20 /// **What it does:** This lint warns when you use `println!("")` to
23 /// **Why is this bad?** You should use `println!()`, which is simpler.
25 /// **Known problems:** None.
35 pub PRINTLN_EMPTY_STRING,
37 "using `println!(\"\")` with an empty string"
40 declare_clippy_lint! {
41 /// **What it does:** This lint warns when you use `print!()` with a format
42 /// string that ends in a newline.
44 /// **Why is this bad?** You should use `println!()` instead, which appends the
47 /// **Known problems:** None.
51 /// # let name = "World";
52 /// print!("Hello {}!\n", name);
54 /// use println!() instead
56 /// # let name = "World";
57 /// println!("Hello {}!", name);
59 pub PRINT_WITH_NEWLINE,
61 "using `print!()` with a format string that ends in a single newline"
64 declare_clippy_lint! {
65 /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
66 /// is to catch debugging remnants.
68 /// **Why is this bad?** People often print on *stdout* while debugging an
69 /// application and might forget to remove those prints afterward.
71 /// **Known problems:** Only catches `print!` and `println!` calls.
75 /// println!("Hello world!");
82 declare_clippy_lint! {
83 /// **What it does:** Checks for printing on *stderr*. The purpose of this lint
84 /// is to catch debugging remnants.
86 /// **Why is this bad?** People often print on *stderr* while debugging an
87 /// application and might forget to remove those prints afterward.
89 /// **Known problems:** Only catches `eprint!` and `eprintln!` calls.
93 /// eprintln!("Hello world!");
100 declare_clippy_lint! {
101 /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
102 /// lint is to catch debugging remnants.
104 /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
105 /// debugging Rust code. It should not be used in user-facing output.
109 /// # let foo = "bar";
110 /// println!("{:?}", foo);
114 "use of `Debug`-based formatting"
117 declare_clippy_lint! {
118 /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
120 /// **Why is this bad?** Using literals as `println!` args is inefficient
121 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
122 /// (i.e., just put the literal in the format string)
124 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
125 /// -- e.g., `println!("{}", env!("FOO"))`.
129 /// println!("{}", "foo");
131 /// use the literal without formatting:
137 "printing a literal with a format string"
140 declare_clippy_lint! {
141 /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
144 /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
146 /// **Known problems:** None.
150 /// # use std::fmt::Write;
151 /// # let mut buf = String::new();
154 /// writeln!(buf, "");
159 pub WRITELN_EMPTY_STRING,
161 "using `writeln!(buf, \"\")` with an empty string"
164 declare_clippy_lint! {
165 /// **What it does:** This lint warns when you use `write!()` with a format
167 /// ends in a newline.
169 /// **Why is this bad?** You should use `writeln!()` instead, which appends the
172 /// **Known problems:** None.
176 /// # use std::fmt::Write;
177 /// # let mut buf = String::new();
178 /// # let name = "World";
181 /// write!(buf, "Hello {}!\n", name);
184 /// writeln!(buf, "Hello {}!", name);
186 pub WRITE_WITH_NEWLINE,
188 "using `write!()` with a format string that ends in a single newline"
191 declare_clippy_lint! {
192 /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
194 /// **Why is this bad?** Using literals as `writeln!` args is inefficient
195 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
196 /// (i.e., just put the literal in the format string)
198 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
199 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
203 /// # use std::fmt::Write;
204 /// # let mut buf = String::new();
207 /// writeln!(buf, "{}", "foo");
210 /// writeln!(buf, "foo");
214 "writing a literal with a format string"
222 impl_lint_pass!(Write => [
224 PRINTLN_EMPTY_STRING,
230 WRITELN_EMPTY_STRING,
234 impl EarlyLintPass for Write {
235 fn check_item(&mut self, _: &EarlyContext<'_>, item: &Item) {
236 if let ItemKind::Impl(box ImplKind {
237 of_trait: Some(trait_ref),
241 let trait_name = trait_ref
246 .expect("path has at least one segment")
249 if trait_name == sym::Debug {
250 self.in_debug_impl = true;
255 fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &Item) {
256 self.in_debug_impl = false;
259 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &MacCall) {
260 fn is_build_script(cx: &EarlyContext<'_>) -> bool {
261 // Cargo sets the crate name for build scripts to `build_script_build`
266 .map_or(false, |crate_name| crate_name == "build_script_build")
269 if mac.path == sym!(print) {
270 if !is_build_script(cx) {
271 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`");
273 self.lint_print_with_newline(cx, mac);
274 } else if mac.path == sym!(println) {
275 if !is_build_script(cx) {
276 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`");
278 self.lint_println_empty_string(cx, mac);
279 } else if mac.path == sym!(eprint) {
280 span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprint!`");
281 self.lint_print_with_newline(cx, mac);
282 } else if mac.path == sym!(eprintln) {
283 span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprintln!`");
284 self.lint_println_empty_string(cx, mac);
285 } else if mac.path == sym!(write) {
286 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), true) {
287 if check_newlines(&fmt_str) {
292 "using `write!()` with a format string that ends in a single newline",
294 err.multipart_suggestion(
295 "use `writeln!()` instead",
297 (mac.path.span, String::from("writeln")),
298 (newline_span(&fmt_str), String::new()),
300 Applicability::MachineApplicable,
306 } else if mac.path == sym!(writeln) {
307 if let (Some(fmt_str), expr) = self.check_tts(cx, mac.args.inner_tokens(), true) {
308 if fmt_str.symbol == kw::Empty {
309 let mut applicability = Applicability::MachineApplicable;
310 // FIXME: remove this `#[allow(...)]` once the issue #5822 gets fixed
311 #[allow(clippy::option_if_let_else)]
312 let suggestion = if let Some(e) = expr {
313 snippet_with_applicability(cx, e.span, "v", &mut applicability)
315 applicability = Applicability::HasPlaceholders;
321 WRITELN_EMPTY_STRING,
323 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
325 format!("writeln!({})", suggestion),
334 /// Given a format string that ends in a newline and its span, calculates the span of the
335 /// newline, or the format string itself if the format string consists solely of a newline.
336 fn newline_span(fmtstr: &StrLit) -> Span {
337 let sp = fmtstr.span;
338 let contents = &fmtstr.symbol.as_str();
340 if *contents == r"\n" {
344 let newline_sp_hi = sp.hi()
345 - match fmtstr.style {
346 StrStyle::Cooked => BytePos(1),
347 StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
350 let newline_sp_len = if contents.ends_with('\n') {
352 } else if contents.ends_with(r"\n") {
355 panic!("expected format string to contain a newline");
358 sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi)
362 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
363 /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
364 /// the contents of the string, whether it's a raw string, and the span of the literal in the
365 /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
366 /// `format_str` should be written to.
370 /// Calling this function on
372 /// # use std::fmt::Write;
373 /// # let mut buf = String::new();
374 /// # let something = "something";
375 /// writeln!(buf, "string to write: {}", something);
379 /// (Some("string to write: {}"), Some(buf))
381 #[allow(clippy::too_many_lines)]
384 cx: &EarlyContext<'a>,
387 ) -> (Option<StrLit>, Option<Expr>) {
388 use rustc_parse_format::{
389 AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied,
390 FormatSpec, ParseMode, Parser, Piece,
393 let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, false, None);
394 let mut expr: Option<Expr> = None;
396 expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
397 Ok(p) => Some(p.into_inner()),
398 Err(_) => return (None, None),
400 // might be `writeln!(foo)`
401 if parser.expect(&token::Comma).map_err(|mut err| err.cancel()).is_err() {
406 let fmtstr = match parser.parse_str_lit() {
407 Ok(fmtstr) => fmtstr,
408 Err(_) => return (None, expr),
410 let tmp = fmtstr.symbol.as_str();
411 let mut args = vec![];
412 let mut fmt_parser = Parser::new(&tmp, None, None, false, ParseMode::Format);
413 while let Some(piece) = fmt_parser.next() {
414 if !fmt_parser.errors.is_empty() {
417 if let Piece::NextArgument(arg) = piece {
418 if !self.in_debug_impl && arg.format.ty == "?" {
419 // FIXME: modify rustc's fmt string parser to give us the current span
423 parser.prev_token.span,
424 "use of `Debug`-based formatting",
430 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
433 const SIMPLE: FormatSpec<'_> = FormatSpec {
437 precision: CountImplied,
438 precision_span: None,
444 if !parser.eat(&token::Comma) {
445 return (Some(fmtstr), expr);
447 let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
450 return (Some(fmtstr), None);
452 match &token_expr.kind {
454 if !matches!(lit.kind, LitKind::Int(..) | LitKind::Float(..)) =>
456 let mut all_simple = true;
457 let mut seen = false;
460 ArgumentImplicitlyIs(n) | ArgumentIs(n) => {
462 all_simple &= arg.format == SIMPLE;
466 ArgumentNamed(_) => {}
469 if all_simple && seen {
470 span_lint(cx, lint, token_expr.span, "literal with an empty format string");
474 ExprKind::Assign(lhs, rhs, _) => {
476 if let ExprKind::Lit(ref lit) = rhs.kind;
477 if !matches!(lit.kind, LitKind::Int(..) | LitKind::Float(..));
478 if let ExprKind::Path(_, p) = &lhs.kind;
480 let mut all_simple = true;
481 let mut seen = false;
484 ArgumentImplicitlyIs(_) | ArgumentIs(_) => {},
485 ArgumentNamed(name) => {
488 all_simple &= arg.format == SIMPLE;
493 if all_simple && seen {
494 span_lint(cx, lint, rhs.span, "literal with an empty format string");
504 fn lint_println_empty_string(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
505 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
506 if fmt_str.symbol == kw::Empty {
507 let name = mac.path.segments[0].ident.name;
510 PRINTLN_EMPTY_STRING,
512 &format!("using `{}!(\"\")`", name),
514 format!("{}!()", name),
515 Applicability::MachineApplicable,
521 fn lint_print_with_newline(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
522 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
523 if check_newlines(&fmt_str) {
524 let name = mac.path.segments[0].ident.name;
525 let suggested = format!("{}ln", name);
531 "using `{}!()` with a format string that ends in a single newline",
535 err.multipart_suggestion(
536 &format!("use `{}!` instead", suggested),
538 (mac.path.span, suggested),
539 (newline_span(&fmt_str), String::new()),
541 Applicability::MachineApplicable,
550 /// Checks if the format string contains a single newline that terminates it.
552 /// Literal and escaped newlines are both checked (only literal for raw strings).
553 fn check_newlines(fmtstr: &StrLit) -> bool {
554 let mut has_internal_newline = false;
555 let mut last_was_cr = false;
556 let mut should_lint = false;
558 let contents = &fmtstr.symbol.as_str();
560 let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
563 if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
566 last_was_cr = c == '\r';
568 has_internal_newline = true;
574 StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb),
575 StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb),