2 use rustc::{declare_lint, lint_array};
4 use syntax::tokenstream::{ThinTokenStream, TokenStream};
5 use syntax::parse::{token, parser};
6 use crate::utils::{span_lint, span_lint_and_sugg};
8 /// **What it does:** This lint warns when you use `println!("")` to
11 /// **Why is this bad?** You should use `println!()`, which is simpler.
13 /// **Known problems:** None.
19 declare_clippy_lint! {
20 pub PRINTLN_EMPTY_STRING,
22 "using `println!(\"\")` with an empty string"
25 /// **What it does:** This lint warns when you use `print!()` with a format
27 /// ends in a newline.
29 /// **Why is this bad?** You should use `println!()` instead, which appends the
32 /// **Known problems:** None.
36 /// print!("Hello {}!\n", name);
38 /// use println!() instead
40 /// println!("Hello {}!", name);
42 declare_clippy_lint! {
43 pub PRINT_WITH_NEWLINE,
45 "using `print!()` with a format string that ends in a single newline"
48 /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
49 /// is to catch debugging remnants.
51 /// **Why is this bad?** People often print on *stdout* while debugging an
52 /// application and might forget to remove those prints afterward.
54 /// **Known problems:** Only catches `print!` and `println!` calls.
58 /// println!("Hello world!");
60 declare_clippy_lint! {
66 /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
67 /// lint is to catch debugging remnants.
69 /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
70 /// debugging Rust code. It should not be used in in user-facing output.
74 /// println!("{:?}", foo);
76 declare_clippy_lint! {
79 "use of `Debug`-based formatting"
82 /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
84 /// **Why is this bad?** Using literals as `println!` args is inefficient
85 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
86 /// (i.e., just put the literal in the format string)
88 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
89 /// -- e.g., `println!("{}", env!("FOO"))`.
93 /// println!("{}", "foo");
95 /// use the literal without formatting:
99 declare_clippy_lint! {
102 "printing a literal with a format string"
105 /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
108 /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
110 /// **Known problems:** None.
116 declare_clippy_lint! {
117 pub WRITELN_EMPTY_STRING,
119 "using `writeln!(\"\")` with an empty string"
122 /// **What it does:** This lint warns when you use `write!()` with a format
124 /// ends in a newline.
126 /// **Why is this bad?** You should use `writeln!()` instead, which appends the
129 /// **Known problems:** None.
133 /// write!(buf, "Hello {}!\n", name);
135 declare_clippy_lint! {
136 pub WRITE_WITH_NEWLINE,
138 "using `write!()` with a format string that ends in a single newline"
141 /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
143 /// **Why is this bad?** Using literals as `writeln!` args is inefficient
144 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
145 /// (i.e., just put the literal in the format string)
147 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
148 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
152 /// writeln!(buf, "{}", "foo");
154 declare_clippy_lint! {
157 "writing a literal with a format string"
160 #[derive(Copy, Clone, Debug)]
163 impl LintPass for Pass {
164 fn get_lints(&self) -> LintArray {
167 PRINTLN_EMPTY_STRING,
172 WRITELN_EMPTY_STRING,
178 impl EarlyLintPass for Pass {
179 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &Mac) {
180 if mac.node.path == "println" {
181 span_lint(cx, PRINT_STDOUT, mac.span, "use of `println!`");
182 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, false) {
186 PRINTLN_EMPTY_STRING,
188 "using `println!(\"\")`",
190 "println!()".to_string(),
194 } else if mac.node.path == "print" {
195 span_lint(cx, PRINT_STDOUT, mac.span, "use of `print!`");
196 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, false) {
197 if fmtstr.ends_with("\\n") && !fmtstr.ends_with("\\n\\n") {
198 span_lint(cx, PRINT_WITH_NEWLINE, mac.span,
199 "using `print!()` with a format string that ends in a \
200 single newline, consider using `println!()` instead");
203 } else if mac.node.path == "write" {
204 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, true) {
205 if fmtstr.ends_with("\\n") && !fmtstr.ends_with("\\n\\n") {
206 span_lint(cx, WRITE_WITH_NEWLINE, mac.span,
207 "using `write!()` with a format string that ends in a \
208 single newline, consider using `writeln!()` instead");
211 } else if mac.node.path == "writeln" {
212 if let Some(fmtstr) = check_tts(cx, &mac.node.tts, true) {
216 WRITELN_EMPTY_STRING,
218 "using `writeln!(v, \"\")`",
220 "writeln!(v)".to_string(),
228 fn check_tts<'a>(cx: &EarlyContext<'a>, tts: &ThinTokenStream, is_write: bool) -> Option<String> {
229 let tts = TokenStream::from(tts.clone());
230 let mut parser = parser::Parser::new(
238 // skip the initial write target
239 parser.parse_expr().map_err(|mut err| err.cancel()).ok()?;
240 // might be `writeln!(foo)`
241 parser.expect(&token::Comma).map_err(|mut err| err.cancel()).ok()?;
243 let fmtstr = parser.parse_str().map_err(|mut err| err.cancel()).ok()?.0.to_string();
245 let tmp = fmtstr.clone();
246 let mut args = vec![];
247 let mut fmt_parser = Parser::new(&tmp, None);
248 while let Some(piece) = fmt_parser.next() {
249 if !fmt_parser.errors.is_empty() {
252 if let Piece::NextArgument(arg) = piece {
253 if arg.format.ty == "?" {
254 // FIXME: modify rustc's fmt string parser to give us the current span
255 span_lint(cx, USE_DEBUG, parser.prev_span, "use of `Debug`-based formatting");
260 let lint = if is_write {
267 if !parser.eat(&token::Comma) {
268 assert!(parser.eat(&token::Eof));
271 let expr = parser.parse_expr().map_err(|mut err| err.cancel()).ok()?;
272 const SIMPLE: FormatSpec<'_> = FormatSpec {
276 precision: CountImplied,
281 ExprKind::Lit(_) => {
282 let mut all_simple = true;
283 let mut seen = false;
286 | ArgumentImplicitlyIs(n)
289 all_simple &= arg.format == SIMPLE;
292 ArgumentNamed(_) => {},
295 if all_simple && seen {
296 span_lint(cx, lint, expr.span, "literal with an empty format string");
300 ExprKind::Assign(lhs, rhs) => {
301 if let ExprKind::Lit(_) = rhs.node {
302 if let ExprKind::Path(_, p) = &lhs.node {
303 let mut all_simple = true;
304 let mut seen = false;
307 | ArgumentImplicitlyIs(_)
310 ArgumentNamed(name) => if *p == name {
312 all_simple &= arg.format == SIMPLE;
316 if all_simple && seen {
317 span_lint(cx, lint, rhs.span, "literal with an empty format string");