3 use std::ops::{Deref, Range};
5 use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then};
6 use clippy_utils::source::{snippet_opt, snippet_with_applicability};
7 use rustc_ast::ast::{Expr, ExprKind, ImplKind, Item, ItemKind, MacCall, Path, StrLit, StrStyle};
8 use rustc_ast::token::{self, LitKind};
9 use rustc_ast::tokenstream::TokenStream;
10 use rustc_errors::Applicability;
11 use rustc_lexer::unescape::{self, EscapeError};
12 use rustc_lint::{EarlyContext, EarlyLintPass};
13 use rustc_parse::parser;
14 use rustc_session::{declare_tool_lint, impl_lint_pass};
15 use rustc_span::symbol::{kw, Symbol};
16 use rustc_span::{sym, BytePos, Span, DUMMY_SP};
18 declare_clippy_lint! {
20 /// This lint warns when you use `println!("")` to
23 /// ### Why is this bad?
24 /// You should use `println!()`, which is simpler.
34 pub PRINTLN_EMPTY_STRING,
36 "using `println!(\"\")` with an empty string"
39 declare_clippy_lint! {
41 /// This lint warns when you use `print!()` with a format
42 /// string that ends in a newline.
44 /// ### Why is this bad?
45 /// You should use `println!()` instead, which appends the
50 /// # let name = "World";
51 /// print!("Hello {}!\n", name);
53 /// use println!() instead
55 /// # let name = "World";
56 /// println!("Hello {}!", name);
58 pub PRINT_WITH_NEWLINE,
60 "using `print!()` with a format string that ends in a single newline"
63 declare_clippy_lint! {
65 /// Checks for printing on *stdout*. The purpose of this lint
66 /// is to catch debugging remnants.
68 /// ### Why is this bad?
69 /// People often print on *stdout* while debugging an
70 /// application and might forget to remove those prints afterward.
72 /// ### Known problems
73 /// Only catches `print!` and `println!` calls.
77 /// println!("Hello world!");
84 declare_clippy_lint! {
86 /// Checks for printing on *stderr*. The purpose of this lint
87 /// is to catch debugging remnants.
89 /// ### Why is this bad?
90 /// People often print on *stderr* while debugging an
91 /// application and might forget to remove those prints afterward.
93 /// ### Known problems
94 /// Only catches `eprint!` and `eprintln!` calls.
98 /// eprintln!("Hello world!");
105 declare_clippy_lint! {
107 /// Checks for use of `Debug` formatting. The purpose of this
108 /// lint is to catch debugging remnants.
110 /// ### Why is this bad?
111 /// The purpose of the `Debug` trait is to facilitate
112 /// debugging Rust code. It should not be used in user-facing output.
116 /// # let foo = "bar";
117 /// println!("{:?}", foo);
121 "use of `Debug`-based formatting"
124 declare_clippy_lint! {
126 /// This lint warns about the use of literals as `print!`/`println!` args.
128 /// ### Why is this bad?
129 /// Using literals as `println!` args is inefficient
130 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
131 /// (i.e., just put the literal in the format string)
133 /// ### Known problems
134 /// Will also warn with macro calls as arguments that expand to literals
135 /// -- e.g., `println!("{}", env!("FOO"))`.
139 /// println!("{}", "foo");
141 /// use the literal without formatting:
147 "printing a literal with a format string"
150 declare_clippy_lint! {
152 /// This lint warns when you use `writeln!(buf, "")` to
155 /// ### Why is this bad?
156 /// You should use `writeln!(buf)`, which is simpler.
160 /// # use std::fmt::Write;
161 /// # let mut buf = String::new();
163 /// writeln!(buf, "");
168 pub WRITELN_EMPTY_STRING,
170 "using `writeln!(buf, \"\")` with an empty string"
173 declare_clippy_lint! {
175 /// This lint warns when you use `write!()` with a format
177 /// ends in a newline.
179 /// ### Why is this bad?
180 /// You should use `writeln!()` instead, which appends the
185 /// # use std::fmt::Write;
186 /// # let mut buf = String::new();
187 /// # let name = "World";
189 /// write!(buf, "Hello {}!\n", name);
192 /// writeln!(buf, "Hello {}!", name);
194 pub WRITE_WITH_NEWLINE,
196 "using `write!()` with a format string that ends in a single newline"
199 declare_clippy_lint! {
201 /// This lint warns about the use of literals as `write!`/`writeln!` args.
203 /// ### Why is this bad?
204 /// Using literals as `writeln!` args is inefficient
205 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
206 /// (i.e., just put the literal in the format string)
208 /// ### Known problems
209 /// Will also warn with macro calls as arguments that expand to literals
210 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
214 /// # use std::fmt::Write;
215 /// # let mut buf = String::new();
217 /// writeln!(buf, "{}", "foo");
220 /// writeln!(buf, "foo");
224 "writing a literal with a format string"
232 impl_lint_pass!(Write => [
234 PRINTLN_EMPTY_STRING,
240 WRITELN_EMPTY_STRING,
244 impl EarlyLintPass for Write {
245 fn check_item(&mut self, _: &EarlyContext<'_>, item: &Item) {
246 if let ItemKind::Impl(box ImplKind {
247 of_trait: Some(trait_ref),
251 let trait_name = trait_ref
256 .expect("path has at least one segment")
259 if trait_name == sym::Debug {
260 self.in_debug_impl = true;
265 fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &Item) {
266 self.in_debug_impl = false;
269 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &MacCall) {
270 fn is_build_script(cx: &EarlyContext<'_>) -> bool {
271 // Cargo sets the crate name for build scripts to `build_script_build`
276 .map_or(false, |crate_name| crate_name == "build_script_build")
279 if mac.path == sym!(print) {
280 if !is_build_script(cx) {
281 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`");
283 self.lint_print_with_newline(cx, mac);
284 } else if mac.path == sym!(println) {
285 if !is_build_script(cx) {
286 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`");
288 self.lint_println_empty_string(cx, mac);
289 } else if mac.path == sym!(eprint) {
290 span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprint!`");
291 self.lint_print_with_newline(cx, mac);
292 } else if mac.path == sym!(eprintln) {
293 span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprintln!`");
294 self.lint_println_empty_string(cx, mac);
295 } else if mac.path == sym!(write) {
296 if let (Some(fmt_str), dest) = self.check_tts(cx, mac.args.inner_tokens(), true) {
297 if check_newlines(&fmt_str) {
298 let (nl_span, only_nl) = newline_span(&fmt_str);
299 let nl_span = match (dest, only_nl) {
300 // Special case of `write!(buf, "\n")`: Mark everything from the end of
301 // `buf` for removal so no trailing comma [`writeln!(buf, )`] remains.
302 (Some(dest_expr), true) => nl_span.with_lo(dest_expr.span.hi()),
309 "using `write!()` with a format string that ends in a single newline",
311 err.multipart_suggestion(
312 "use `writeln!()` instead",
313 vec![(mac.path.span, String::from("writeln")), (nl_span, String::new())],
314 Applicability::MachineApplicable,
320 } else if mac.path == sym!(writeln) {
321 if let (Some(fmt_str), expr) = self.check_tts(cx, mac.args.inner_tokens(), true) {
322 if fmt_str.symbol == kw::Empty {
323 let mut applicability = Applicability::MachineApplicable;
324 // FIXME: remove this `#[allow(...)]` once the issue #5822 gets fixed
325 #[allow(clippy::option_if_let_else)]
326 let suggestion = if let Some(e) = expr {
327 snippet_with_applicability(cx, e.span, "v", &mut applicability)
329 applicability = Applicability::HasPlaceholders;
335 WRITELN_EMPTY_STRING,
337 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
339 format!("writeln!({})", suggestion),
348 /// Given a format string that ends in a newline and its span, calculates the span of the
349 /// newline, or the format string itself if the format string consists solely of a newline.
350 /// Return this and a boolean indicating whether it only consisted of a newline.
351 fn newline_span(fmtstr: &StrLit) -> (Span, bool) {
352 let sp = fmtstr.span;
353 let contents = &fmtstr.symbol.as_str();
355 if *contents == r"\n" {
359 let newline_sp_hi = sp.hi()
360 - match fmtstr.style {
361 StrStyle::Cooked => BytePos(1),
362 StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
365 let newline_sp_len = if contents.ends_with('\n') {
367 } else if contents.ends_with(r"\n") {
370 panic!("expected format string to contain a newline");
373 (sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi), false)
376 /// Stores a list of replacement spans for each argument, but only if all the replacements used an
377 /// empty format string.
379 struct SimpleFormatArgs {
380 unnamed: Vec<Vec<Span>>,
381 named: Vec<(Symbol, Vec<Span>)>,
383 impl SimpleFormatArgs {
384 fn get_unnamed(&self) -> impl Iterator<Item = &[Span]> {
385 self.unnamed.iter().map(|x| match x.as_slice() {
386 // Ignore the dummy span added from out of order format arguments.
392 fn get_named(&self, n: &Path) -> &[Span] {
393 self.named.iter().find(|x| *n == x.0).map_or(&[], |x| x.1.as_slice())
396 fn push(&mut self, arg: rustc_parse_format::Argument<'_>, span: Span) {
397 use rustc_parse_format::{
398 AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied, FormatSpec,
401 const SIMPLE: FormatSpec<'_> = FormatSpec {
405 precision: CountImplied,
406 precision_span: None,
414 ArgumentIs(n) | ArgumentImplicitlyIs(n) => {
415 if self.unnamed.len() <= n {
416 // Use a dummy span to mark all unseen arguments.
417 self.unnamed.resize_with(n, || vec![DUMMY_SP]);
418 if arg.format == SIMPLE {
419 self.unnamed.push(vec![span]);
421 self.unnamed.push(Vec::new());
424 let args = &mut self.unnamed[n];
425 match (args.as_mut_slice(), arg.format == SIMPLE) {
426 // A non-empty format string has been seen already.
428 // Replace the dummy span, if it exists.
429 ([dummy @ DUMMY_SP], true) => *dummy = span,
430 ([_, ..], true) => args.push(span),
431 ([_, ..], false) => *args = Vec::new(),
435 ArgumentNamed(n) => {
436 if let Some(x) = self.named.iter_mut().find(|x| x.0 == n) {
437 match x.1.as_slice() {
438 // A non-empty format string has been seen already.
440 [_, ..] if arg.format == SIMPLE => x.1.push(span),
441 [_, ..] => x.1 = Vec::new(),
443 } else if arg.format == SIMPLE {
444 self.named.push((n, vec![span]));
446 self.named.push((n, Vec::new()));
454 /// Parses a format string into a collection of spans for each argument. This only keeps track
455 /// of empty format arguments. Will also lint usages of debug format strings outside of debug
457 fn parse_fmt_string(&self, cx: &EarlyContext<'_>, str_lit: &StrLit) -> Option<SimpleFormatArgs> {
458 use rustc_parse_format::{ParseMode, Parser, Piece};
460 let str_sym = str_lit.symbol_unescaped.as_str();
461 let style = match str_lit.style {
462 StrStyle::Cooked => None,
463 StrStyle::Raw(n) => Some(n as usize),
466 let mut parser = Parser::new(&str_sym, style, snippet_opt(cx, str_lit.span), false, ParseMode::Format);
467 let mut args = SimpleFormatArgs::default();
469 while let Some(arg) = parser.next() {
470 let arg = match arg {
471 Piece::String(_) => continue,
472 Piece::NextArgument(arg) => arg,
477 .map_or(DUMMY_SP, |&x| str_lit.span.from_inner(x));
479 if !self.in_debug_impl && arg.format.ty == "?" {
480 // FIXME: modify rustc's fmt string parser to give us the current span
481 span_lint(cx, USE_DEBUG, span, "use of `Debug`-based formatting");
484 args.push(arg, span);
487 parser.errors.is_empty().then(move || args)
490 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
491 /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
492 /// the contents of the string, whether it's a raw string, and the span of the literal in the
493 /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
494 /// `format_str` should be written to.
498 /// Calling this function on
500 /// # use std::fmt::Write;
501 /// # let mut buf = String::new();
502 /// # let something = "something";
503 /// writeln!(buf, "string to write: {}", something);
507 /// (Some("string to write: {}"), Some(buf))
509 #[allow(clippy::too_many_lines)]
510 fn check_tts<'a>(&self, cx: &EarlyContext<'a>, tts: TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
511 let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, false, None);
512 let expr = if is_write {
515 .map(rustc_ast::ptr::P::into_inner)
516 .map_err(|mut e| e.cancel())
519 Ok(p) if parser.eat(&token::Comma) => Some(p),
520 // write!(e) or error
521 e => return (None, e.ok()),
527 let fmtstr = match parser.parse_str_lit() {
528 Ok(fmtstr) => fmtstr,
529 Err(_) => return (None, expr),
532 let args = match self.parse_fmt_string(cx, &fmtstr) {
534 None => return (Some(fmtstr), expr),
537 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
538 let mut unnamed_args = args.get_unnamed();
540 if !parser.eat(&token::Comma) {
541 return (Some(fmtstr), expr);
544 let comma_span = parser.prev_token.span;
545 let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
548 return (Some(fmtstr), None);
550 let (fmt_spans, lit) = match &token_expr.kind {
551 ExprKind::Lit(lit) => (unnamed_args.next().unwrap_or(&[]), lit),
552 ExprKind::Assign(lhs, rhs, _) => match (&lhs.kind, &rhs.kind) {
553 (ExprKind::Path(_, p), ExprKind::Lit(lit)) => (args.get_named(p), lit),
562 let replacement: String = match lit.token.kind {
563 LitKind::Integer | LitKind::Float | LitKind::Err => continue,
564 LitKind::StrRaw(_) | LitKind::ByteStrRaw(_) if matches!(fmtstr.style, StrStyle::Raw(_)) => {
565 lit.token.symbol.as_str().replace("{", "{{").replace("}", "}}")
567 LitKind::Str | LitKind::ByteStr if matches!(fmtstr.style, StrStyle::Cooked) => {
568 lit.token.symbol.as_str().replace("{", "{{").replace("}", "}}")
570 LitKind::StrRaw(_) | LitKind::Str | LitKind::ByteStrRaw(_) | LitKind::ByteStr => continue,
571 LitKind::Byte | LitKind::Char => match &*lit.token.symbol.as_str() {
572 "\"" if matches!(fmtstr.style, StrStyle::Cooked) => "\\\"",
573 "\"" if matches!(fmtstr.style, StrStyle::Raw(0)) => continue,
574 "\\\\" if matches!(fmtstr.style, StrStyle::Raw(_)) => "\\",
578 x if matches!(fmtstr.style, StrStyle::Raw(_)) && x.starts_with('\\') => continue,
582 LitKind::Bool => lit.token.symbol.as_str().deref().into(),
585 if !fmt_spans.is_empty() {
590 "literal with an empty format string",
592 diag.multipart_suggestion(
594 iter::once((comma_span.to(token_expr.span), String::new()))
595 .chain(fmt_spans.iter().copied().zip(iter::repeat(replacement)))
597 Applicability::MachineApplicable,
605 fn lint_println_empty_string(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
606 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
607 if fmt_str.symbol == kw::Empty {
608 let name = mac.path.segments[0].ident.name;
611 PRINTLN_EMPTY_STRING,
613 &format!("using `{}!(\"\")`", name),
615 format!("{}!()", name),
616 Applicability::MachineApplicable,
622 fn lint_print_with_newline(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
623 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
624 if check_newlines(&fmt_str) {
625 let name = mac.path.segments[0].ident.name;
626 let suggested = format!("{}ln", name);
631 &format!("using `{}!()` with a format string that ends in a single newline", name),
633 err.multipart_suggestion(
634 &format!("use `{}!` instead", suggested),
635 vec![(mac.path.span, suggested), (newline_span(&fmt_str).0, String::new())],
636 Applicability::MachineApplicable,
645 /// Checks if the format string contains a single newline that terminates it.
647 /// Literal and escaped newlines are both checked (only literal for raw strings).
648 fn check_newlines(fmtstr: &StrLit) -> bool {
649 let mut has_internal_newline = false;
650 let mut last_was_cr = false;
651 let mut should_lint = false;
653 let contents = &fmtstr.symbol.as_str();
655 let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
658 if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
661 last_was_cr = c == '\r';
663 has_internal_newline = true;
669 StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb),
670 StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb),