4 use crate::utils::{snippet_with_applicability, span_lint, span_lint_and_sugg, span_lint_and_then};
5 use rustc::declare_lint_pass;
6 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
7 use rustc_errors::Applicability;
8 use rustc_lexer::unescape::{self, EscapeError};
9 use rustc_parse::parser;
10 use rustc_session::declare_tool_lint;
12 use syntax::symbol::Symbol;
14 use syntax::tokenstream::TokenStream;
15 use syntax_pos::{BytePos, 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.
29 pub PRINTLN_EMPTY_STRING,
31 "using `println!(\"\")` with an empty string"
34 declare_clippy_lint! {
35 /// **What it does:** This lint warns when you use `print!()` with a format
37 /// ends in a newline.
39 /// **Why is this bad?** You should use `println!()` instead, which appends the
42 /// **Known problems:** None.
46 /// # let name = "World";
47 /// print!("Hello {}!\n", name);
49 /// use println!() instead
51 /// # let name = "World";
52 /// println!("Hello {}!", name);
54 pub PRINT_WITH_NEWLINE,
56 "using `print!()` with a format string that ends in a single newline"
59 declare_clippy_lint! {
60 /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
61 /// is to catch debugging remnants.
63 /// **Why is this bad?** People often print on *stdout* while debugging an
64 /// application and might forget to remove those prints afterward.
66 /// **Known problems:** Only catches `print!` and `println!` calls.
70 /// println!("Hello world!");
77 declare_clippy_lint! {
78 /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
79 /// lint is to catch debugging remnants.
81 /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
82 /// debugging Rust code. It should not be used in user-facing output.
86 /// # let foo = "bar";
87 /// println!("{:?}", foo);
91 "use of `Debug`-based formatting"
94 declare_clippy_lint! {
95 /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
97 /// **Why is this bad?** Using literals as `println!` args is inefficient
98 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
99 /// (i.e., just put the literal in the format string)
101 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
102 /// -- e.g., `println!("{}", env!("FOO"))`.
106 /// println!("{}", "foo");
108 /// use the literal without formatting:
114 "printing a literal with a format string"
117 declare_clippy_lint! {
118 /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
121 /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
123 /// **Known problems:** None.
127 /// # use std::fmt::Write;
128 /// # let mut buf = String::new();
129 /// writeln!(buf, "");
131 pub WRITELN_EMPTY_STRING,
133 "using `writeln!(buf, \"\")` with an empty string"
136 declare_clippy_lint! {
137 /// **What it does:** This lint warns when you use `write!()` with a format
139 /// ends in a newline.
141 /// **Why is this bad?** You should use `writeln!()` instead, which appends the
144 /// **Known problems:** None.
148 /// # use std::fmt::Write;
149 /// # let mut buf = String::new();
150 /// # let name = "World";
151 /// write!(buf, "Hello {}!\n", name);
153 pub WRITE_WITH_NEWLINE,
155 "using `write!()` with a format string that ends in a single newline"
158 declare_clippy_lint! {
159 /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
161 /// **Why is this bad?** Using literals as `writeln!` args is inefficient
162 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
163 /// (i.e., just put the literal in the format string)
165 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
166 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
170 /// # use std::fmt::Write;
171 /// # let mut buf = String::new();
172 /// writeln!(buf, "{}", "foo");
176 "writing a literal with a format string"
179 declare_lint_pass!(Write => [
181 PRINTLN_EMPTY_STRING,
186 WRITELN_EMPTY_STRING,
190 impl EarlyLintPass for Write {
191 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &Mac) {
192 if mac.path == sym!(println) {
193 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`");
194 if let (Some(fmt_str), _) = check_tts(cx, &mac.args.inner_tokens(), false) {
195 if fmt_str.symbol == Symbol::intern("") {
198 PRINTLN_EMPTY_STRING,
200 "using `println!(\"\")`",
202 "println!()".to_string(),
203 Applicability::MachineApplicable,
207 } else if mac.path == sym!(print) {
208 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`");
209 if let (Some(fmt_str), _) = check_tts(cx, &mac.args.inner_tokens(), false) {
210 if check_newlines(&fmt_str) {
215 "using `print!()` with a format string that ends in a single newline",
217 err.multipart_suggestion(
218 "use `println!` instead",
220 (mac.path.span, String::from("println")),
221 (newline_span(&fmt_str), String::new()),
223 Applicability::MachineApplicable,
229 } else if mac.path == sym!(write) {
230 if let (Some(fmt_str), _) = check_tts(cx, &mac.args.inner_tokens(), true) {
231 if check_newlines(&fmt_str) {
236 "using `write!()` with a format string that ends in a single newline",
238 err.multipart_suggestion(
239 "use `writeln!()` instead",
241 (mac.path.span, String::from("writeln")),
242 (newline_span(&fmt_str), String::new()),
244 Applicability::MachineApplicable,
250 } else if mac.path == sym!(writeln) {
251 if let (Some(fmt_str), expr) = check_tts(cx, &mac.args.inner_tokens(), true) {
252 if fmt_str.symbol == Symbol::intern("") {
253 let mut applicability = Applicability::MachineApplicable;
254 let suggestion = expr.map_or_else(
256 applicability = Applicability::HasPlaceholders;
259 move |expr| snippet_with_applicability(cx, expr.span, "v", &mut applicability),
264 WRITELN_EMPTY_STRING,
266 format!("using `writeln!({}, \"\")`", suggestion).as_str(),
268 format!("writeln!({})", suggestion),
277 /// Given a format string that ends in a newline and its span, calculates the span of the
279 fn newline_span(fmtstr: &StrLit) -> Span {
280 let sp = fmtstr.span;
281 let contents = &fmtstr.symbol.as_str();
283 let newline_sp_hi = sp.hi()
284 - match fmtstr.style {
285 StrStyle::Cooked => BytePos(1),
286 StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
289 let newline_sp_len = if contents.ends_with('\n') {
291 } else if contents.ends_with(r"\n") {
294 panic!("expected format string to contain a newline");
297 sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi)
300 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
301 /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
302 /// the contents of the string, whether it's a raw string, and the span of the literal in the
303 /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
304 /// `format_str` should be written to.
308 /// Calling this function on
310 /// # use std::fmt::Write;
311 /// # let mut buf = String::new();
312 /// # let something = "something";
313 /// writeln!(buf, "string to write: {}", something);
317 /// (Some("string to write: {}"), Some(buf))
319 #[allow(clippy::too_many_lines)]
320 fn check_tts<'a>(cx: &EarlyContext<'a>, tts: &TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
322 let tts = tts.clone();
324 let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, None, false, false, None);
325 let mut expr: Option<Expr> = None;
327 expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
328 Ok(p) => Some(p.into_inner()),
329 Err(_) => return (None, None),
331 // might be `writeln!(foo)`
332 if parser.expect(&token::Comma).map_err(|mut err| err.cancel()).is_err() {
337 let fmtstr = match parser.parse_str_lit() {
338 Ok(fmtstr) => fmtstr,
339 Err(_) => return (None, expr),
341 let tmp = fmtstr.symbol.as_str();
342 let mut args = vec![];
343 let mut fmt_parser = Parser::new(&tmp, None, Vec::new(), false);
344 while let Some(piece) = fmt_parser.next() {
345 if !fmt_parser.errors.is_empty() {
348 if let Piece::NextArgument(arg) = piece {
349 if arg.format.ty == "?" {
350 // FIXME: modify rustc's fmt string parser to give us the current span
351 span_lint(cx, USE_DEBUG, parser.prev_span, "use of `Debug`-based formatting");
356 let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
359 const SIMPLE: FormatSpec<'_> = FormatSpec {
363 precision: CountImplied,
364 precision_span: None,
370 if !parser.eat(&token::Comma) {
371 return (Some(fmtstr), expr);
373 let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
376 return (Some(fmtstr), None);
378 match &token_expr.kind {
379 ExprKind::Lit(_) => {
380 let mut all_simple = true;
381 let mut seen = false;
384 ArgumentImplicitlyIs(n) | ArgumentIs(n) => {
386 all_simple &= arg.format == SIMPLE;
390 ArgumentNamed(_) => {},
393 if all_simple && seen {
394 span_lint(cx, lint, token_expr.span, "literal with an empty format string");
398 ExprKind::Assign(lhs, rhs) => {
399 if let ExprKind::Lit(_) = rhs.kind {
400 if let ExprKind::Path(_, p) = &lhs.kind {
401 let mut all_simple = true;
402 let mut seen = false;
405 ArgumentImplicitlyIs(_) | ArgumentIs(_) => {},
406 ArgumentNamed(name) => {
409 all_simple &= arg.format == SIMPLE;
414 if all_simple && seen {
415 span_lint(cx, lint, rhs.span, "literal with an empty format string");
425 /// Checks if the format string contains a single newline that terminates it.
427 /// Literal and escaped newlines are both checked (only literal for raw strings).
428 fn check_newlines(fmtstr: &StrLit) -> bool {
429 let mut has_internal_newline = false;
430 let mut last_was_cr = false;
431 let mut should_lint = false;
433 let contents = &fmtstr.symbol.as_str();
435 let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
438 if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
441 last_was_cr = c == '\r';
443 has_internal_newline = true;
449 StrStyle::Cooked => unescape::unescape_str(contents, &mut cb),
450 StrStyle::Raw(_) => unescape::unescape_raw_str(contents, &mut cb),