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.
35 #[clippy::version = "pre 1.29.0"]
36 pub PRINTLN_EMPTY_STRING,
38 "using `println!(\"\")` with an empty string"
41 declare_clippy_lint! {
43 /// This lint warns when you use `print!()` with a format
44 /// string that ends in a newline.
46 /// ### Why is this bad?
47 /// You should use `println!()` instead, which appends the
52 /// # let name = "World";
53 /// print!("Hello {}!\n", name);
55 /// use println!() instead
57 /// # let name = "World";
58 /// println!("Hello {}!", name);
60 #[clippy::version = "pre 1.29.0"]
61 pub PRINT_WITH_NEWLINE,
63 "using `print!()` with a format string that ends in a single newline"
66 declare_clippy_lint! {
68 /// Checks for printing on *stdout*. The purpose of this lint
69 /// is to catch debugging remnants.
71 /// ### Why is this bad?
72 /// People often print on *stdout* while debugging an
73 /// application and might forget to remove those prints afterward.
75 /// ### Known problems
76 /// * Only catches `print!` and `println!` calls.
77 /// * The lint level is unaffected by crate attributes. The level can still
78 /// be set for functions, modules and other items. To change the level for
79 /// the entire crate, please use command line flags. More information and a
80 /// configuration example can be found in [clippy#6610].
82 /// [clippy#6610]: https://github.com/rust-lang/rust-clippy/issues/6610#issuecomment-977120558
86 /// println!("Hello world!");
88 #[clippy::version = "pre 1.29.0"]
94 declare_clippy_lint! {
96 /// Checks for printing on *stderr*. The purpose of this lint
97 /// is to catch debugging remnants.
99 /// ### Why is this bad?
100 /// People often print on *stderr* while debugging an
101 /// application and might forget to remove those prints afterward.
103 /// ### Known problems
104 /// * Only catches `eprint!` and `eprintln!` calls.
105 /// * The lint level is unaffected by crate attributes. The level can still
106 /// be set for functions, modules and other items. To change the level for
107 /// the entire crate, please use command line flags. More information and a
108 /// configuration example can be found in [clippy#6610].
110 /// [clippy#6610]: https://github.com/rust-lang/rust-clippy/issues/6610#issuecomment-977120558
114 /// eprintln!("Hello world!");
116 #[clippy::version = "1.50.0"]
122 declare_clippy_lint! {
124 /// Checks for use of `Debug` formatting. The purpose of this
125 /// lint is to catch debugging remnants.
127 /// ### Why is this bad?
128 /// The purpose of the `Debug` trait is to facilitate
129 /// debugging Rust code. It should not be used in user-facing output.
133 /// # let foo = "bar";
134 /// println!("{:?}", foo);
136 #[clippy::version = "pre 1.29.0"]
139 "use of `Debug`-based formatting"
142 declare_clippy_lint! {
144 /// This lint warns about the use of literals as `print!`/`println!` args.
146 /// ### Why is this bad?
147 /// Using literals as `println!` args is inefficient
148 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
149 /// (i.e., just put the literal in the format string)
151 /// ### Known problems
152 /// Will also warn with macro calls as arguments that expand to literals
153 /// -- e.g., `println!("{}", env!("FOO"))`.
157 /// println!("{}", "foo");
159 /// use the literal without formatting:
163 #[clippy::version = "pre 1.29.0"]
166 "printing a literal with a format string"
169 declare_clippy_lint! {
171 /// This lint warns when you use `writeln!(buf, "")` to
174 /// ### Why is this bad?
175 /// You should use `writeln!(buf)`, which is simpler.
179 /// # use std::fmt::Write;
180 /// # let mut buf = String::new();
181 /// writeln!(buf, "");
186 /// # use std::fmt::Write;
187 /// # let mut buf = String::new();
190 #[clippy::version = "pre 1.29.0"]
191 pub WRITELN_EMPTY_STRING,
193 "using `writeln!(buf, \"\")` with an empty string"
196 declare_clippy_lint! {
198 /// This lint warns when you use `write!()` with a format
200 /// ends in a newline.
202 /// ### Why is this bad?
203 /// You should use `writeln!()` instead, which appends the
208 /// # use std::fmt::Write;
209 /// # let mut buf = String::new();
210 /// # let name = "World";
211 /// write!(buf, "Hello {}!\n", name);
216 /// # use std::fmt::Write;
217 /// # let mut buf = String::new();
218 /// # let name = "World";
219 /// writeln!(buf, "Hello {}!", name);
221 #[clippy::version = "pre 1.29.0"]
222 pub WRITE_WITH_NEWLINE,
224 "using `write!()` with a format string that ends in a single newline"
227 declare_clippy_lint! {
229 /// This lint warns about the use of literals as `write!`/`writeln!` args.
231 /// ### Why is this bad?
232 /// Using literals as `writeln!` args is inefficient
233 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
234 /// (i.e., just put the literal in the format string)
236 /// ### Known problems
237 /// Will also warn with macro calls as arguments that expand to literals
238 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
242 /// # use std::fmt::Write;
243 /// # let mut buf = String::new();
244 /// writeln!(buf, "{}", "foo");
249 /// # use std::fmt::Write;
250 /// # let mut buf = String::new();
251 /// writeln!(buf, "foo");
253 #[clippy::version = "pre 1.29.0"]
256 "writing a literal with a format string"
264 impl_lint_pass!(Write => [
266 PRINTLN_EMPTY_STRING,
272 WRITELN_EMPTY_STRING,
276 impl EarlyLintPass for Write {
277 fn check_item(&mut self, _: &EarlyContext<'_>, item: &Item) {
278 if let ItemKind::Impl(box Impl {
279 of_trait: Some(trait_ref),
283 let trait_name = trait_ref
288 .expect("path has at least one segment")
291 if trait_name == sym::Debug {
292 self.in_debug_impl = true;
297 fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &Item) {
298 self.in_debug_impl = false;
301 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &MacCall) {
302 fn is_build_script(cx: &EarlyContext<'_>) -> bool {
303 // Cargo sets the crate name for build scripts to `build_script_build`
308 .map_or(false, |crate_name| crate_name == "build_script_build")
311 if mac.path == sym!(print) {
312 if !is_build_script(cx) {
313 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`");
315 self.lint_print_with_newline(cx, mac);
316 } else if mac.path == sym!(println) {
317 if !is_build_script(cx) {
318 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`");
320 self.lint_println_empty_string(cx, mac);
321 } else if mac.path == sym!(eprint) {
322 span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprint!`");
323 self.lint_print_with_newline(cx, mac);
324 } else if mac.path == sym!(eprintln) {
325 span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprintln!`");
326 self.lint_println_empty_string(cx, mac);
327 } else if mac.path == sym!(write) {
328 if let (Some(fmt_str), dest) = self.check_tts(cx, mac.args.inner_tokens(), true) {
329 if check_newlines(&fmt_str) {
330 let (nl_span, only_nl) = newline_span(&fmt_str);
331 let nl_span = match (dest, only_nl) {
332 // Special case of `write!(buf, "\n")`: Mark everything from the end of
333 // `buf` for removal so no trailing comma [`writeln!(buf, )`] remains.
334 (Some(dest_expr), true) => nl_span.with_lo(dest_expr.span.hi()),
341 "using `write!()` with a format string that ends in a single newline",
343 err.multipart_suggestion(
344 "use `writeln!()` instead",
345 vec![(mac.path.span, String::from("writeln")), (nl_span, String::new())],
346 Applicability::MachineApplicable,
352 } else if mac.path == sym!(writeln) {
353 if let (Some(fmt_str), expr) = self.check_tts(cx, mac.args.inner_tokens(), true) {
354 if fmt_str.symbol == kw::Empty {
355 let mut applicability = Applicability::MachineApplicable;
356 let suggestion = if let Some(e) = expr {
357 snippet_with_applicability(cx, e.span, "v", &mut applicability)
359 applicability = Applicability::HasPlaceholders;
365 WRITELN_EMPTY_STRING,
367 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
369 format!("writeln!({})", suggestion),
378 /// Given a format string that ends in a newline and its span, calculates the span of the
379 /// newline, or the format string itself if the format string consists solely of a newline.
380 /// Return this and a boolean indicating whether it only consisted of a newline.
381 fn newline_span(fmtstr: &StrLit) -> (Span, bool) {
382 let sp = fmtstr.span;
383 let contents = fmtstr.symbol.as_str();
385 if contents == r"\n" {
389 let newline_sp_hi = sp.hi()
390 - match fmtstr.style {
391 StrStyle::Cooked => BytePos(1),
392 StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
395 let newline_sp_len = if contents.ends_with('\n') {
397 } else if contents.ends_with(r"\n") {
400 panic!("expected format string to contain a newline");
403 (sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi), false)
406 /// Stores a list of replacement spans for each argument, but only if all the replacements used an
407 /// empty format string.
409 struct SimpleFormatArgs {
410 unnamed: Vec<Vec<Span>>,
411 named: Vec<(Symbol, Vec<Span>)>,
413 impl SimpleFormatArgs {
414 fn get_unnamed(&self) -> impl Iterator<Item = &[Span]> {
415 self.unnamed.iter().map(|x| match x.as_slice() {
416 // Ignore the dummy span added from out of order format arguments.
422 fn get_named(&self, n: &Path) -> &[Span] {
423 self.named.iter().find(|x| *n == x.0).map_or(&[], |x| x.1.as_slice())
426 fn push(&mut self, arg: rustc_parse_format::Argument<'_>, span: Span) {
427 use rustc_parse_format::{
428 AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied, FormatSpec,
431 const SIMPLE: FormatSpec<'_> = FormatSpec {
435 precision: CountImplied,
436 precision_span: None,
444 ArgumentIs(n, _) | ArgumentImplicitlyIs(n) => {
445 if self.unnamed.len() <= n {
446 // Use a dummy span to mark all unseen arguments.
447 self.unnamed.resize_with(n, || vec![DUMMY_SP]);
448 if arg.format == SIMPLE {
449 self.unnamed.push(vec![span]);
451 self.unnamed.push(Vec::new());
454 let args = &mut self.unnamed[n];
455 match (args.as_mut_slice(), arg.format == SIMPLE) {
456 // A non-empty format string has been seen already.
458 // Replace the dummy span, if it exists.
459 ([dummy @ DUMMY_SP], true) => *dummy = span,
460 ([_, ..], true) => args.push(span),
461 ([_, ..], false) => *args = Vec::new(),
465 ArgumentNamed(n, _) => {
466 let n = Symbol::intern(n);
467 if let Some(x) = self.named.iter_mut().find(|x| x.0 == n) {
468 match x.1.as_slice() {
469 // A non-empty format string has been seen already.
471 [_, ..] if arg.format == SIMPLE => x.1.push(span),
472 [_, ..] => x.1 = Vec::new(),
474 } else if arg.format == SIMPLE {
475 self.named.push((n, vec![span]));
477 self.named.push((n, Vec::new()));
485 /// Parses a format string into a collection of spans for each argument. This only keeps track
486 /// of empty format arguments. Will also lint usages of debug format strings outside of debug
488 fn parse_fmt_string(&self, cx: &EarlyContext<'_>, str_lit: &StrLit) -> Option<SimpleFormatArgs> {
489 use rustc_parse_format::{ParseMode, Parser, Piece};
491 let str_sym = str_lit.symbol_unescaped.as_str();
492 let style = match str_lit.style {
493 StrStyle::Cooked => None,
494 StrStyle::Raw(n) => Some(n as usize),
497 let mut parser = Parser::new(str_sym, style, snippet_opt(cx, str_lit.span), false, ParseMode::Format);
498 let mut args = SimpleFormatArgs::default();
500 while let Some(arg) = parser.next() {
501 let arg = match arg {
502 Piece::String(_) => continue,
503 Piece::NextArgument(arg) => arg,
508 .map_or(DUMMY_SP, |&x| str_lit.span.from_inner(InnerSpan::new(x.start, x.end)));
510 if !self.in_debug_impl && arg.format.ty == "?" {
511 // FIXME: modify rustc's fmt string parser to give us the current span
512 span_lint(cx, USE_DEBUG, span, "use of `Debug`-based formatting");
515 args.push(arg, span);
518 parser.errors.is_empty().then_some(args)
521 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
522 /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
523 /// the contents of the string, whether it's a raw string, and the span of the literal in the
524 /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
525 /// `format_str` should be written to.
529 /// Calling this function on
531 /// # use std::fmt::Write;
532 /// # let mut buf = String::new();
533 /// # let something = "something";
534 /// writeln!(buf, "string to write: {}", something);
538 /// (Some("string to write: {}"), Some(buf))
540 fn check_tts<'a>(&self, cx: &EarlyContext<'a>, tts: TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
541 let mut parser = parser::Parser::new(&cx.sess().parse_sess, tts, false, None);
542 let expr = if is_write {
545 .map(rustc_ast::ptr::P::into_inner)
546 .map_err(DiagnosticBuilder::cancel)
549 Ok(p) if parser.eat(&token::Comma) => Some(p),
550 // write!(e) or error
551 e => return (None, e.ok()),
557 let fmtstr = match parser.parse_str_lit() {
558 Ok(fmtstr) => fmtstr,
559 Err(_) => return (None, expr),
562 let args = match self.parse_fmt_string(cx, &fmtstr) {
564 None => return (Some(fmtstr), expr),
567 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
568 let mut unnamed_args = args.get_unnamed();
570 if !parser.eat(&token::Comma) {
571 return (Some(fmtstr), expr);
574 let comma_span = parser.prev_token.span;
575 let token_expr = if let Ok(expr) = parser.parse_expr().map_err(DiagnosticBuilder::cancel) {
578 return (Some(fmtstr), None);
580 let (fmt_spans, lit) = match &token_expr.kind {
581 ExprKind::Lit(lit) => (unnamed_args.next().unwrap_or(&[]), lit),
582 ExprKind::Assign(lhs, rhs, _) => match (&lhs.kind, &rhs.kind) {
583 (ExprKind::Path(_, p), ExprKind::Lit(lit)) => (args.get_named(p), lit),
592 let replacement: String = match lit.token.kind {
593 LitKind::StrRaw(_) | LitKind::ByteStrRaw(_) if matches!(fmtstr.style, StrStyle::Raw(_)) => {
594 lit.token.symbol.as_str().replace('{', "{{").replace('}', "}}")
596 LitKind::Str | LitKind::ByteStr if matches!(fmtstr.style, StrStyle::Cooked) => {
597 lit.token.symbol.as_str().replace('{', "{{").replace('}', "}}")
601 | LitKind::ByteStrRaw(_)
605 | LitKind::Err => continue,
606 LitKind::Byte | LitKind::Char => match lit.token.symbol.as_str() {
607 "\"" if matches!(fmtstr.style, StrStyle::Cooked) => "\\\"",
608 "\"" if matches!(fmtstr.style, StrStyle::Raw(0)) => continue,
609 "\\\\" if matches!(fmtstr.style, StrStyle::Raw(_)) => "\\",
613 x if matches!(fmtstr.style, StrStyle::Raw(_)) && x.starts_with('\\') => continue,
617 LitKind::Bool => lit.token.symbol.as_str().deref().into(),
620 if !fmt_spans.is_empty() {
625 "literal with an empty format string",
627 diag.multipart_suggestion(
629 iter::once((comma_span.to(token_expr.span), String::new()))
630 .chain(fmt_spans.iter().copied().zip(iter::repeat(replacement)))
632 Applicability::MachineApplicable,
640 fn lint_println_empty_string(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
641 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
642 if fmt_str.symbol == kw::Empty {
643 let name = mac.path.segments[0].ident.name;
646 PRINTLN_EMPTY_STRING,
648 &format!("using `{}!(\"\")`", name),
650 format!("{}!()", name),
651 Applicability::MachineApplicable,
657 fn lint_print_with_newline(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
658 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
659 if check_newlines(&fmt_str) {
660 let name = mac.path.segments[0].ident.name;
661 let suggested = format!("{}ln", name);
666 &format!("using `{}!()` with a format string that ends in a single newline", name),
668 err.multipart_suggestion(
669 &format!("use `{}!` instead", suggested),
670 vec![(mac.path.span, suggested), (newline_span(&fmt_str).0, String::new())],
671 Applicability::MachineApplicable,
680 /// Checks if the format string contains a single newline that terminates it.
682 /// Literal and escaped newlines are both checked (only literal for raw strings).
683 fn check_newlines(fmtstr: &StrLit) -> bool {
684 let mut has_internal_newline = false;
685 let mut last_was_cr = false;
686 let mut should_lint = false;
688 let contents = fmtstr.symbol.as_str();
690 let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
693 if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
696 last_was_cr = c == '\r';
698 has_internal_newline = true;
704 StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb),
705 StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb),