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