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, LitKind, 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::{sym, BytePos, Span, Symbol};
16 declare_clippy_lint! {
17 /// **What it does:** This lint warns when you use `println!("")` to
20 /// **Why is this bad?** You should use `println!()`, which is simpler.
22 /// **Known problems:** None.
32 pub PRINTLN_EMPTY_STRING,
34 "using `println!(\"\")` with an empty string"
37 declare_clippy_lint! {
38 /// **What it does:** This lint warns when you use `print!()` with a format
39 /// string that ends in a newline.
41 /// **Why is this bad?** You should use `println!()` instead, which appends the
44 /// **Known problems:** None.
48 /// # let name = "World";
49 /// print!("Hello {}!\n", name);
51 /// use println!() instead
53 /// # let name = "World";
54 /// println!("Hello {}!", name);
56 pub PRINT_WITH_NEWLINE,
58 "using `print!()` with a format string that ends in a single newline"
61 declare_clippy_lint! {
62 /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
63 /// is to catch debugging remnants.
65 /// **Why is this bad?** People often print on *stdout* while debugging an
66 /// application and might forget to remove those prints afterward.
68 /// **Known problems:** Only catches `print!` and `println!` calls.
72 /// println!("Hello world!");
79 declare_clippy_lint! {
80 /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
81 /// lint is to catch debugging remnants.
83 /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
84 /// debugging Rust code. It should not be used in user-facing output.
88 /// # let foo = "bar";
89 /// println!("{:?}", foo);
93 "use of `Debug`-based formatting"
96 declare_clippy_lint! {
97 /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
99 /// **Why is this bad?** Using literals as `println!` args is inefficient
100 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
101 /// (i.e., just put the literal in the format string)
103 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
104 /// -- e.g., `println!("{}", env!("FOO"))`.
108 /// println!("{}", "foo");
110 /// use the literal without formatting:
116 "printing a literal with a format string"
119 declare_clippy_lint! {
120 /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
123 /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
125 /// **Known problems:** None.
129 /// # use std::fmt::Write;
130 /// # let mut buf = String::new();
133 /// writeln!(buf, "");
138 pub WRITELN_EMPTY_STRING,
140 "using `writeln!(buf, \"\")` with an empty string"
143 declare_clippy_lint! {
144 /// **What it does:** This lint warns when you use `write!()` with a format
146 /// ends in a newline.
148 /// **Why is this bad?** You should use `writeln!()` instead, which appends the
151 /// **Known problems:** None.
155 /// # use std::fmt::Write;
156 /// # let mut buf = String::new();
157 /// # let name = "World";
160 /// write!(buf, "Hello {}!\n", name);
163 /// writeln!(buf, "Hello {}!", name);
165 pub WRITE_WITH_NEWLINE,
167 "using `write!()` with a format string that ends in a single newline"
170 declare_clippy_lint! {
171 /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
173 /// **Why is this bad?** Using literals as `writeln!` args is inefficient
174 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
175 /// (i.e., just put the literal in the format string)
177 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
178 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
182 /// # use std::fmt::Write;
183 /// # let mut buf = String::new();
186 /// writeln!(buf, "{}", "foo");
189 /// writeln!(buf, "foo");
193 "writing a literal with a format string"
201 impl_lint_pass!(Write => [
203 PRINTLN_EMPTY_STRING,
208 WRITELN_EMPTY_STRING,
212 impl EarlyLintPass for Write {
213 fn check_item(&mut self, _: &EarlyContext<'_>, item: &Item) {
214 if let ItemKind::Impl {
215 of_trait: Some(trait_ref),
219 let trait_name = trait_ref
224 .expect("path has at least one segment")
227 if trait_name == sym::Debug {
228 self.in_debug_impl = true;
233 fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &Item) {
234 self.in_debug_impl = false;
237 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &MacCall) {
238 fn is_build_script(cx: &EarlyContext<'_>) -> bool {
239 // Cargo sets the crate name for build scripts to `build_script_build`
244 .map_or(false, |crate_name| crate_name == "build_script_build")
247 if mac.path == sym!(println) {
248 if !is_build_script(cx) {
249 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`");
251 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
252 if fmt_str.symbol == Symbol::intern("") {
255 PRINTLN_EMPTY_STRING,
257 "using `println!(\"\")`",
259 "println!()".to_string(),
260 Applicability::MachineApplicable,
264 } else if mac.path == sym!(print) {
265 if !is_build_script(cx) {
266 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`");
268 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
269 if check_newlines(&fmt_str) {
274 "using `print!()` with a format string that ends in a single newline",
276 err.multipart_suggestion(
277 "use `println!` instead",
279 (mac.path.span, String::from("println")),
280 (newline_span(&fmt_str), String::new()),
282 Applicability::MachineApplicable,
288 } else if mac.path == sym!(write) {
289 if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), true) {
290 if check_newlines(&fmt_str) {
295 "using `write!()` with a format string that ends in a single newline",
297 err.multipart_suggestion(
298 "use `writeln!()` instead",
300 (mac.path.span, String::from("writeln")),
301 (newline_span(&fmt_str), String::new()),
303 Applicability::MachineApplicable,
309 } else if mac.path == sym!(writeln) {
310 if let (Some(fmt_str), expr) = self.check_tts(cx, mac.args.inner_tokens(), true) {
311 if fmt_str.symbol == Symbol::intern("") {
312 let mut applicability = Applicability::MachineApplicable;
313 // FIXME: remove this `#[allow(...)]` once the issue #5822 gets fixed
314 #[allow(clippy::option_if_let_else)]
315 let suggestion = if let Some(e) = expr {
316 snippet_with_applicability(cx, e.span, "v", &mut applicability)
318 applicability = Applicability::HasPlaceholders;
324 WRITELN_EMPTY_STRING,
326 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
328 format!("writeln!({})", suggestion),
337 /// Given a format string that ends in a newline and its span, calculates the span of the
338 /// newline, or the format string itself if the format string consists solely of a newline.
339 fn newline_span(fmtstr: &StrLit) -> Span {
340 let sp = fmtstr.span;
341 let contents = &fmtstr.symbol.as_str();
343 if *contents == r"\n" {
347 let newline_sp_hi = sp.hi()
348 - match fmtstr.style {
349 StrStyle::Cooked => BytePos(1),
350 StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
353 let newline_sp_len = if contents.ends_with('\n') {
355 } else if contents.ends_with(r"\n") {
358 panic!("expected format string to contain a newline");
361 sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi)
365 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
366 /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
367 /// the contents of the string, whether it's a raw string, and the span of the literal in the
368 /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
369 /// `format_str` should be written to.
373 /// Calling this function on
375 /// # use std::fmt::Write;
376 /// # let mut buf = String::new();
377 /// # let something = "something";
378 /// writeln!(buf, "string to write: {}", something);
382 /// (Some("string to write: {}"), Some(buf))
384 #[allow(clippy::too_many_lines)]
385 fn check_tts<'a>(&self, cx: &EarlyContext<'a>, tts: TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
386 use rustc_parse_format::{
387 AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied, FormatSpec, ParseMode, Parser,
391 let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, false, None);
392 let mut expr: Option<Expr> = None;
394 expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
395 Ok(p) => Some(p.into_inner()),
396 Err(_) => return (None, None),
398 // might be `writeln!(foo)`
399 if parser.expect(&token::Comma).map_err(|mut err| err.cancel()).is_err() {
404 let fmtstr = match parser.parse_str_lit() {
405 Ok(fmtstr) => fmtstr,
406 Err(_) => return (None, expr),
408 let tmp = fmtstr.symbol.as_str();
409 let mut args = vec![];
410 let mut fmt_parser = Parser::new(&tmp, None, None, false, ParseMode::Format);
411 while let Some(piece) = fmt_parser.next() {
412 if !fmt_parser.errors.is_empty() {
415 if let Piece::NextArgument(arg) = piece {
416 if !self.in_debug_impl && arg.format.ty == "?" {
417 // FIXME: modify rustc's fmt string parser to give us the current span
418 span_lint(cx, USE_DEBUG, parser.prev_token.span, "use of `Debug`-based formatting");
423 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
426 const SIMPLE: FormatSpec<'_> = FormatSpec {
430 precision: CountImplied,
431 precision_span: None,
437 if !parser.eat(&token::Comma) {
438 return (Some(fmtstr), expr);
440 let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
443 return (Some(fmtstr), None);
445 match &token_expr.kind {
448 LitKind::Int(_, _) | LitKind::Float(_, _) => false,
452 let mut all_simple = true;
453 let mut seen = false;
456 ArgumentImplicitlyIs(n) | ArgumentIs(n) => {
458 all_simple &= arg.format == SIMPLE;
462 ArgumentNamed(_) => {},
465 if all_simple && seen {
466 span_lint(cx, lint, token_expr.span, "literal with an empty format string");
470 ExprKind::Assign(lhs, rhs, _) => {
472 if let ExprKind::Lit(ref lit) = rhs.kind;
473 if matches!(lit.kind, LitKind::Int(..) | LitKind::Float(..));
474 if let ExprKind::Path(_, p) = &lhs.kind;
476 let mut all_simple = true;
477 let mut seen = false;
480 ArgumentImplicitlyIs(_) | ArgumentIs(_) => {},
481 ArgumentNamed(name) => {
484 all_simple &= arg.format == SIMPLE;
489 if all_simple && seen {
490 span_lint(cx, lint, rhs.span, "literal with an empty format string");
501 /// Checks if the format string contains a single newline that terminates it.
503 /// Literal and escaped newlines are both checked (only literal for raw strings).
504 fn check_newlines(fmtstr: &StrLit) -> bool {
505 let mut has_internal_newline = false;
506 let mut last_was_cr = false;
507 let mut should_lint = false;
509 let contents = &fmtstr.symbol.as_str();
511 let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
514 if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
517 last_was_cr = c == '\r';
519 has_internal_newline = true;
525 StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb),
526 StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb),