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, Impl, 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 #[clippy::version = "pre 1.29.0"]
35 pub PRINTLN_EMPTY_STRING,
37 "using `println!(\"\")` with an empty string"
40 declare_clippy_lint! {
42 /// This lint warns when you use `print!()` with a format
43 /// string that ends in a newline.
45 /// ### Why is this bad?
46 /// You should use `println!()` instead, which appends the
51 /// # let name = "World";
52 /// print!("Hello {}!\n", name);
54 /// use println!() instead
56 /// # let name = "World";
57 /// println!("Hello {}!", name);
59 #[clippy::version = "pre 1.29.0"]
60 pub PRINT_WITH_NEWLINE,
62 "using `print!()` with a format string that ends in a single newline"
65 declare_clippy_lint! {
67 /// Checks for printing on *stdout*. The purpose of this lint
68 /// is to catch debugging remnants.
70 /// ### Why is this bad?
71 /// People often print on *stdout* while debugging an
72 /// application and might forget to remove those prints afterward.
74 /// ### Known problems
75 /// Only catches `print!` and `println!` calls.
79 /// println!("Hello world!");
81 #[clippy::version = "pre 1.29.0"]
87 declare_clippy_lint! {
89 /// Checks for printing on *stderr*. The purpose of this lint
90 /// is to catch debugging remnants.
92 /// ### Why is this bad?
93 /// People often print on *stderr* while debugging an
94 /// application and might forget to remove those prints afterward.
96 /// ### Known problems
97 /// Only catches `eprint!` and `eprintln!` calls.
101 /// eprintln!("Hello world!");
103 #[clippy::version = "1.50.0"]
109 declare_clippy_lint! {
111 /// Checks for use of `Debug` formatting. The purpose of this
112 /// lint is to catch debugging remnants.
114 /// ### Why is this bad?
115 /// The purpose of the `Debug` trait is to facilitate
116 /// debugging Rust code. It should not be used in user-facing output.
120 /// # let foo = "bar";
121 /// println!("{:?}", foo);
123 #[clippy::version = "pre 1.29.0"]
126 "use of `Debug`-based formatting"
129 declare_clippy_lint! {
131 /// This lint warns about the use of literals as `print!`/`println!` args.
133 /// ### Why is this bad?
134 /// Using literals as `println!` args is inefficient
135 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
136 /// (i.e., just put the literal in the format string)
138 /// ### Known problems
139 /// Will also warn with macro calls as arguments that expand to literals
140 /// -- e.g., `println!("{}", env!("FOO"))`.
144 /// println!("{}", "foo");
146 /// use the literal without formatting:
150 #[clippy::version = "pre 1.29.0"]
153 "printing a literal with a format string"
156 declare_clippy_lint! {
158 /// This lint warns when you use `writeln!(buf, "")` to
161 /// ### Why is this bad?
162 /// You should use `writeln!(buf)`, which is simpler.
166 /// # use std::fmt::Write;
167 /// # let mut buf = String::new();
169 /// writeln!(buf, "");
174 #[clippy::version = "pre 1.29.0"]
175 pub WRITELN_EMPTY_STRING,
177 "using `writeln!(buf, \"\")` with an empty string"
180 declare_clippy_lint! {
182 /// This lint warns when you use `write!()` with a format
184 /// ends in a newline.
186 /// ### Why is this bad?
187 /// You should use `writeln!()` instead, which appends the
192 /// # use std::fmt::Write;
193 /// # let mut buf = String::new();
194 /// # let name = "World";
196 /// write!(buf, "Hello {}!\n", name);
199 /// writeln!(buf, "Hello {}!", name);
201 #[clippy::version = "pre 1.29.0"]
202 pub WRITE_WITH_NEWLINE,
204 "using `write!()` with a format string that ends in a single newline"
207 declare_clippy_lint! {
209 /// This lint warns about the use of literals as `write!`/`writeln!` args.
211 /// ### Why is this bad?
212 /// Using literals as `writeln!` args is inefficient
213 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
214 /// (i.e., just put the literal in the format string)
216 /// ### Known problems
217 /// Will also warn with macro calls as arguments that expand to literals
218 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
222 /// # use std::fmt::Write;
223 /// # let mut buf = String::new();
225 /// writeln!(buf, "{}", "foo");
228 /// writeln!(buf, "foo");
230 #[clippy::version = "pre 1.29.0"]
233 "writing a literal with a format string"
241 impl_lint_pass!(Write => [
243 PRINTLN_EMPTY_STRING,
249 WRITELN_EMPTY_STRING,
253 impl EarlyLintPass for Write {
254 fn check_item(&mut self, _: &EarlyContext<'_>, item: &Item) {
255 if let ItemKind::Impl(box Impl {
256 of_trait: Some(trait_ref),
260 let trait_name = trait_ref
265 .expect("path has at least one segment")
268 if trait_name == sym::Debug {
269 self.in_debug_impl = true;
274 fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &Item) {
275 self.in_debug_impl = false;
278 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &MacCall) {
279 fn is_build_script(cx: &EarlyContext<'_>) -> bool {
280 // Cargo sets the crate name for build scripts to `build_script_build`
285 .map_or(false, |crate_name| crate_name == "build_script_build")
288 if mac.path == sym!(print) {
289 if !is_build_script(cx) {
290 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`");
292 self.lint_print_with_newline(cx, mac);
293 } else if mac.path == sym!(println) {
294 if !is_build_script(cx) {
295 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`");
297 self.lint_println_empty_string(cx, mac);
298 } else if mac.path == sym!(eprint) {
299 span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprint!`");
300 self.lint_print_with_newline(cx, mac);
301 } else if mac.path == sym!(eprintln) {
302 span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprintln!`");
303 self.lint_println_empty_string(cx, mac);
304 } else if mac.path == sym!(write) {
305 if let (Some(fmt_str), dest) = self.check_tts(cx, mac.args.inner_tokens(), true) {
306 if check_newlines(&fmt_str) {
307 let (nl_span, only_nl) = newline_span(&fmt_str);
308 let nl_span = match (dest, only_nl) {
309 // Special case of `write!(buf, "\n")`: Mark everything from the end of
310 // `buf` for removal so no trailing comma [`writeln!(buf, )`] remains.
311 (Some(dest_expr), true) => nl_span.with_lo(dest_expr.span.hi()),
318 "using `write!()` with a format string that ends in a single newline",
320 err.multipart_suggestion(
321 "use `writeln!()` instead",
322 vec![(mac.path.span, String::from("writeln")), (nl_span, String::new())],
323 Applicability::MachineApplicable,
329 } else if mac.path == sym!(writeln) {
330 if let (Some(fmt_str), expr) = self.check_tts(cx, mac.args.inner_tokens(), true) {
331 if fmt_str.symbol == kw::Empty {
332 let mut applicability = Applicability::MachineApplicable;
333 // FIXME: remove this `#[allow(...)]` once the issue #5822 gets fixed
334 #[allow(clippy::option_if_let_else)]
335 let suggestion = if let Some(e) = expr {
336 snippet_with_applicability(cx, e.span, "v", &mut applicability)
338 applicability = Applicability::HasPlaceholders;
344 WRITELN_EMPTY_STRING,
346 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
348 format!("writeln!({})", suggestion),
357 /// Given a format string that ends in a newline and its span, calculates the span of the
358 /// newline, or the format string itself if the format string consists solely of a newline.
359 /// Return this and a boolean indicating whether it only consisted of a newline.
360 fn newline_span(fmtstr: &StrLit) -> (Span, bool) {
361 let sp = fmtstr.span;
362 let contents = &fmtstr.symbol.as_str();
364 if *contents == r"\n" {
368 let newline_sp_hi = sp.hi()
369 - match fmtstr.style {
370 StrStyle::Cooked => BytePos(1),
371 StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
374 let newline_sp_len = if contents.ends_with('\n') {
376 } else if contents.ends_with(r"\n") {
379 panic!("expected format string to contain a newline");
382 (sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi), false)
385 /// Stores a list of replacement spans for each argument, but only if all the replacements used an
386 /// empty format string.
388 struct SimpleFormatArgs {
389 unnamed: Vec<Vec<Span>>,
390 named: Vec<(Symbol, Vec<Span>)>,
392 impl SimpleFormatArgs {
393 fn get_unnamed(&self) -> impl Iterator<Item = &[Span]> {
394 self.unnamed.iter().map(|x| match x.as_slice() {
395 // Ignore the dummy span added from out of order format arguments.
401 fn get_named(&self, n: &Path) -> &[Span] {
402 self.named.iter().find(|x| *n == x.0).map_or(&[], |x| x.1.as_slice())
405 fn push(&mut self, arg: rustc_parse_format::Argument<'_>, span: Span) {
406 use rustc_parse_format::{
407 AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied, FormatSpec,
410 const SIMPLE: FormatSpec<'_> = FormatSpec {
414 precision: CountImplied,
415 precision_span: None,
423 ArgumentIs(n) | ArgumentImplicitlyIs(n) => {
424 if self.unnamed.len() <= n {
425 // Use a dummy span to mark all unseen arguments.
426 self.unnamed.resize_with(n, || vec![DUMMY_SP]);
427 if arg.format == SIMPLE {
428 self.unnamed.push(vec![span]);
430 self.unnamed.push(Vec::new());
433 let args = &mut self.unnamed[n];
434 match (args.as_mut_slice(), arg.format == SIMPLE) {
435 // A non-empty format string has been seen already.
437 // Replace the dummy span, if it exists.
438 ([dummy @ DUMMY_SP], true) => *dummy = span,
439 ([_, ..], true) => args.push(span),
440 ([_, ..], false) => *args = Vec::new(),
444 ArgumentNamed(n) => {
445 if let Some(x) = self.named.iter_mut().find(|x| x.0 == n) {
446 match x.1.as_slice() {
447 // A non-empty format string has been seen already.
449 [_, ..] if arg.format == SIMPLE => x.1.push(span),
450 [_, ..] => x.1 = Vec::new(),
452 } else if arg.format == SIMPLE {
453 self.named.push((n, vec![span]));
455 self.named.push((n, Vec::new()));
463 /// Parses a format string into a collection of spans for each argument. This only keeps track
464 /// of empty format arguments. Will also lint usages of debug format strings outside of debug
466 fn parse_fmt_string(&self, cx: &EarlyContext<'_>, str_lit: &StrLit) -> Option<SimpleFormatArgs> {
467 use rustc_parse_format::{ParseMode, Parser, Piece};
469 let str_sym = str_lit.symbol_unescaped.as_str();
470 let style = match str_lit.style {
471 StrStyle::Cooked => None,
472 StrStyle::Raw(n) => Some(n as usize),
475 let mut parser = Parser::new(&str_sym, style, snippet_opt(cx, str_lit.span), false, ParseMode::Format);
476 let mut args = SimpleFormatArgs::default();
478 while let Some(arg) = parser.next() {
479 let arg = match arg {
480 Piece::String(_) => continue,
481 Piece::NextArgument(arg) => arg,
486 .map_or(DUMMY_SP, |&x| str_lit.span.from_inner(x));
488 if !self.in_debug_impl && arg.format.ty == "?" {
489 // FIXME: modify rustc's fmt string parser to give us the current span
490 span_lint(cx, USE_DEBUG, span, "use of `Debug`-based formatting");
493 args.push(arg, span);
496 parser.errors.is_empty().then(move || args)
499 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
500 /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
501 /// the contents of the string, whether it's a raw string, and the span of the literal in the
502 /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
503 /// `format_str` should be written to.
507 /// Calling this function on
509 /// # use std::fmt::Write;
510 /// # let mut buf = String::new();
511 /// # let something = "something";
512 /// writeln!(buf, "string to write: {}", something);
516 /// (Some("string to write: {}"), Some(buf))
518 #[allow(clippy::too_many_lines)]
519 fn check_tts<'a>(&self, cx: &EarlyContext<'a>, tts: TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
520 let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, false, None);
521 let expr = if is_write {
524 .map(rustc_ast::ptr::P::into_inner)
525 .map_err(|mut e| e.cancel())
528 Ok(p) if parser.eat(&token::Comma) => Some(p),
529 // write!(e) or error
530 e => return (None, e.ok()),
536 let fmtstr = match parser.parse_str_lit() {
537 Ok(fmtstr) => fmtstr,
538 Err(_) => return (None, expr),
541 let args = match self.parse_fmt_string(cx, &fmtstr) {
543 None => return (Some(fmtstr), expr),
546 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
547 let mut unnamed_args = args.get_unnamed();
549 if !parser.eat(&token::Comma) {
550 return (Some(fmtstr), expr);
553 let comma_span = parser.prev_token.span;
554 let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
557 return (Some(fmtstr), None);
559 let (fmt_spans, lit) = match &token_expr.kind {
560 ExprKind::Lit(lit) => (unnamed_args.next().unwrap_or(&[]), lit),
561 ExprKind::Assign(lhs, rhs, _) => match (&lhs.kind, &rhs.kind) {
562 (ExprKind::Path(_, p), ExprKind::Lit(lit)) => (args.get_named(p), lit),
571 let replacement: String = match lit.token.kind {
572 LitKind::Integer | LitKind::Float | LitKind::Err => continue,
573 LitKind::StrRaw(_) | LitKind::ByteStrRaw(_) if matches!(fmtstr.style, StrStyle::Raw(_)) => {
574 lit.token.symbol.as_str().replace("{", "{{").replace("}", "}}")
576 LitKind::Str | LitKind::ByteStr if matches!(fmtstr.style, StrStyle::Cooked) => {
577 lit.token.symbol.as_str().replace("{", "{{").replace("}", "}}")
579 LitKind::StrRaw(_) | LitKind::Str | LitKind::ByteStrRaw(_) | LitKind::ByteStr => continue,
580 LitKind::Byte | LitKind::Char => match &*lit.token.symbol.as_str() {
581 "\"" if matches!(fmtstr.style, StrStyle::Cooked) => "\\\"",
582 "\"" if matches!(fmtstr.style, StrStyle::Raw(0)) => continue,
583 "\\\\" if matches!(fmtstr.style, StrStyle::Raw(_)) => "\\",
587 x if matches!(fmtstr.style, StrStyle::Raw(_)) && x.starts_with('\\') => continue,
591 LitKind::Bool => lit.token.symbol.as_str().deref().into(),
594 if !fmt_spans.is_empty() {
599 "literal with an empty format string",
601 diag.multipart_suggestion(
603 iter::once((comma_span.to(token_expr.span), String::new()))
604 .chain(fmt_spans.iter().copied().zip(iter::repeat(replacement)))
606 Applicability::MachineApplicable,
614 fn lint_println_empty_string(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
615 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
616 if fmt_str.symbol == kw::Empty {
617 let name = mac.path.segments[0].ident.name;
620 PRINTLN_EMPTY_STRING,
622 &format!("using `{}!(\"\")`", name),
624 format!("{}!()", name),
625 Applicability::MachineApplicable,
631 fn lint_print_with_newline(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
632 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
633 if check_newlines(&fmt_str) {
634 let name = mac.path.segments[0].ident.name;
635 let suggested = format!("{}ln", name);
640 &format!("using `{}!()` with a format string that ends in a single newline", name),
642 err.multipart_suggestion(
643 &format!("use `{}!` instead", suggested),
644 vec![(mac.path.span, suggested), (newline_span(&fmt_str).0, String::new())],
645 Applicability::MachineApplicable,
654 /// Checks if the format string contains a single newline that terminates it.
656 /// Literal and escaped newlines are both checked (only literal for raw strings).
657 fn check_newlines(fmtstr: &StrLit) -> bool {
658 let mut has_internal_newline = false;
659 let mut last_was_cr = false;
660 let mut should_lint = false;
662 let contents = &fmtstr.symbol.as_str();
664 let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
667 if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
670 last_was_cr = c == '\r';
672 has_internal_newline = true;
678 StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb),
679 StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb),