]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/write.rs
Merge pull request #3285 from devonhollowood/pedantic-dogfood-items-after-statements
[rust.git] / clippy_lints / src / write.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 use crate::utils::{snippet, span_lint, span_lint_and_sugg};
12 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use std::borrow::Cow;
15 use crate::syntax::ast::*;
16 use crate::syntax::parse::{parser, token};
17 use crate::syntax::tokenstream::{ThinTokenStream, TokenStream};
18
19 /// **What it does:** This lint warns when you use `println!("")` to
20 /// print a newline.
21 ///
22 /// **Why is this bad?** You should use `println!()`, which is simpler.
23 ///
24 /// **Known problems:** None.
25 ///
26 /// **Example:**
27 /// ```rust
28 /// println!("");
29 /// ```
30 declare_clippy_lint! {
31     pub PRINTLN_EMPTY_STRING,
32     style,
33     "using `println!(\"\")` with an empty string"
34 }
35
36 /// **What it does:** This lint warns when you use `print!()` with a format
37 /// string that
38 /// ends in a newline.
39 ///
40 /// **Why is this bad?** You should use `println!()` instead, which appends the
41 /// newline.
42 ///
43 /// **Known problems:** None.
44 ///
45 /// **Example:**
46 /// ```rust
47 /// print!("Hello {}!\n", name);
48 /// ```
49 /// use println!() instead
50 /// ```rust
51 /// println!("Hello {}!", name);
52 /// ```
53 declare_clippy_lint! {
54     pub PRINT_WITH_NEWLINE,
55     style,
56     "using `print!()` with a format string that ends in a single newline"
57 }
58
59 /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
60 /// is to catch debugging remnants.
61 ///
62 /// **Why is this bad?** People often print on *stdout* while debugging an
63 /// application and might forget to remove those prints afterward.
64 ///
65 /// **Known problems:** Only catches `print!` and `println!` calls.
66 ///
67 /// **Example:**
68 /// ```rust
69 /// println!("Hello world!");
70 /// ```
71 declare_clippy_lint! {
72     pub PRINT_STDOUT,
73     restriction,
74     "printing on stdout"
75 }
76
77 /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
78 /// lint is to catch debugging remnants.
79 ///
80 /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
81 /// debugging Rust code. It should not be used in in user-facing output.
82 ///
83 /// **Example:**
84 /// ```rust
85 /// println!("{:?}", foo);
86 /// ```
87 declare_clippy_lint! {
88     pub USE_DEBUG,
89     restriction,
90     "use of `Debug`-based formatting"
91 }
92
93 /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
94 ///
95 /// **Why is this bad?** Using literals as `println!` args is inefficient
96 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
97 /// (i.e., just put the literal in the format string)
98 ///
99 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
100 /// -- e.g., `println!("{}", env!("FOO"))`.
101 ///
102 /// **Example:**
103 /// ```rust
104 /// println!("{}", "foo");
105 /// ```
106 /// use the literal without formatting:
107 /// ```rust
108 /// println!("foo");
109 /// ```
110 declare_clippy_lint! {
111     pub PRINT_LITERAL,
112     style,
113     "printing a literal with a format string"
114 }
115
116 /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
117 /// print a newline.
118 ///
119 /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
120 ///
121 /// **Known problems:** None.
122 ///
123 /// **Example:**
124 /// ```rust
125 /// writeln!("");
126 /// ```
127 declare_clippy_lint! {
128     pub WRITELN_EMPTY_STRING,
129     style,
130     "using `writeln!(\"\")` with an empty string"
131 }
132
133 /// **What it does:** This lint warns when you use `write!()` with a format
134 /// string that
135 /// ends in a newline.
136 ///
137 /// **Why is this bad?** You should use `writeln!()` instead, which appends the
138 /// newline.
139 ///
140 /// **Known problems:** None.
141 ///
142 /// **Example:**
143 /// ```rust
144 /// write!(buf, "Hello {}!\n", name);
145 /// ```
146 declare_clippy_lint! {
147     pub WRITE_WITH_NEWLINE,
148     style,
149     "using `write!()` with a format string that ends in a single newline"
150 }
151
152 /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
153 ///
154 /// **Why is this bad?** Using literals as `writeln!` args is inefficient
155 /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
156 /// (i.e., just put the literal in the format string)
157 ///
158 /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
159 /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
160 ///
161 /// **Example:**
162 /// ```rust
163 /// writeln!(buf, "{}", "foo");
164 /// ```
165 declare_clippy_lint! {
166     pub WRITE_LITERAL,
167     style,
168     "writing a literal with a format string"
169 }
170
171 #[derive(Copy, Clone, Debug)]
172 pub struct Pass;
173
174 impl LintPass for Pass {
175     fn get_lints(&self) -> LintArray {
176         lint_array!(
177             PRINT_WITH_NEWLINE,
178             PRINTLN_EMPTY_STRING,
179             PRINT_STDOUT,
180             USE_DEBUG,
181             PRINT_LITERAL,
182             WRITE_WITH_NEWLINE,
183             WRITELN_EMPTY_STRING,
184             WRITE_LITERAL
185         )
186     }
187 }
188
189 impl EarlyLintPass for Pass {
190     fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &Mac) {
191         if mac.node.path == "println" {
192             span_lint(cx, PRINT_STDOUT, mac.span, "use of `println!`");
193             if let Some(fmtstr) = check_tts(cx, &mac.node.tts, false).0 {
194                 if fmtstr == "" {
195                     span_lint_and_sugg(
196                         cx,
197                         PRINTLN_EMPTY_STRING,
198                         mac.span,
199                         "using `println!(\"\")`",
200                         "replace it with",
201                         "println!()".to_string(),
202                     );
203                 }
204             }
205         } else if mac.node.path == "print" {
206             span_lint(cx, PRINT_STDOUT, mac.span, "use of `print!`");
207             if let Some(fmtstr) = check_tts(cx, &mac.node.tts, false).0 {
208                 if fmtstr.ends_with("\\n") &&
209                    // don't warn about strings with several `\n`s (#3126)
210                    fmtstr.matches("\\n").count() == 1
211                 {
212                     span_lint(
213                         cx,
214                         PRINT_WITH_NEWLINE,
215                         mac.span,
216                         "using `print!()` with a format string that ends in a \
217                          single newline, consider using `println!()` instead",
218                     );
219                 }
220             }
221         } else if mac.node.path == "write" {
222             if let Some(fmtstr) = check_tts(cx, &mac.node.tts, true).0 {
223                 if fmtstr.ends_with("\\n") &&
224                    // don't warn about strings with several `\n`s (#3126)
225                    fmtstr.matches("\\n").count() == 1
226                 {
227                     span_lint(
228                         cx,
229                         WRITE_WITH_NEWLINE,
230                         mac.span,
231                         "using `write!()` with a format string that ends in a \
232                          single newline, consider using `writeln!()` instead",
233                     );
234                 }
235             }
236         } else if mac.node.path == "writeln" {
237             let check_tts = check_tts(cx, &mac.node.tts, true);
238             if let Some(fmtstr) = check_tts.0 {
239                 if fmtstr == "" {
240                     let suggestion = check_tts
241                         .1
242                         .map_or(Cow::Borrowed("v"), |expr| snippet(cx, expr.span, "v"));
243
244                     span_lint_and_sugg(
245                         cx,
246                         WRITELN_EMPTY_STRING,
247                         mac.span,
248                         format!("using `writeln!({}, \"\")`", suggestion).as_str(),
249                         "replace it with",
250                         format!("writeln!({})", suggestion),
251                     );
252                 }
253             }
254         }
255     }
256 }
257
258 fn check_tts<'a>(cx: &EarlyContext<'a>, tts: &ThinTokenStream, is_write: bool) -> (Option<String>, Option<Expr>) {
259     use crate::fmt_macros::*;
260     let tts = TokenStream::from(tts.clone());
261     let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, None, false, false);
262     let mut expr: Option<Expr> = None;
263     if is_write {
264         expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
265             Ok(p) => Some(p.into_inner()),
266             Err(_) => return (None, None),
267         };
268         // might be `writeln!(foo)`
269         if parser.expect(&token::Comma).map_err(|mut err| err.cancel()).is_err() {
270             return (None, expr);
271         }
272     }
273
274     let fmtstr = match parser.parse_str().map_err(|mut err| err.cancel()) {
275         Ok(token) => token.0.to_string(),
276         Err(_) => return (None, expr),
277     };
278     let tmp = fmtstr.clone();
279     let mut args = vec![];
280     let mut fmt_parser = Parser::new(&tmp, None);
281     while let Some(piece) = fmt_parser.next() {
282         if !fmt_parser.errors.is_empty() {
283             return (None, expr);
284         }
285         if let Piece::NextArgument(arg) = piece {
286             if arg.format.ty == "?" {
287                 // FIXME: modify rustc's fmt string parser to give us the current span
288                 span_lint(cx, USE_DEBUG, parser.prev_span, "use of `Debug`-based formatting");
289             }
290             args.push(arg);
291         }
292     }
293     let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
294     let mut idx = 0;
295     loop {
296         const SIMPLE: FormatSpec<'_> = FormatSpec {
297             fill: None,
298             align: AlignUnknown,
299             flags: 0,
300             precision: CountImplied,
301             width: CountImplied,
302             ty: "",
303         };
304         if !parser.eat(&token::Comma) {
305             return (Some(fmtstr), expr);
306         }
307         let token_expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
308             Ok(expr) => expr,
309             Err(_) => return (Some(fmtstr), None),
310         };
311         match &token_expr.node {
312             ExprKind::Lit(_) => {
313                 let mut all_simple = true;
314                 let mut seen = false;
315                 for arg in &args {
316                     match arg.position {
317                         ArgumentImplicitlyIs(n) | ArgumentIs(n) => if n == idx {
318                             all_simple &= arg.format == SIMPLE;
319                             seen = true;
320                         },
321                         ArgumentNamed(_) => {},
322                     }
323                 }
324                 if all_simple && seen {
325                     span_lint(cx, lint, token_expr.span, "literal with an empty format string");
326                 }
327                 idx += 1;
328             },
329             ExprKind::Assign(lhs, rhs) => {
330                 if let ExprKind::Lit(_) = rhs.node {
331                     if let ExprKind::Path(_, p) = &lhs.node {
332                         let mut all_simple = true;
333                         let mut seen = false;
334                         for arg in &args {
335                             match arg.position {
336                                 ArgumentImplicitlyIs(_) | ArgumentIs(_) => {},
337                                 ArgumentNamed(name) => if *p == name {
338                                     seen = true;
339                                     all_simple &= arg.format == SIMPLE;
340                                 },
341                             }
342                         }
343                         if all_simple && seen {
344                             span_lint(cx, lint, rhs.span, "literal with an empty format string");
345                         }
346                     }
347                 }
348             },
349             _ => idx += 1,
350         }
351     }
352 }