]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/write.rs
Auto merge of #4487 - JohnTitor:deref-addrof-external-macro, r=flip1995
[rust.git] / clippy_lints / src / write.rs
1 use crate::utils::{snippet_with_applicability, span_lint, span_lint_and_sugg, span_lint_and_then};
2 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
3 use rustc::{declare_lint_pass, declare_tool_lint};
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 use syntax_pos::{BytePos, Span};
10
11 declare_clippy_lint! {
12     /// **What it does:** This lint warns when you use `println!("")` to
13     /// print a newline.
14     ///
15     /// **Why is this bad?** You should use `println!()`, which is simpler.
16     ///
17     /// **Known problems:** None.
18     ///
19     /// **Example:**
20     /// ```rust
21     /// println!("");
22     /// ```
23     pub PRINTLN_EMPTY_STRING,
24     style,
25     "using `println!(\"\")` with an empty string"
26 }
27
28 declare_clippy_lint! {
29     /// **What it does:** This lint warns when you use `print!()` with a format
30     /// string that
31     /// ends in a newline.
32     ///
33     /// **Why is this bad?** You should use `println!()` instead, which appends the
34     /// newline.
35     ///
36     /// **Known problems:** None.
37     ///
38     /// **Example:**
39     /// ```rust
40     /// # let name = "World";
41     /// print!("Hello {}!\n", name);
42     /// ```
43     /// use println!() instead
44     /// ```rust
45     /// # let name = "World";
46     /// println!("Hello {}!", name);
47     /// ```
48     pub PRINT_WITH_NEWLINE,
49     style,
50     "using `print!()` with a format string that ends in a single newline"
51 }
52
53 declare_clippy_lint! {
54     /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
55     /// is to catch debugging remnants.
56     ///
57     /// **Why is this bad?** People often print on *stdout* while debugging an
58     /// application and might forget to remove those prints afterward.
59     ///
60     /// **Known problems:** Only catches `print!` and `println!` calls.
61     ///
62     /// **Example:**
63     /// ```rust
64     /// println!("Hello world!");
65     /// ```
66     pub PRINT_STDOUT,
67     restriction,
68     "printing on stdout"
69 }
70
71 declare_clippy_lint! {
72     /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
73     /// lint is to catch debugging remnants.
74     ///
75     /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
76     /// debugging Rust code. It should not be used in user-facing output.
77     ///
78     /// **Example:**
79     /// ```rust
80     /// # let foo = "bar";
81     /// println!("{:?}", foo);
82     /// ```
83     pub USE_DEBUG,
84     restriction,
85     "use of `Debug`-based formatting"
86 }
87
88 declare_clippy_lint! {
89     /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
90     ///
91     /// **Why is this bad?** Using literals as `println!` args is inefficient
92     /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
93     /// (i.e., just put the literal in the format string)
94     ///
95     /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
96     /// -- e.g., `println!("{}", env!("FOO"))`.
97     ///
98     /// **Example:**
99     /// ```rust
100     /// println!("{}", "foo");
101     /// ```
102     /// use the literal without formatting:
103     /// ```rust
104     /// println!("foo");
105     /// ```
106     pub PRINT_LITERAL,
107     style,
108     "printing a literal with a format string"
109 }
110
111 declare_clippy_lint! {
112     /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
113     /// print a newline.
114     ///
115     /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
116     ///
117     /// **Known problems:** None.
118     ///
119     /// **Example:**
120     /// ```rust
121     /// # use std::fmt::Write;
122     /// # let mut buf = String::new();
123     /// writeln!(buf, "");
124     /// ```
125     pub WRITELN_EMPTY_STRING,
126     style,
127     "using `writeln!(buf, \"\")` with an empty string"
128 }
129
130 declare_clippy_lint! {
131     /// **What it does:** This lint warns when you use `write!()` with a format
132     /// string that
133     /// ends in a newline.
134     ///
135     /// **Why is this bad?** You should use `writeln!()` instead, which appends the
136     /// newline.
137     ///
138     /// **Known problems:** None.
139     ///
140     /// **Example:**
141     /// ```rust
142     /// # use std::fmt::Write;
143     /// # let mut buf = String::new();
144     /// # let name = "World";
145     /// write!(buf, "Hello {}!\n", name);
146     /// ```
147     pub WRITE_WITH_NEWLINE,
148     style,
149     "using `write!()` with a format string that ends in a single newline"
150 }
151
152 declare_clippy_lint! {
153     /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
154     ///
155     /// **Why is this bad?** Using literals as `writeln!` args is inefficient
156     /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
157     /// (i.e., just put the literal in the format string)
158     ///
159     /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
160     /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
161     ///
162     /// **Example:**
163     /// ```rust
164     /// # use std::fmt::Write;
165     /// # let mut buf = String::new();
166     /// writeln!(buf, "{}", "foo");
167     /// ```
168     pub WRITE_LITERAL,
169     style,
170     "writing a literal with a format string"
171 }
172
173 declare_lint_pass!(Write => [
174     PRINT_WITH_NEWLINE,
175     PRINTLN_EMPTY_STRING,
176     PRINT_STDOUT,
177     USE_DEBUG,
178     PRINT_LITERAL,
179     WRITE_WITH_NEWLINE,
180     WRITELN_EMPTY_STRING,
181     WRITE_LITERAL
182 ]);
183
184 impl EarlyLintPass for Write {
185     fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &Mac) {
186         if mac.path == sym!(println) {
187             span_lint(cx, PRINT_STDOUT, mac.span, "use of `println!`");
188             if let (Some(fmt_str), _) = check_tts(cx, &mac.tts, false) {
189                 if fmt_str.contents.is_empty() {
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.path == sym!(print) {
202             span_lint(cx, PRINT_STDOUT, mac.span, "use of `print!`");
203             if let (Some(fmt_str), _) = check_tts(cx, &mac.tts, false) {
204                 if check_newlines(&fmt_str) {
205                     span_lint_and_then(
206                         cx,
207                         PRINT_WITH_NEWLINE,
208                         mac.span,
209                         "using `print!()` with a format string that ends in a single newline",
210                         |err| {
211                             err.multipart_suggestion(
212                                 "use `println!` instead",
213                                 vec![
214                                     (mac.path.span, String::from("println")),
215                                     (fmt_str.newline_span(), String::new()),
216                                 ],
217                                 Applicability::MachineApplicable,
218                             );
219                         },
220                     );
221                 }
222             }
223         } else if mac.path == sym!(write) {
224             if let (Some(fmt_str), _) = check_tts(cx, &mac.tts, true) {
225                 if check_newlines(&fmt_str) {
226                     span_lint_and_then(
227                         cx,
228                         WRITE_WITH_NEWLINE,
229                         mac.span,
230                         "using `write!()` with a format string that ends in a single newline",
231                         |err| {
232                             err.multipart_suggestion(
233                                 "use `writeln!()` instead",
234                                 vec![
235                                     (mac.path.span, String::from("writeln")),
236                                     (fmt_str.newline_span(), String::new()),
237                                 ],
238                                 Applicability::MachineApplicable,
239                             );
240                         },
241                     )
242                 }
243             }
244         } else if mac.path == sym!(writeln) {
245             if let (Some(fmt_str), expr) = check_tts(cx, &mac.tts, true) {
246                 if fmt_str.contents.is_empty() {
247                     let mut applicability = Applicability::MachineApplicable;
248                     let suggestion = expr.map_or_else(
249                         move || {
250                             applicability = Applicability::HasPlaceholders;
251                             Cow::Borrowed("v")
252                         },
253                         move |expr| snippet_with_applicability(cx, expr.span, "v", &mut applicability),
254                     );
255
256                     span_lint_and_sugg(
257                         cx,
258                         WRITELN_EMPTY_STRING,
259                         mac.span,
260                         format!("using `writeln!({}, \"\")`", suggestion).as_str(),
261                         "replace it with",
262                         format!("writeln!({})", suggestion),
263                         applicability,
264                     );
265                 }
266             }
267         }
268     }
269 }
270
271 /// The arguments of a `print[ln]!` or `write[ln]!` invocation.
272 struct FmtStr {
273     /// The contents of the format string (inside the quotes).
274     contents: String,
275     style: StrStyle,
276     /// The span of the format string, including quotes, the raw marker, and any raw hashes.
277     span: Span,
278 }
279
280 impl FmtStr {
281     /// Given a format string that ends in a newline and its span, calculates the span of the
282     /// newline.
283     fn newline_span(&self) -> Span {
284         let sp = self.span;
285
286         let newline_sp_hi = sp.hi()
287             - match self.style {
288                 StrStyle::Cooked => BytePos(1),
289                 StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
290             };
291
292         let newline_sp_len = if self.contents.ends_with('\n') {
293             BytePos(1)
294         } else if self.contents.ends_with(r"\n") {
295             BytePos(2)
296         } else {
297             panic!("expected format string to contain a newline");
298         };
299
300         sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi)
301     }
302 }
303
304 /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
305 /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
306 /// the contents of the string, whether it's a raw string, and the span of the literal in the
307 /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
308 /// `format_str` should be written to.
309 ///
310 /// Example:
311 ///
312 /// Calling this function on
313 /// ```rust
314 /// # use std::fmt::Write;
315 /// # let mut buf = String::new();
316 /// # let something = "something";
317 /// writeln!(buf, "string to write: {}", something);
318 /// ```
319 /// will return
320 /// ```rust,ignore
321 /// (Some("string to write: {}"), Some(buf))
322 /// ```
323 #[allow(clippy::too_many_lines)]
324 fn check_tts<'a>(cx: &EarlyContext<'a>, tts: &TokenStream, is_write: bool) -> (Option<FmtStr>, Option<Expr>) {
325     use fmt_macros::*;
326     let tts = tts.clone();
327
328     let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, None, false, false, None);
329     let mut expr: Option<Expr> = None;
330     if is_write {
331         expr = match parser.parse_expr().map_err(|mut err| err.cancel()) {
332             Ok(p) => Some(p.into_inner()),
333             Err(_) => return (None, None),
334         };
335         // might be `writeln!(foo)`
336         if parser.expect(&token::Comma).map_err(|mut err| err.cancel()).is_err() {
337             return (None, expr);
338         }
339     }
340
341     let (fmtstr, fmtstyle) = match parser.parse_str().map_err(|mut err| err.cancel()) {
342         Ok((fmtstr, fmtstyle)) => (fmtstr.to_string(), fmtstyle),
343         Err(_) => return (None, expr),
344     };
345     let fmtspan = parser.prev_span;
346     let tmp = fmtstr.clone();
347     let mut args = vec![];
348     let mut fmt_parser = Parser::new(&tmp, None, Vec::new(), false);
349     while let Some(piece) = fmt_parser.next() {
350         if !fmt_parser.errors.is_empty() {
351             return (None, expr);
352         }
353         if let Piece::NextArgument(arg) = piece {
354             if arg.format.ty == "?" {
355                 // FIXME: modify rustc's fmt string parser to give us the current span
356                 span_lint(cx, USE_DEBUG, parser.prev_span, "use of `Debug`-based formatting");
357             }
358             args.push(arg);
359         }
360     }
361     let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
362     let mut idx = 0;
363     loop {
364         const SIMPLE: FormatSpec<'_> = FormatSpec {
365             fill: None,
366             align: AlignUnknown,
367             flags: 0,
368             precision: CountImplied,
369             precision_span: None,
370             width: CountImplied,
371             width_span: None,
372             ty: "",
373         };
374         if !parser.eat(&token::Comma) {
375             return (
376                 Some(FmtStr {
377                     contents: fmtstr,
378                     style: fmtstyle,
379                     span: fmtspan,
380                 }),
381                 expr,
382             );
383         }
384         let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
385             expr
386         } else {
387             return (
388                 Some(FmtStr {
389                     contents: fmtstr,
390                     style: fmtstyle,
391                     span: fmtspan,
392                 }),
393                 None,
394             );
395         };
396         match &token_expr.node {
397             ExprKind::Lit(_) => {
398                 let mut all_simple = true;
399                 let mut seen = false;
400                 for arg in &args {
401                     match arg.position {
402                         ArgumentImplicitlyIs(n) | ArgumentIs(n) => {
403                             if n == idx {
404                                 all_simple &= arg.format == SIMPLE;
405                                 seen = true;
406                             }
407                         },
408                         ArgumentNamed(_) => {},
409                     }
410                 }
411                 if all_simple && seen {
412                     span_lint(cx, lint, token_expr.span, "literal with an empty format string");
413                 }
414                 idx += 1;
415             },
416             ExprKind::Assign(lhs, rhs) => {
417                 if let ExprKind::Lit(_) = rhs.node {
418                     if let ExprKind::Path(_, p) = &lhs.node {
419                         let mut all_simple = true;
420                         let mut seen = false;
421                         for arg in &args {
422                             match arg.position {
423                                 ArgumentImplicitlyIs(_) | ArgumentIs(_) => {},
424                                 ArgumentNamed(name) => {
425                                     if *p == name {
426                                         seen = true;
427                                         all_simple &= arg.format == SIMPLE;
428                                     }
429                                 },
430                             }
431                         }
432                         if all_simple && seen {
433                             span_lint(cx, lint, rhs.span, "literal with an empty format string");
434                         }
435                     }
436                 }
437             },
438             _ => idx += 1,
439         }
440     }
441 }
442
443 /// Checks if the format string constains a single newline that terminates it.
444 ///
445 /// Literal and escaped newlines are both checked (only literal for raw strings).
446 fn check_newlines(fmt_str: &FmtStr) -> bool {
447     let s = &fmt_str.contents;
448
449     if s.ends_with('\n') {
450         return true;
451     } else if let StrStyle::Raw(_) = fmt_str.style {
452         return false;
453     }
454
455     if s.len() < 2 {
456         return false;
457     }
458
459     let bytes = s.as_bytes();
460     if bytes[bytes.len() - 2] != b'\\' || bytes[bytes.len() - 1] != b'n' {
461         return false;
462     }
463
464     let mut escaping = false;
465     for (index, &byte) in bytes.iter().enumerate() {
466         if escaping {
467             if byte == b'n' {
468                 return index == bytes.len() - 1;
469             }
470             escaping = false;
471         } else if byte == b'\\' {
472             escaping = true;
473         }
474     }
475
476     false
477 }