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