4 use crate::utils::{snippet_with_applicability, span_lint, span_lint_and_sugg, span_lint_and_then};
5 use if_chain::if_chain;
6 use rustc_ast::ast::{Expr, ExprKind, Item, ItemKind, MacCall, StrLit, StrStyle};
8 use rustc_ast::tokenstream::TokenStream;
9 use rustc_errors::Applicability;
10 use rustc_lexer::unescape::{self, EscapeError};
11 use rustc_lint::{EarlyContext, EarlyLintPass};
12 use rustc_parse::parser;
13 use rustc_session::{declare_tool_lint, impl_lint_pass};
14 use rustc_span::symbol::Symbol;
15 use rustc_span::{BytePos, FileName, Span};
17 declare_clippy_lint! {
18 /// **What it does:** This lint warns when you use `println!("")` to
21 /// **Why is this bad?** You should use `println!()`, which is simpler.
23 /// **Known problems:** None.
33 pub PRINTLN_EMPTY_STRING,
35 "using `println!(\"\")` with an empty string"
38 declare_clippy_lint! {
39 /// **What it does:** This lint warns when you use `print!()` with a format
40 /// string that ends in a newline.
42 /// **Why is this bad?** You should use `println!()` instead, which appends the
45 /// **Known problems:** None.
49 /// # let name = "World";
50 /// print!("Hello {}!\n", name);
52 /// use println!() instead
54 /// # let name = "World";
55 /// println!("Hello {}!", name);
57 pub PRINT_WITH_NEWLINE,
59 "using `print!()` with a format string that ends in a single newline"
62 declare_clippy_lint! {
63 /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
64 /// is to catch debugging remnants.
66 /// **Why is this bad?** People often print on *stdout* while debugging an
67 /// application and might forget to remove those prints afterward.
69 /// **Known problems:** Only catches `print!` and `println!` calls.
73 /// println!("Hello world!");
80 declare_clippy_lint! {
81 /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
82 /// lint is to catch debugging remnants.
84 /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
85 /// debugging Rust code. It should not be used in user-facing output.
89 /// # let foo = "bar";
90 /// println!("{:?}", foo);
94 "use of `Debug`-based formatting"
97 declare_clippy_lint! {
98 /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
100 /// **Why is this bad?** Using literals as `println!` args is inefficient
101 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
102 /// (i.e., just put the literal in the format string)
104 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
105 /// -- e.g., `println!("{}", env!("FOO"))`.
109 /// println!("{}", "foo");
111 /// use the literal without formatting:
117 "printing a literal with a format string"
120 declare_clippy_lint! {
121 /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
124 /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
126 /// **Known problems:** None.
130 /// # use std::fmt::Write;
131 /// # let mut buf = String::new();
134 /// writeln!(buf, "");
139 pub WRITELN_EMPTY_STRING,
141 "using `writeln!(buf, \"\")` with an empty string"
144 declare_clippy_lint! {
145 /// **What it does:** This lint warns when you use `write!()` with a format
147 /// ends in a newline.
149 /// **Why is this bad?** You should use `writeln!()` instead, which appends the
152 /// **Known problems:** None.
156 /// # use std::fmt::Write;
157 /// # let mut buf = String::new();
158 /// # let name = "World";
161 /// write!(buf, "Hello {}!\n", name);
164 /// writeln!(buf, "Hello {}!", name);
166 pub WRITE_WITH_NEWLINE,
168 "using `write!()` with a format string that ends in a single newline"
171 declare_clippy_lint! {
172 /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
174 /// **Why is this bad?** Using literals as `writeln!` args is inefficient
175 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
176 /// (i.e., just put the literal in the format string)
178 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
179 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
183 /// # use std::fmt::Write;
184 /// # let mut buf = String::new();
187 /// writeln!(buf, "{}", "foo");
190 /// writeln!(buf, "foo");
194 "writing a literal with a format string"
202 impl_lint_pass!(Write => [
204 PRINTLN_EMPTY_STRING,
209 WRITELN_EMPTY_STRING,
213 impl EarlyLintPass for Write {
214 fn check_item(&mut self, _: &EarlyContext<'_>, item: &Item) {
215 if let ItemKind::Impl {
216 of_trait: Some(trait_ref),
220 let trait_name = trait_ref
225 .expect("path has at least one segment")
228 if trait_name == sym!(Debug) {
229 self.in_debug_impl = true;
234 fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &Item) {
235 self.in_debug_impl = false;
238 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &MacCall) {
239 if mac.path == sym!(println) {
240 let filename = cx.sess.source_map().span_to_filename(mac.span());
242 if let FileName::Real(filename) = filename;
243 if let Some(filename) = filename.local_path().file_name();
244 if filename != "build.rs";
246 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`");
249 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
250 if fmt_str.symbol == Symbol::intern("") {
253 PRINTLN_EMPTY_STRING,
255 "using `println!(\"\")`",
257 "println!()".to_string(),
258 Applicability::MachineApplicable,
262 } else if mac.path == sym!(print) {
264 let filename = cx.sess.source_map().span_to_filename(mac.span());
265 if let FileName::Real(filename) = filename;
266 if let Some(filename) = filename.local_path().file_name();
267 if filename != "build.rs";
269 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`");
272 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
273 if check_newlines(&fmt_str) {
278 "using `print!()` with a format string that ends in a single newline",
280 err.multipart_suggestion(
281 "use `println!` instead",
283 (mac.path.span, String::from("println")),
284 (newline_span(&fmt_str), String::new()),
286 Applicability::MachineApplicable,
292 } else if mac.path == sym!(write) {
293 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), true) {
294 if check_newlines(&fmt_str) {
299 "using `write!()` with a format string that ends in a single newline",
301 err.multipart_suggestion(
302 "use `writeln!()` instead",
304 (mac.path.span, String::from("writeln")),
305 (newline_span(&fmt_str), String::new()),
307 Applicability::MachineApplicable,
313 } else if mac.path == sym!(writeln) {
314 if let (Some(fmt_str), expr) = self.check_tts(cx, mac.args.inner_tokens(), true) {
315 if fmt_str.symbol == Symbol::intern("") {
316 let mut applicability = Applicability::MachineApplicable;
317 // FIXME: remove this `#[allow(...)]` once the issue #5822 gets fixed
318 #[allow(clippy::option_if_let_else)]
319 let suggestion = if let Some(e) = expr {
320 snippet_with_applicability(cx, e.span, "v", &mut applicability)
322 applicability = Applicability::HasPlaceholders;
328 WRITELN_EMPTY_STRING,
330 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
332 format!("writeln!({})", suggestion),
341 /// Given a format string that ends in a newline and its span, calculates the span of the
342 /// newline, or the format string itself if the format string consists solely of a newline.
343 fn newline_span(fmtstr: &StrLit) -> Span {
344 let sp = fmtstr.span;
345 let contents = &fmtstr.symbol.as_str();
347 if *contents == r"\n" {
351 let newline_sp_hi = sp.hi()
352 - match fmtstr.style {
353 StrStyle::Cooked => BytePos(1),
354 StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
357 let newline_sp_len = if contents.ends_with('\n') {
359 } else if contents.ends_with(r"\n") {
362 panic!("expected format string to contain a newline");
365 sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi)
369 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
370 /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
371 /// the contents of the string, whether it's a raw string, and the span of the literal in the
372 /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
373 /// `format_str` should be written to.
377 /// Calling this function on
379 /// # use std::fmt::Write;
380 /// # let mut buf = String::new();
381 /// # let something = "something";
382 /// writeln!(buf, "string to write: {}", something);
386 /// (Some("string to write: {}"), Some(buf))
388 #[allow(clippy::too_many_lines)]
389 fn check_tts<'a>(&self, cx: &EarlyContext<'a>, tts: TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
390 use rustc_parse_format::{
391 AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied, FormatSpec, ParseMode, Parser,
395 let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, false, None);
396 let mut expr: Option<Expr> = None;
398 expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
399 Ok(p) => Some(p.into_inner()),
400 Err(_) => return (None, None),
402 // might be `writeln!(foo)`
403 if parser.expect(&token::Comma).map_err(|mut err| err.cancel()).is_err() {
408 let fmtstr = match parser.parse_str_lit() {
409 Ok(fmtstr) => fmtstr,
410 Err(_) => return (None, expr),
412 let tmp = fmtstr.symbol.as_str();
413 let mut args = vec![];
414 let mut fmt_parser = Parser::new(&tmp, None, None, false, ParseMode::Format);
415 while let Some(piece) = fmt_parser.next() {
416 if !fmt_parser.errors.is_empty() {
419 if let Piece::NextArgument(arg) = piece {
420 if !self.in_debug_impl && arg.format.ty == "?" {
421 // FIXME: modify rustc's fmt string parser to give us the current span
422 span_lint(cx, USE_DEBUG, parser.prev_token.span, "use of `Debug`-based formatting");
427 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
430 const SIMPLE: FormatSpec<'_> = FormatSpec {
434 precision: CountImplied,
435 precision_span: None,
441 if !parser.eat(&token::Comma) {
442 return (Some(fmtstr), expr);
444 let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
447 return (Some(fmtstr), None);
449 match &token_expr.kind {
450 ExprKind::Lit(_) => {
451 let mut all_simple = true;
452 let mut seen = false;
455 ArgumentImplicitlyIs(n) | ArgumentIs(n) => {
457 all_simple &= arg.format == SIMPLE;
461 ArgumentNamed(_) => {},
464 if all_simple && seen {
465 span_lint(cx, lint, token_expr.span, "literal with an empty format string");
469 ExprKind::Assign(lhs, rhs, _) => {
470 if let ExprKind::Lit(_) = rhs.kind {
471 if let ExprKind::Path(_, p) = &lhs.kind {
472 let mut all_simple = true;
473 let mut seen = false;
476 ArgumentImplicitlyIs(_) | ArgumentIs(_) => {},
477 ArgumentNamed(name) => {
480 all_simple &= arg.format == SIMPLE;
485 if all_simple && seen {
486 span_lint(cx, lint, rhs.span, "literal with an empty format string");
497 /// Checks if the format string contains a single newline that terminates it.
499 /// Literal and escaped newlines are both checked (only literal for raw strings).
500 fn check_newlines(fmtstr: &StrLit) -> bool {
501 let mut has_internal_newline = false;
502 let mut last_was_cr = false;
503 let mut should_lint = false;
505 let contents = &fmtstr.symbol.as_str();
507 let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
510 if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
513 last_was_cr = c == '\r';
515 has_internal_newline = true;
521 StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb),
522 StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb),