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, DiagnosticBuilder};
11 use rustc_lexer::unescape::{self, EscapeError};
12 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
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, InnerSpan, 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 let suggestion = if let Some(e) = expr {
346 snippet_with_applicability(cx, e.span, "v", &mut applicability)
348 applicability = Applicability::HasPlaceholders;
354 WRITELN_EMPTY_STRING,
356 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
358 format!("writeln!({})", suggestion),
367 /// Given a format string that ends in a newline and its span, calculates the span of the
368 /// newline, or the format string itself if the format string consists solely of a newline.
369 /// Return this and a boolean indicating whether it only consisted of a newline.
370 fn newline_span(fmtstr: &StrLit) -> (Span, bool) {
371 let sp = fmtstr.span;
372 let contents = fmtstr.symbol.as_str();
374 if contents == r"\n" {
378 let newline_sp_hi = sp.hi()
379 - match fmtstr.style {
380 StrStyle::Cooked => BytePos(1),
381 StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
384 let newline_sp_len = if contents.ends_with('\n') {
386 } else if contents.ends_with(r"\n") {
389 panic!("expected format string to contain a newline");
392 (sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi), false)
395 /// Stores a list of replacement spans for each argument, but only if all the replacements used an
396 /// empty format string.
398 struct SimpleFormatArgs {
399 unnamed: Vec<Vec<Span>>,
400 named: Vec<(Symbol, Vec<Span>)>,
402 impl SimpleFormatArgs {
403 fn get_unnamed(&self) -> impl Iterator<Item = &[Span]> {
404 self.unnamed.iter().map(|x| match x.as_slice() {
405 // Ignore the dummy span added from out of order format arguments.
411 fn get_named(&self, n: &Path) -> &[Span] {
412 self.named.iter().find(|x| *n == x.0).map_or(&[], |x| x.1.as_slice())
415 fn push(&mut self, arg: rustc_parse_format::Argument<'_>, span: Span) {
416 use rustc_parse_format::{
417 AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied, FormatSpec,
420 const SIMPLE: FormatSpec<'_> = FormatSpec {
424 precision: CountImplied,
425 precision_span: None,
433 ArgumentIs(n) | ArgumentImplicitlyIs(n) => {
434 if self.unnamed.len() <= n {
435 // Use a dummy span to mark all unseen arguments.
436 self.unnamed.resize_with(n, || vec![DUMMY_SP]);
437 if arg.format == SIMPLE {
438 self.unnamed.push(vec![span]);
440 self.unnamed.push(Vec::new());
443 let args = &mut self.unnamed[n];
444 match (args.as_mut_slice(), arg.format == SIMPLE) {
445 // A non-empty format string has been seen already.
447 // Replace the dummy span, if it exists.
448 ([dummy @ DUMMY_SP], true) => *dummy = span,
449 ([_, ..], true) => args.push(span),
450 ([_, ..], false) => *args = Vec::new(),
454 ArgumentNamed(n, _) => {
455 let n = Symbol::intern(n);
456 if let Some(x) = self.named.iter_mut().find(|x| x.0 == n) {
457 match x.1.as_slice() {
458 // A non-empty format string has been seen already.
460 [_, ..] if arg.format == SIMPLE => x.1.push(span),
461 [_, ..] => x.1 = Vec::new(),
463 } else if arg.format == SIMPLE {
464 self.named.push((n, vec![span]));
466 self.named.push((n, Vec::new()));
474 /// Parses a format string into a collection of spans for each argument. This only keeps track
475 /// of empty format arguments. Will also lint usages of debug format strings outside of debug
477 fn parse_fmt_string(&self, cx: &EarlyContext<'_>, str_lit: &StrLit) -> Option<SimpleFormatArgs> {
478 use rustc_parse_format::{ParseMode, Parser, Piece};
480 let str_sym = str_lit.symbol_unescaped.as_str();
481 let style = match str_lit.style {
482 StrStyle::Cooked => None,
483 StrStyle::Raw(n) => Some(n as usize),
486 let mut parser = Parser::new(str_sym, style, snippet_opt(cx, str_lit.span), false, ParseMode::Format);
487 let mut args = SimpleFormatArgs::default();
489 while let Some(arg) = parser.next() {
490 let arg = match arg {
491 Piece::String(_) => continue,
492 Piece::NextArgument(arg) => arg,
497 .map_or(DUMMY_SP, |&x| str_lit.span.from_inner(InnerSpan::new(x.start, x.end)));
499 if !self.in_debug_impl && arg.format.ty == "?" {
500 // FIXME: modify rustc's fmt string parser to give us the current span
501 span_lint(cx, USE_DEBUG, span, "use of `Debug`-based formatting");
504 args.push(arg, span);
507 parser.errors.is_empty().then(move || args)
510 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
511 /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
512 /// the contents of the string, whether it's a raw string, and the span of the literal in the
513 /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
514 /// `format_str` should be written to.
518 /// Calling this function on
520 /// # use std::fmt::Write;
521 /// # let mut buf = String::new();
522 /// # let something = "something";
523 /// writeln!(buf, "string to write: {}", something);
527 /// (Some("string to write: {}"), Some(buf))
529 fn check_tts<'a>(&self, cx: &EarlyContext<'a>, tts: TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
530 let mut parser = parser::Parser::new(&cx.sess().parse_sess, tts, false, None);
531 let expr = if is_write {
534 .map(rustc_ast::ptr::P::into_inner)
535 .map_err(DiagnosticBuilder::cancel)
538 Ok(p) if parser.eat(&token::Comma) => Some(p),
539 // write!(e) or error
540 e => return (None, e.ok()),
546 let fmtstr = match parser.parse_str_lit() {
547 Ok(fmtstr) => fmtstr,
548 Err(_) => return (None, expr),
551 let args = match self.parse_fmt_string(cx, &fmtstr) {
553 None => return (Some(fmtstr), expr),
556 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
557 let mut unnamed_args = args.get_unnamed();
559 if !parser.eat(&token::Comma) {
560 return (Some(fmtstr), expr);
563 let comma_span = parser.prev_token.span;
564 let token_expr = if let Ok(expr) = parser.parse_expr().map_err(DiagnosticBuilder::cancel) {
567 return (Some(fmtstr), None);
569 let (fmt_spans, lit) = match &token_expr.kind {
570 ExprKind::Lit(lit) => (unnamed_args.next().unwrap_or(&[]), lit),
571 ExprKind::Assign(lhs, rhs, _) => match (&lhs.kind, &rhs.kind) {
572 (ExprKind::Path(_, p), ExprKind::Lit(lit)) => (args.get_named(p), lit),
581 let replacement: String = match lit.token.kind {
582 LitKind::StrRaw(_) | LitKind::ByteStrRaw(_) if matches!(fmtstr.style, StrStyle::Raw(_)) => {
583 lit.token.symbol.as_str().replace('{', "{{").replace('}', "}}")
585 LitKind::Str | LitKind::ByteStr if matches!(fmtstr.style, StrStyle::Cooked) => {
586 lit.token.symbol.as_str().replace('{', "{{").replace('}', "}}")
590 | LitKind::ByteStrRaw(_)
594 | LitKind::Err => continue,
595 LitKind::Byte | LitKind::Char => match lit.token.symbol.as_str() {
596 "\"" if matches!(fmtstr.style, StrStyle::Cooked) => "\\\"",
597 "\"" if matches!(fmtstr.style, StrStyle::Raw(0)) => continue,
598 "\\\\" if matches!(fmtstr.style, StrStyle::Raw(_)) => "\\",
602 x if matches!(fmtstr.style, StrStyle::Raw(_)) && x.starts_with('\\') => continue,
606 LitKind::Bool => lit.token.symbol.as_str().deref().into(),
609 if !fmt_spans.is_empty() {
614 "literal with an empty format string",
616 diag.multipart_suggestion(
618 iter::once((comma_span.to(token_expr.span), String::new()))
619 .chain(fmt_spans.iter().copied().zip(iter::repeat(replacement)))
621 Applicability::MachineApplicable,
629 fn lint_println_empty_string(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
630 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
631 if fmt_str.symbol == kw::Empty {
632 let name = mac.path.segments[0].ident.name;
635 PRINTLN_EMPTY_STRING,
637 &format!("using `{}!(\"\")`", name),
639 format!("{}!()", name),
640 Applicability::MachineApplicable,
646 fn lint_print_with_newline(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
647 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
648 if check_newlines(&fmt_str) {
649 let name = mac.path.segments[0].ident.name;
650 let suggested = format!("{}ln", name);
655 &format!("using `{}!()` with a format string that ends in a single newline", name),
657 err.multipart_suggestion(
658 &format!("use `{}!` instead", suggested),
659 vec![(mac.path.span, suggested), (newline_span(&fmt_str).0, String::new())],
660 Applicability::MachineApplicable,
669 /// Checks if the format string contains a single newline that terminates it.
671 /// Literal and escaped newlines are both checked (only literal for raw strings).
672 fn check_newlines(fmtstr: &StrLit) -> bool {
673 let mut has_internal_newline = false;
674 let mut last_was_cr = false;
675 let mut should_lint = false;
677 let contents = fmtstr.symbol.as_str();
679 let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
682 if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
685 last_was_cr = c == '\r';
687 has_internal_newline = true;
693 StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb),
694 StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb),