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! {
19 /// **What it does:** This lint warns when you use `println!("")` to
22 /// **Why is this bad?** You should use `println!()`, which is simpler.
24 /// **Known problems:** None.
34 pub PRINTLN_EMPTY_STRING,
36 "using `println!(\"\")` with an empty string"
39 declare_clippy_lint! {
40 /// **What it does:** This lint warns when you use `print!()` with a format
41 /// string that ends in a newline.
43 /// **Why is this bad?** You should use `println!()` instead, which appends the
46 /// **Known problems:** None.
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! {
64 /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
65 /// is to catch debugging remnants.
67 /// **Why is this bad?** People often print on *stdout* while debugging an
68 /// application and might forget to remove those prints afterward.
70 /// **Known problems:** Only catches `print!` and `println!` calls.
74 /// println!("Hello world!");
81 declare_clippy_lint! {
82 /// **What it does:** Checks for printing on *stderr*. The purpose of this lint
83 /// is to catch debugging remnants.
85 /// **Why is this bad?** People often print on *stderr* while debugging an
86 /// application and might forget to remove those prints afterward.
88 /// **Known problems:** Only catches `eprint!` and `eprintln!` calls.
92 /// eprintln!("Hello world!");
99 declare_clippy_lint! {
100 /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
101 /// lint is to catch debugging remnants.
103 /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
104 /// debugging Rust code. It should not be used in user-facing output.
108 /// # let foo = "bar";
109 /// println!("{:?}", foo);
113 "use of `Debug`-based formatting"
116 declare_clippy_lint! {
117 /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
119 /// **Why is this bad?** Using literals as `println!` args is inefficient
120 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
121 /// (i.e., just put the literal in the format string)
123 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
124 /// -- e.g., `println!("{}", env!("FOO"))`.
128 /// println!("{}", "foo");
130 /// use the literal without formatting:
136 "printing a literal with a format string"
139 declare_clippy_lint! {
140 /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
143 /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
145 /// **Known problems:** None.
149 /// # use std::fmt::Write;
150 /// # 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";
178 /// write!(buf, "Hello {}!\n", name);
181 /// writeln!(buf, "Hello {}!", name);
183 pub WRITE_WITH_NEWLINE,
185 "using `write!()` with a format string that ends in a single newline"
188 declare_clippy_lint! {
189 /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
191 /// **Why is this bad?** Using literals as `writeln!` args is inefficient
192 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
193 /// (i.e., just put the literal in the format string)
195 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
196 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
200 /// # use std::fmt::Write;
201 /// # let mut buf = String::new();
203 /// writeln!(buf, "{}", "foo");
206 /// writeln!(buf, "foo");
210 "writing a literal with a format string"
218 impl_lint_pass!(Write => [
220 PRINTLN_EMPTY_STRING,
226 WRITELN_EMPTY_STRING,
230 impl EarlyLintPass for Write {
231 fn check_item(&mut self, _: &EarlyContext<'_>, item: &Item) {
232 if let ItemKind::Impl(box ImplKind {
233 of_trait: Some(trait_ref),
237 let trait_name = trait_ref
242 .expect("path has at least one segment")
245 if trait_name == sym::Debug {
246 self.in_debug_impl = true;
251 fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &Item) {
252 self.in_debug_impl = false;
255 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &MacCall) {
256 fn is_build_script(cx: &EarlyContext<'_>) -> bool {
257 // Cargo sets the crate name for build scripts to `build_script_build`
262 .map_or(false, |crate_name| crate_name == "build_script_build")
265 if mac.path == sym!(print) {
266 if !is_build_script(cx) {
267 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`");
269 self.lint_print_with_newline(cx, mac);
270 } else if mac.path == sym!(println) {
271 if !is_build_script(cx) {
272 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`");
274 self.lint_println_empty_string(cx, mac);
275 } else if mac.path == sym!(eprint) {
276 span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprint!`");
277 self.lint_print_with_newline(cx, mac);
278 } else if mac.path == sym!(eprintln) {
279 span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprintln!`");
280 self.lint_println_empty_string(cx, mac);
281 } else if mac.path == sym!(write) {
282 if let (Some(fmt_str), dest) = self.check_tts(cx, mac.args.inner_tokens(), true) {
283 if check_newlines(&fmt_str) {
284 let (nl_span, only_nl) = newline_span(&fmt_str);
285 let nl_span = match (dest, only_nl) {
286 // Special case of `write!(buf, "\n")`: Mark everything from the end of
287 // `buf` for removal so no trailing comma [`writeln!(buf, )`] remains.
288 (Some(dest_expr), true) => Span::new(dest_expr.span.hi(), nl_span.hi(), nl_span.ctxt()),
295 "using `write!()` with a format string that ends in a single newline",
297 err.multipart_suggestion(
298 "use `writeln!()` instead",
299 vec![(mac.path.span, String::from("writeln")), (nl_span, 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 /// Return this and a boolean indicating whether it only consisted of a newline.
337 fn newline_span(fmtstr: &StrLit) -> (Span, bool) {
338 let sp = fmtstr.span;
339 let contents = &fmtstr.symbol.as_str();
341 if *contents == r"\n" {
345 let newline_sp_hi = sp.hi()
346 - match fmtstr.style {
347 StrStyle::Cooked => BytePos(1),
348 StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
351 let newline_sp_len = if contents.ends_with('\n') {
353 } else if contents.ends_with(r"\n") {
356 panic!("expected format string to contain a newline");
359 (sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi), false)
362 /// Stores a list of replacement spans for each argument, but only if all the replacements used an
363 /// empty format string.
365 struct SimpleFormatArgs {
366 unnamed: Vec<Vec<Span>>,
367 named: Vec<(Symbol, Vec<Span>)>,
369 impl SimpleFormatArgs {
370 fn get_unnamed(&self) -> impl Iterator<Item = &[Span]> {
371 self.unnamed.iter().map(|x| match x.as_slice() {
372 // Ignore the dummy span added from out of order format arguments.
378 fn get_named(&self, n: &Path) -> &[Span] {
379 self.named.iter().find(|x| *n == x.0).map_or(&[], |x| x.1.as_slice())
382 fn push(&mut self, arg: rustc_parse_format::Argument<'_>, span: Span) {
383 use rustc_parse_format::{
384 AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied, FormatSpec,
387 const SIMPLE: FormatSpec<'_> = FormatSpec {
391 precision: CountImplied,
392 precision_span: None,
400 ArgumentIs(n) | ArgumentImplicitlyIs(n) => {
401 if self.unnamed.len() <= n {
402 // Use a dummy span to mark all unseen arguments.
403 self.unnamed.resize_with(n, || vec![DUMMY_SP]);
404 if arg.format == SIMPLE {
405 self.unnamed.push(vec![span]);
407 self.unnamed.push(Vec::new());
410 let args = &mut self.unnamed[n];
411 match (args.as_mut_slice(), arg.format == SIMPLE) {
412 // A non-empty format string has been seen already.
414 // Replace the dummy span, if it exists.
415 ([dummy @ DUMMY_SP], true) => *dummy = span,
416 ([_, ..], true) => args.push(span),
417 ([_, ..], false) => *args = Vec::new(),
421 ArgumentNamed(n) => {
422 if let Some(x) = self.named.iter_mut().find(|x| x.0 == n) {
423 match x.1.as_slice() {
424 // A non-empty format string has been seen already.
426 [_, ..] if arg.format == SIMPLE => x.1.push(span),
427 [_, ..] => x.1 = Vec::new(),
429 } else if arg.format == SIMPLE {
430 self.named.push((n, vec![span]));
432 self.named.push((n, Vec::new()));
440 /// Parses a format string into a collection of spans for each argument. This only keeps track
441 /// of empty format arguments. Will also lint usages of debug format strings outside of debug
443 fn parse_fmt_string(&self, cx: &EarlyContext<'_>, str_lit: &StrLit) -> Option<SimpleFormatArgs> {
444 use rustc_parse_format::{ParseMode, Parser, Piece};
446 let str_sym = str_lit.symbol_unescaped.as_str();
447 let style = match str_lit.style {
448 StrStyle::Cooked => None,
449 StrStyle::Raw(n) => Some(n as usize),
452 let mut parser = Parser::new(&str_sym, style, snippet_opt(cx, str_lit.span), false, ParseMode::Format);
453 let mut args = SimpleFormatArgs::default();
455 while let Some(arg) = parser.next() {
456 let arg = match arg {
457 Piece::String(_) => continue,
458 Piece::NextArgument(arg) => arg,
463 .map_or(DUMMY_SP, |&x| str_lit.span.from_inner(x));
465 if !self.in_debug_impl && arg.format.ty == "?" {
466 // FIXME: modify rustc's fmt string parser to give us the current span
467 span_lint(cx, USE_DEBUG, span, "use of `Debug`-based formatting");
470 args.push(arg, span);
473 parser.errors.is_empty().then(move || args)
476 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
477 /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
478 /// the contents of the string, whether it's a raw string, and the span of the literal in the
479 /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
480 /// `format_str` should be written to.
484 /// Calling this function on
486 /// # use std::fmt::Write;
487 /// # let mut buf = String::new();
488 /// # let something = "something";
489 /// writeln!(buf, "string to write: {}", something);
493 /// (Some("string to write: {}"), Some(buf))
495 #[allow(clippy::too_many_lines)]
496 fn check_tts<'a>(&self, cx: &EarlyContext<'a>, tts: TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
497 let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, false, None);
498 let expr = if is_write {
501 .map(rustc_ast::ptr::P::into_inner)
502 .map_err(|mut e| e.cancel())
505 Ok(p) if parser.eat(&token::Comma) => Some(p),
506 // write!(e) or error
507 e => return (None, e.ok()),
513 let fmtstr = match parser.parse_str_lit() {
514 Ok(fmtstr) => fmtstr,
515 Err(_) => return (None, expr),
518 let args = match self.parse_fmt_string(cx, &fmtstr) {
520 None => return (Some(fmtstr), expr),
523 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
524 let mut unnamed_args = args.get_unnamed();
526 if !parser.eat(&token::Comma) {
527 return (Some(fmtstr), expr);
530 let comma_span = parser.prev_token.span;
531 let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
534 return (Some(fmtstr), None);
536 let (fmt_spans, lit) = match &token_expr.kind {
537 ExprKind::Lit(lit) => (unnamed_args.next().unwrap_or(&[]), lit),
538 ExprKind::Assign(lhs, rhs, _) => match (&lhs.kind, &rhs.kind) {
539 (ExprKind::Path(_, p), ExprKind::Lit(lit)) => (args.get_named(p), lit),
548 let replacement: String = match lit.token.kind {
549 LitKind::Integer | LitKind::Float | LitKind::Err => continue,
550 LitKind::StrRaw(_) | LitKind::ByteStrRaw(_) if matches!(fmtstr.style, StrStyle::Raw(_)) => {
551 lit.token.symbol.as_str().replace("{", "{{").replace("}", "}}")
553 LitKind::Str | LitKind::ByteStr if matches!(fmtstr.style, StrStyle::Cooked) => {
554 lit.token.symbol.as_str().replace("{", "{{").replace("}", "}}")
556 LitKind::StrRaw(_) | LitKind::Str | LitKind::ByteStrRaw(_) | LitKind::ByteStr => continue,
557 LitKind::Byte | LitKind::Char => match &*lit.token.symbol.as_str() {
558 "\"" if matches!(fmtstr.style, StrStyle::Cooked) => "\\\"",
559 "\"" if matches!(fmtstr.style, StrStyle::Raw(0)) => continue,
560 "\\\\" if matches!(fmtstr.style, StrStyle::Raw(_)) => "\\",
564 x if matches!(fmtstr.style, StrStyle::Raw(_)) && x.starts_with('\\') => continue,
568 LitKind::Bool => lit.token.symbol.as_str().deref().into(),
571 if !fmt_spans.is_empty() {
576 "literal with an empty format string",
578 diag.multipart_suggestion(
580 iter::once((comma_span.to(token_expr.span), String::new()))
581 .chain(fmt_spans.iter().copied().zip(iter::repeat(replacement)))
583 Applicability::MachineApplicable,
591 fn lint_println_empty_string(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
592 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
593 if fmt_str.symbol == kw::Empty {
594 let name = mac.path.segments[0].ident.name;
597 PRINTLN_EMPTY_STRING,
599 &format!("using `{}!(\"\")`", name),
601 format!("{}!()", name),
602 Applicability::MachineApplicable,
608 fn lint_print_with_newline(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
609 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
610 if check_newlines(&fmt_str) {
611 let name = mac.path.segments[0].ident.name;
612 let suggested = format!("{}ln", name);
617 &format!("using `{}!()` with a format string that ends in a single newline", name),
619 err.multipart_suggestion(
620 &format!("use `{}!` instead", suggested),
621 vec![(mac.path.span, suggested), (newline_span(&fmt_str).0, String::new())],
622 Applicability::MachineApplicable,
631 /// Checks if the format string contains a single newline that terminates it.
633 /// Literal and escaped newlines are both checked (only literal for raw strings).
634 fn check_newlines(fmtstr: &StrLit) -> bool {
635 let mut has_internal_newline = false;
636 let mut last_was_cr = false;
637 let mut should_lint = false;
639 let contents = &fmtstr.symbol.as_str();
641 let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
644 if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
647 last_was_cr = c == '\r';
649 has_internal_newline = true;
655 StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb),
656 StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb),