4 use crate::utils::{snippet_with_applicability, span_lint, span_lint_and_sugg, span_lint_and_then};
5 use rustc_ast::ast::{Expr, ExprKind, Item, ItemKind, MacCall, StrLit, StrStyle};
7 use rustc_ast::tokenstream::TokenStream;
8 use rustc_errors::Applicability;
9 use rustc_lexer::unescape::{self, EscapeError};
10 use rustc_lint::{EarlyContext, EarlyLintPass};
11 use rustc_parse::parser;
12 use rustc_session::{declare_tool_lint, impl_lint_pass};
13 use rustc_span::{sym, BytePos, Span, Symbol};
15 declare_clippy_lint! {
16 /// **What it does:** This lint warns when you use `println!("")` to
19 /// **Why is this bad?** You should use `println!()`, which is simpler.
21 /// **Known problems:** None.
31 pub PRINTLN_EMPTY_STRING,
33 "using `println!(\"\")` with an empty string"
36 declare_clippy_lint! {
37 /// **What it does:** This lint warns when you use `print!()` with a format
38 /// string that ends in a newline.
40 /// **Why is this bad?** You should use `println!()` instead, which appends the
43 /// **Known problems:** None.
47 /// # let name = "World";
48 /// print!("Hello {}!\n", name);
50 /// use println!() instead
52 /// # let name = "World";
53 /// println!("Hello {}!", name);
55 pub PRINT_WITH_NEWLINE,
57 "using `print!()` with a format string that ends in a single newline"
60 declare_clippy_lint! {
61 /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
62 /// is to catch debugging remnants.
64 /// **Why is this bad?** People often print on *stdout* while debugging an
65 /// application and might forget to remove those prints afterward.
67 /// **Known problems:** Only catches `print!` and `println!` calls.
71 /// println!("Hello world!");
78 declare_clippy_lint! {
79 /// **What it does:** Checks for printing on *stderr*. The purpose of this lint
80 /// is to catch debugging remnants.
82 /// **Why is this bad?** People often print on *stderr* while debugging an
83 /// application and might forget to remove those prints afterward.
85 /// **Known problems:** Only catches `eprint!` and `eprintln!` calls.
89 /// eprintln!("Hello world!");
96 declare_clippy_lint! {
97 /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
98 /// lint is to catch debugging remnants.
100 /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
101 /// debugging Rust code. It should not be used in user-facing output.
105 /// # let foo = "bar";
106 /// println!("{:?}", foo);
110 "use of `Debug`-based formatting"
113 declare_clippy_lint! {
114 /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
116 /// **Why is this bad?** Using literals as `println!` args is inefficient
117 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
118 /// (i.e., just put the literal in the format string)
120 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
121 /// -- e.g., `println!("{}", env!("FOO"))`.
125 /// println!("{}", "foo");
127 /// use the literal without formatting:
133 "printing a literal with a format string"
136 declare_clippy_lint! {
137 /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
140 /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
142 /// **Known problems:** None.
146 /// # use std::fmt::Write;
147 /// # let mut buf = String::new();
150 /// writeln!(buf, "");
155 pub WRITELN_EMPTY_STRING,
157 "using `writeln!(buf, \"\")` with an empty string"
160 declare_clippy_lint! {
161 /// **What it does:** This lint warns when you use `write!()` with a format
163 /// ends in a newline.
165 /// **Why is this bad?** You should use `writeln!()` instead, which appends the
168 /// **Known problems:** None.
172 /// # use std::fmt::Write;
173 /// # let mut buf = String::new();
174 /// # let name = "World";
177 /// write!(buf, "Hello {}!\n", name);
180 /// writeln!(buf, "Hello {}!", name);
182 pub WRITE_WITH_NEWLINE,
184 "using `write!()` with a format string that ends in a single newline"
187 declare_clippy_lint! {
188 /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
190 /// **Why is this bad?** Using literals as `writeln!` args is inefficient
191 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
192 /// (i.e., just put the literal in the format string)
194 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
195 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
199 /// # use std::fmt::Write;
200 /// # 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 {
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), _) = self.check_tts(cx, mac.args.inner_tokens(), true) {
283 if check_newlines(&fmt_str) {
288 "using `write!()` with a format string that ends in a single newline",
290 err.multipart_suggestion(
291 "use `writeln!()` instead",
293 (mac.path.span, String::from("writeln")),
294 (newline_span(&fmt_str), String::new()),
296 Applicability::MachineApplicable,
302 } else if mac.path == sym!(writeln) {
303 if let (Some(fmt_str), expr) = self.check_tts(cx, mac.args.inner_tokens(), true) {
304 if fmt_str.symbol == Symbol::intern("") {
305 let mut applicability = Applicability::MachineApplicable;
306 // FIXME: remove this `#[allow(...)]` once the issue #5822 gets fixed
307 #[allow(clippy::option_if_let_else)]
308 let suggestion = if let Some(e) = expr {
309 snippet_with_applicability(cx, e.span, "v", &mut applicability)
311 applicability = Applicability::HasPlaceholders;
317 WRITELN_EMPTY_STRING,
319 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
321 format!("writeln!({})", suggestion),
330 /// Given a format string that ends in a newline and its span, calculates the span of the
331 /// newline, or the format string itself if the format string consists solely of a newline.
332 fn newline_span(fmtstr: &StrLit) -> Span {
333 let sp = fmtstr.span;
334 let contents = &fmtstr.symbol.as_str();
336 if *contents == r"\n" {
340 let newline_sp_hi = sp.hi()
341 - match fmtstr.style {
342 StrStyle::Cooked => BytePos(1),
343 StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
346 let newline_sp_len = if contents.ends_with('\n') {
348 } else if contents.ends_with(r"\n") {
351 panic!("expected format string to contain a newline");
354 sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi)
358 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
359 /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
360 /// the contents of the string, whether it's a raw string, and the span of the literal in the
361 /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
362 /// `format_str` should be written to.
366 /// Calling this function on
368 /// # use std::fmt::Write;
369 /// # let mut buf = String::new();
370 /// # let something = "something";
371 /// writeln!(buf, "string to write: {}", something);
375 /// (Some("string to write: {}"), Some(buf))
377 #[allow(clippy::too_many_lines)]
378 fn check_tts<'a>(&self, cx: &EarlyContext<'a>, tts: TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
379 use rustc_parse_format::{
380 AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied, FormatSpec, ParseMode, Parser,
384 let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, false, None);
385 let mut expr: Option<Expr> = None;
387 expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
388 Ok(p) => Some(p.into_inner()),
389 Err(_) => return (None, None),
391 // might be `writeln!(foo)`
392 if parser.expect(&token::Comma).map_err(|mut err| err.cancel()).is_err() {
397 let fmtstr = match parser.parse_str_lit() {
398 Ok(fmtstr) => fmtstr,
399 Err(_) => return (None, expr),
401 let tmp = fmtstr.symbol.as_str();
402 let mut args = vec![];
403 let mut fmt_parser = Parser::new(&tmp, None, None, false, ParseMode::Format);
404 while let Some(piece) = fmt_parser.next() {
405 if !fmt_parser.errors.is_empty() {
408 if let Piece::NextArgument(arg) = piece {
409 if !self.in_debug_impl && arg.format.ty == "?" {
410 // FIXME: modify rustc's fmt string parser to give us the current span
411 span_lint(cx, USE_DEBUG, parser.prev_token.span, "use of `Debug`-based formatting");
416 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
419 const SIMPLE: FormatSpec<'_> = FormatSpec {
423 precision: CountImplied,
424 precision_span: None,
430 if !parser.eat(&token::Comma) {
431 return (Some(fmtstr), expr);
433 let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
436 return (Some(fmtstr), None);
438 match &token_expr.kind {
439 ExprKind::Lit(_) => {
440 let mut all_simple = true;
441 let mut seen = false;
444 ArgumentImplicitlyIs(n) | ArgumentIs(n) => {
446 all_simple &= arg.format == SIMPLE;
450 ArgumentNamed(_) => {},
453 if all_simple && seen {
454 span_lint(cx, lint, token_expr.span, "literal with an empty format string");
458 ExprKind::Assign(lhs, rhs, _) => {
459 if let ExprKind::Lit(_) = rhs.kind {
460 if let ExprKind::Path(_, p) = &lhs.kind {
461 let mut all_simple = true;
462 let mut seen = false;
465 ArgumentImplicitlyIs(_) | ArgumentIs(_) => {},
466 ArgumentNamed(name) => {
469 all_simple &= arg.format == SIMPLE;
474 if all_simple && seen {
475 span_lint(cx, lint, rhs.span, "literal with an empty format string");
485 fn lint_println_empty_string(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
486 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
487 if fmt_str.symbol == Symbol::intern("") {
488 let name = mac.path.segments[0].ident.name;
491 PRINTLN_EMPTY_STRING,
493 &format!("using `{}!(\"\")`", name),
495 format!("{}!()", name),
496 Applicability::MachineApplicable,
502 fn lint_print_with_newline(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
503 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
504 if check_newlines(&fmt_str) {
505 let name = mac.path.segments[0].ident.name;
506 let suggested = format!("{}ln", name);
511 &format!("using `{}!()` with a format string that ends in a single newline", name),
513 err.multipart_suggestion(
514 &format!("use `{}!` instead", suggested),
515 vec![(mac.path.span, suggested), (newline_span(&fmt_str), String::new())],
516 Applicability::MachineApplicable,
525 /// Checks if the format string contains a single newline that terminates it.
527 /// Literal and escaped newlines are both checked (only literal for raw strings).
528 fn check_newlines(fmtstr: &StrLit) -> bool {
529 let mut has_internal_newline = false;
530 let mut last_was_cr = false;
531 let mut should_lint = false;
533 let contents = &fmtstr.symbol.as_str();
535 let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
538 if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
541 last_was_cr = c == '\r';
543 has_internal_newline = true;
549 StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb),
550 StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb),