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