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.
76 /// * The lint level is unaffected by crate attributes. The level can still
77 /// be set for functions, modules and other items. To change the level for
78 /// the entire crate, please use command line flags. More information and a
79 /// configuration example can be found in [clippy#6610].
81 /// [clippy#6610]: https://github.com/rust-lang/rust-clippy/issues/6610#issuecomment-977120558
85 /// println!("Hello world!");
87 #[clippy::version = "pre 1.29.0"]
93 declare_clippy_lint! {
95 /// Checks for printing on *stderr*. The purpose of this lint
96 /// is to catch debugging remnants.
98 /// ### Why is this bad?
99 /// People often print on *stderr* while debugging an
100 /// application and might forget to remove those prints afterward.
102 /// ### Known problems
103 /// * Only catches `eprint!` and `eprintln!` calls.
104 /// * The lint level is unaffected by crate attributes. The level can still
105 /// be set for functions, modules and other items. To change the level for
106 /// the entire crate, please use command line flags. More information and a
107 /// configuration example can be found in [clippy#6610].
109 /// [clippy#6610]: https://github.com/rust-lang/rust-clippy/issues/6610#issuecomment-977120558
113 /// eprintln!("Hello world!");
115 #[clippy::version = "1.50.0"]
121 declare_clippy_lint! {
123 /// Checks for use of `Debug` formatting. The purpose of this
124 /// lint is to catch debugging remnants.
126 /// ### Why is this bad?
127 /// The purpose of the `Debug` trait is to facilitate
128 /// debugging Rust code. It should not be used in user-facing output.
132 /// # let foo = "bar";
133 /// println!("{:?}", foo);
135 #[clippy::version = "pre 1.29.0"]
138 "use of `Debug`-based formatting"
141 declare_clippy_lint! {
143 /// This lint warns about the use of literals as `print!`/`println!` args.
145 /// ### Why is this bad?
146 /// Using literals as `println!` args is inefficient
147 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
148 /// (i.e., just put the literal in the format string)
150 /// ### Known problems
151 /// Will also warn with macro calls as arguments that expand to literals
152 /// -- e.g., `println!("{}", env!("FOO"))`.
156 /// println!("{}", "foo");
158 /// use the literal without formatting:
162 #[clippy::version = "pre 1.29.0"]
165 "printing a literal with a format string"
168 declare_clippy_lint! {
170 /// This lint warns when you use `writeln!(buf, "")` to
173 /// ### Why is this bad?
174 /// You should use `writeln!(buf)`, which is simpler.
178 /// # use std::fmt::Write;
179 /// # let mut buf = String::new();
181 /// writeln!(buf, "");
186 #[clippy::version = "pre 1.29.0"]
187 pub WRITELN_EMPTY_STRING,
189 "using `writeln!(buf, \"\")` with an empty string"
192 declare_clippy_lint! {
194 /// This lint warns when you use `write!()` with a format
196 /// ends in a newline.
198 /// ### Why is this bad?
199 /// You should use `writeln!()` instead, which appends the
204 /// # use std::fmt::Write;
205 /// # let mut buf = String::new();
206 /// # let name = "World";
208 /// write!(buf, "Hello {}!\n", name);
211 /// writeln!(buf, "Hello {}!", name);
213 #[clippy::version = "pre 1.29.0"]
214 pub WRITE_WITH_NEWLINE,
216 "using `write!()` with a format string that ends in a single newline"
219 declare_clippy_lint! {
221 /// This lint warns about the use of literals as `write!`/`writeln!` args.
223 /// ### Why is this bad?
224 /// Using literals as `writeln!` args is inefficient
225 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
226 /// (i.e., just put the literal in the format string)
228 /// ### Known problems
229 /// Will also warn with macro calls as arguments that expand to literals
230 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
234 /// # use std::fmt::Write;
235 /// # let mut buf = String::new();
237 /// writeln!(buf, "{}", "foo");
240 /// writeln!(buf, "foo");
242 #[clippy::version = "pre 1.29.0"]
245 "writing a literal with a format string"
253 impl_lint_pass!(Write => [
255 PRINTLN_EMPTY_STRING,
261 WRITELN_EMPTY_STRING,
265 impl EarlyLintPass for Write {
266 fn check_item(&mut self, _: &EarlyContext<'_>, item: &Item) {
267 if let ItemKind::Impl(box Impl {
268 of_trait: Some(trait_ref),
272 let trait_name = trait_ref
277 .expect("path has at least one segment")
280 if trait_name == sym::Debug {
281 self.in_debug_impl = true;
286 fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &Item) {
287 self.in_debug_impl = false;
290 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &MacCall) {
291 fn is_build_script(cx: &EarlyContext<'_>) -> bool {
292 // Cargo sets the crate name for build scripts to `build_script_build`
297 .map_or(false, |crate_name| crate_name == "build_script_build")
300 if mac.path == sym!(print) {
301 if !is_build_script(cx) {
302 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`");
304 self.lint_print_with_newline(cx, mac);
305 } else if mac.path == sym!(println) {
306 if !is_build_script(cx) {
307 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`");
309 self.lint_println_empty_string(cx, mac);
310 } else if mac.path == sym!(eprint) {
311 span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprint!`");
312 self.lint_print_with_newline(cx, mac);
313 } else if mac.path == sym!(eprintln) {
314 span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprintln!`");
315 self.lint_println_empty_string(cx, mac);
316 } else if mac.path == sym!(write) {
317 if let (Some(fmt_str), dest) = self.check_tts(cx, mac.args.inner_tokens(), true) {
318 if check_newlines(&fmt_str) {
319 let (nl_span, only_nl) = newline_span(&fmt_str);
320 let nl_span = match (dest, only_nl) {
321 // Special case of `write!(buf, "\n")`: Mark everything from the end of
322 // `buf` for removal so no trailing comma [`writeln!(buf, )`] remains.
323 (Some(dest_expr), true) => nl_span.with_lo(dest_expr.span.hi()),
330 "using `write!()` with a format string that ends in a single newline",
332 err.multipart_suggestion(
333 "use `writeln!()` instead",
334 vec![(mac.path.span, String::from("writeln")), (nl_span, String::new())],
335 Applicability::MachineApplicable,
341 } else if mac.path == sym!(writeln) {
342 if let (Some(fmt_str), expr) = self.check_tts(cx, mac.args.inner_tokens(), true) {
343 if fmt_str.symbol == kw::Empty {
344 let mut applicability = Applicability::MachineApplicable;
345 // FIXME: remove this `#[allow(...)]` once the issue #5822 gets fixed
346 #[allow(clippy::option_if_let_else)]
347 let suggestion = if let Some(e) = expr {
348 snippet_with_applicability(cx, e.span, "v", &mut applicability)
350 applicability = Applicability::HasPlaceholders;
356 WRITELN_EMPTY_STRING,
358 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
360 format!("writeln!({})", suggestion),
369 /// Given a format string that ends in a newline and its span, calculates the span of the
370 /// newline, or the format string itself if the format string consists solely of a newline.
371 /// Return this and a boolean indicating whether it only consisted of a newline.
372 fn newline_span(fmtstr: &StrLit) -> (Span, bool) {
373 let sp = fmtstr.span;
374 let contents = &fmtstr.symbol.as_str();
376 if *contents == r"\n" {
380 let newline_sp_hi = sp.hi()
381 - match fmtstr.style {
382 StrStyle::Cooked => BytePos(1),
383 StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
386 let newline_sp_len = if contents.ends_with('\n') {
388 } else if contents.ends_with(r"\n") {
391 panic!("expected format string to contain a newline");
394 (sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi), false)
397 /// Stores a list of replacement spans for each argument, but only if all the replacements used an
398 /// empty format string.
400 struct SimpleFormatArgs {
401 unnamed: Vec<Vec<Span>>,
402 named: Vec<(Symbol, Vec<Span>)>,
404 impl SimpleFormatArgs {
405 fn get_unnamed(&self) -> impl Iterator<Item = &[Span]> {
406 self.unnamed.iter().map(|x| match x.as_slice() {
407 // Ignore the dummy span added from out of order format arguments.
413 fn get_named(&self, n: &Path) -> &[Span] {
414 self.named.iter().find(|x| *n == x.0).map_or(&[], |x| x.1.as_slice())
417 fn push(&mut self, arg: rustc_parse_format::Argument<'_>, span: Span) {
418 use rustc_parse_format::{
419 AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied, FormatSpec,
422 const SIMPLE: FormatSpec<'_> = FormatSpec {
426 precision: CountImplied,
427 precision_span: None,
435 ArgumentIs(n) | ArgumentImplicitlyIs(n) => {
436 if self.unnamed.len() <= n {
437 // Use a dummy span to mark all unseen arguments.
438 self.unnamed.resize_with(n, || vec![DUMMY_SP]);
439 if arg.format == SIMPLE {
440 self.unnamed.push(vec![span]);
442 self.unnamed.push(Vec::new());
445 let args = &mut self.unnamed[n];
446 match (args.as_mut_slice(), arg.format == SIMPLE) {
447 // A non-empty format string has been seen already.
449 // Replace the dummy span, if it exists.
450 ([dummy @ DUMMY_SP], true) => *dummy = span,
451 ([_, ..], true) => args.push(span),
452 ([_, ..], false) => *args = Vec::new(),
456 ArgumentNamed(n) => {
457 if let Some(x) = self.named.iter_mut().find(|x| x.0 == n) {
458 match x.1.as_slice() {
459 // A non-empty format string has been seen already.
461 [_, ..] if arg.format == SIMPLE => x.1.push(span),
462 [_, ..] => x.1 = Vec::new(),
464 } else if arg.format == SIMPLE {
465 self.named.push((n, vec![span]));
467 self.named.push((n, Vec::new()));
475 /// Parses a format string into a collection of spans for each argument. This only keeps track
476 /// of empty format arguments. Will also lint usages of debug format strings outside of debug
478 fn parse_fmt_string(&self, cx: &EarlyContext<'_>, str_lit: &StrLit) -> Option<SimpleFormatArgs> {
479 use rustc_parse_format::{ParseMode, Parser, Piece};
481 let str_sym = str_lit.symbol_unescaped.as_str();
482 let style = match str_lit.style {
483 StrStyle::Cooked => None,
484 StrStyle::Raw(n) => Some(n as usize),
487 let mut parser = Parser::new(&str_sym, style, snippet_opt(cx, str_lit.span), false, ParseMode::Format);
488 let mut args = SimpleFormatArgs::default();
490 while let Some(arg) = parser.next() {
491 let arg = match arg {
492 Piece::String(_) => continue,
493 Piece::NextArgument(arg) => arg,
498 .map_or(DUMMY_SP, |&x| str_lit.span.from_inner(x));
500 if !self.in_debug_impl && arg.format.ty == "?" {
501 // FIXME: modify rustc's fmt string parser to give us the current span
502 span_lint(cx, USE_DEBUG, span, "use of `Debug`-based formatting");
505 args.push(arg, span);
508 parser.errors.is_empty().then(move || args)
511 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
512 /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
513 /// the contents of the string, whether it's a raw string, and the span of the literal in the
514 /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
515 /// `format_str` should be written to.
519 /// Calling this function on
521 /// # use std::fmt::Write;
522 /// # let mut buf = String::new();
523 /// # let something = "something";
524 /// writeln!(buf, "string to write: {}", something);
528 /// (Some("string to write: {}"), Some(buf))
530 #[allow(clippy::too_many_lines)]
531 fn check_tts<'a>(&self, cx: &EarlyContext<'a>, tts: TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
532 let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, false, None);
533 let expr = if is_write {
536 .map(rustc_ast::ptr::P::into_inner)
537 .map_err(|mut e| e.cancel())
540 Ok(p) if parser.eat(&token::Comma) => Some(p),
541 // write!(e) or error
542 e => return (None, e.ok()),
548 let fmtstr = match parser.parse_str_lit() {
549 Ok(fmtstr) => fmtstr,
550 Err(_) => return (None, expr),
553 let args = match self.parse_fmt_string(cx, &fmtstr) {
555 None => return (Some(fmtstr), expr),
558 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
559 let mut unnamed_args = args.get_unnamed();
561 if !parser.eat(&token::Comma) {
562 return (Some(fmtstr), expr);
565 let comma_span = parser.prev_token.span;
566 let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
569 return (Some(fmtstr), None);
571 let (fmt_spans, lit) = match &token_expr.kind {
572 ExprKind::Lit(lit) => (unnamed_args.next().unwrap_or(&[]), lit),
573 ExprKind::Assign(lhs, rhs, _) => match (&lhs.kind, &rhs.kind) {
574 (ExprKind::Path(_, p), ExprKind::Lit(lit)) => (args.get_named(p), lit),
583 let replacement: String = match lit.token.kind {
584 LitKind::Integer | LitKind::Float | LitKind::Err => continue,
585 LitKind::StrRaw(_) | LitKind::ByteStrRaw(_) if matches!(fmtstr.style, StrStyle::Raw(_)) => {
586 lit.token.symbol.as_str().replace('{', "{{").replace('}', "}}")
588 LitKind::Str | LitKind::ByteStr if matches!(fmtstr.style, StrStyle::Cooked) => {
589 lit.token.symbol.as_str().replace('{', "{{").replace('}', "}}")
591 LitKind::StrRaw(_) | LitKind::Str | LitKind::ByteStrRaw(_) | LitKind::ByteStr => continue,
592 LitKind::Byte | LitKind::Char => match &*lit.token.symbol.as_str() {
593 "\"" if matches!(fmtstr.style, StrStyle::Cooked) => "\\\"",
594 "\"" if matches!(fmtstr.style, StrStyle::Raw(0)) => continue,
595 "\\\\" if matches!(fmtstr.style, StrStyle::Raw(_)) => "\\",
599 x if matches!(fmtstr.style, StrStyle::Raw(_)) && x.starts_with('\\') => continue,
603 LitKind::Bool => lit.token.symbol.as_str().deref().into(),
606 if !fmt_spans.is_empty() {
611 "literal with an empty format string",
613 diag.multipart_suggestion(
615 iter::once((comma_span.to(token_expr.span), String::new()))
616 .chain(fmt_spans.iter().copied().zip(iter::repeat(replacement)))
618 Applicability::MachineApplicable,
626 fn lint_println_empty_string(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
627 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
628 if fmt_str.symbol == kw::Empty {
629 let name = mac.path.segments[0].ident.name;
632 PRINTLN_EMPTY_STRING,
634 &format!("using `{}!(\"\")`", name),
636 format!("{}!()", name),
637 Applicability::MachineApplicable,
643 fn lint_print_with_newline(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
644 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
645 if check_newlines(&fmt_str) {
646 let name = mac.path.segments[0].ident.name;
647 let suggested = format!("{}ln", name);
652 &format!("using `{}!()` with a format string that ends in a single newline", name),
654 err.multipart_suggestion(
655 &format!("use `{}!` instead", suggested),
656 vec![(mac.path.span, suggested), (newline_span(&fmt_str).0, String::new())],
657 Applicability::MachineApplicable,
666 /// Checks if the format string contains a single newline that terminates it.
668 /// Literal and escaped newlines are both checked (only literal for raw strings).
669 fn check_newlines(fmtstr: &StrLit) -> bool {
670 let mut has_internal_newline = false;
671 let mut last_was_cr = false;
672 let mut should_lint = false;
674 let contents = &fmtstr.symbol.as_str();
676 let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
679 if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
682 last_was_cr = c == '\r';
684 has_internal_newline = true;
690 StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb),
691 StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb),