]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/write.rs
5229a7058659c201ad361bbb112c4cd58ba379d3
[rust.git] / clippy_lints / src / write.rs
1 use std::borrow::Cow;
2 use std::iter;
3 use std::ops::{Deref, Range};
4
5 use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then};
6 use clippy_utils::source::{snippet_opt, snippet_with_applicability};
7 use rustc_ast::ast::{Expr, ExprKind, ImplKind, Item, ItemKind, MacCall, Path, StrLit, StrStyle};
8 use rustc_ast::token::{self, LitKind};
9 use rustc_ast::tokenstream::TokenStream;
10 use rustc_errors::Applicability;
11 use rustc_lexer::unescape::{self, EscapeError};
12 use rustc_lint::{EarlyContext, EarlyLintPass};
13 use rustc_parse::parser;
14 use rustc_session::{declare_tool_lint, impl_lint_pass};
15 use rustc_span::symbol::{kw, Symbol};
16 use rustc_span::{sym, BytePos, Span, DUMMY_SP};
17
18 declare_clippy_lint! {
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     /// // Bad
29     /// println!("");
30     ///
31     /// // Good
32     /// println!();
33     /// ```
34     pub PRINTLN_EMPTY_STRING,
35     style,
36     "using `println!(\"\")` with an empty string"
37 }
38
39 declare_clippy_lint! {
40     /// **What it does:** This lint warns when you use `print!()` with a format
41     /// string that ends in a newline.
42     ///
43     /// **Why is this bad?** You should use `println!()` instead, which appends the
44     /// newline.
45     ///
46     /// **Known problems:** None.
47     ///
48     /// **Example:**
49     /// ```rust
50     /// # let name = "World";
51     /// print!("Hello {}!\n", name);
52     /// ```
53     /// use println!() instead
54     /// ```rust
55     /// # let name = "World";
56     /// println!("Hello {}!", name);
57     /// ```
58     pub PRINT_WITH_NEWLINE,
59     style,
60     "using `print!()` with a format string that ends in a single newline"
61 }
62
63 declare_clippy_lint! {
64     /// **What it does:** Checks for printing on *stdout*. The purpose of this lint
65     /// is to catch debugging remnants.
66     ///
67     /// **Why is this bad?** People often print on *stdout* while debugging an
68     /// application and might forget to remove those prints afterward.
69     ///
70     /// **Known problems:** Only catches `print!` and `println!` calls.
71     ///
72     /// **Example:**
73     /// ```rust
74     /// println!("Hello world!");
75     /// ```
76     pub PRINT_STDOUT,
77     restriction,
78     "printing on stdout"
79 }
80
81 declare_clippy_lint! {
82     /// **What it does:** Checks for printing on *stderr*. The purpose of this lint
83     /// is to catch debugging remnants.
84     ///
85     /// **Why is this bad?** People often print on *stderr* while debugging an
86     /// application and might forget to remove those prints afterward.
87     ///
88     /// **Known problems:** Only catches `eprint!` and `eprintln!` calls.
89     ///
90     /// **Example:**
91     /// ```rust
92     /// eprintln!("Hello world!");
93     /// ```
94     pub PRINT_STDERR,
95     restriction,
96     "printing on stderr"
97 }
98
99 declare_clippy_lint! {
100     /// **What it does:** Checks for use of `Debug` formatting. The purpose of this
101     /// lint is to catch debugging remnants.
102     ///
103     /// **Why is this bad?** The purpose of the `Debug` trait is to facilitate
104     /// debugging Rust code. It should not be used in user-facing output.
105     ///
106     /// **Example:**
107     /// ```rust
108     /// # let foo = "bar";
109     /// println!("{:?}", foo);
110     /// ```
111     pub USE_DEBUG,
112     restriction,
113     "use of `Debug`-based formatting"
114 }
115
116 declare_clippy_lint! {
117     /// **What it does:** This lint warns about the use of literals as `print!`/`println!` args.
118     ///
119     /// **Why is this bad?** Using literals as `println!` args is inefficient
120     /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
121     /// (i.e., just put the literal in the format string)
122     ///
123     /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
124     /// -- e.g., `println!("{}", env!("FOO"))`.
125     ///
126     /// **Example:**
127     /// ```rust
128     /// println!("{}", "foo");
129     /// ```
130     /// use the literal without formatting:
131     /// ```rust
132     /// println!("foo");
133     /// ```
134     pub PRINT_LITERAL,
135     style,
136     "printing a literal with a format string"
137 }
138
139 declare_clippy_lint! {
140     /// **What it does:** This lint warns when you use `writeln!(buf, "")` to
141     /// print a newline.
142     ///
143     /// **Why is this bad?** You should use `writeln!(buf)`, which is simpler.
144     ///
145     /// **Known problems:** None.
146     ///
147     /// **Example:**
148     /// ```rust
149     /// # use std::fmt::Write;
150     /// # let mut buf = String::new();
151     /// // Bad
152     /// writeln!(buf, "");
153     ///
154     /// // Good
155     /// writeln!(buf);
156     /// ```
157     pub WRITELN_EMPTY_STRING,
158     style,
159     "using `writeln!(buf, \"\")` with an empty string"
160 }
161
162 declare_clippy_lint! {
163     /// **What it does:** This lint warns when you use `write!()` with a format
164     /// string that
165     /// ends in a newline.
166     ///
167     /// **Why is this bad?** You should use `writeln!()` instead, which appends the
168     /// newline.
169     ///
170     /// **Known problems:** None.
171     ///
172     /// **Example:**
173     /// ```rust
174     /// # use std::fmt::Write;
175     /// # let mut buf = String::new();
176     /// # let name = "World";
177     /// // Bad
178     /// write!(buf, "Hello {}!\n", name);
179     ///
180     /// // Good
181     /// writeln!(buf, "Hello {}!", name);
182     /// ```
183     pub WRITE_WITH_NEWLINE,
184     style,
185     "using `write!()` with a format string that ends in a single newline"
186 }
187
188 declare_clippy_lint! {
189     /// **What it does:** This lint warns about the use of literals as `write!`/`writeln!` args.
190     ///
191     /// **Why is this bad?** Using literals as `writeln!` args is inefficient
192     /// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
193     /// (i.e., just put the literal in the format string)
194     ///
195     /// **Known problems:** Will also warn with macro calls as arguments that expand to literals
196     /// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
197     ///
198     /// **Example:**
199     /// ```rust
200     /// # use std::fmt::Write;
201     /// # let mut buf = String::new();
202     /// // Bad
203     /// writeln!(buf, "{}", "foo");
204     ///
205     /// // Good
206     /// writeln!(buf, "foo");
207     /// ```
208     pub WRITE_LITERAL,
209     style,
210     "writing a literal with a format string"
211 }
212
213 #[derive(Default)]
214 pub struct Write {
215     in_debug_impl: bool,
216 }
217
218 impl_lint_pass!(Write => [
219     PRINT_WITH_NEWLINE,
220     PRINTLN_EMPTY_STRING,
221     PRINT_STDOUT,
222     PRINT_STDERR,
223     USE_DEBUG,
224     PRINT_LITERAL,
225     WRITE_WITH_NEWLINE,
226     WRITELN_EMPTY_STRING,
227     WRITE_LITERAL
228 ]);
229
230 impl EarlyLintPass for Write {
231     fn check_item(&mut self, _: &EarlyContext<'_>, item: &Item) {
232         if let ItemKind::Impl(box ImplKind {
233             of_trait: Some(trait_ref),
234             ..
235         }) = &item.kind
236         {
237             let trait_name = trait_ref
238                 .path
239                 .segments
240                 .iter()
241                 .last()
242                 .expect("path has at least one segment")
243                 .ident
244                 .name;
245             if trait_name == sym::Debug {
246                 self.in_debug_impl = true;
247             }
248         }
249     }
250
251     fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &Item) {
252         self.in_debug_impl = false;
253     }
254
255     fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &MacCall) {
256         fn is_build_script(cx: &EarlyContext<'_>) -> bool {
257             // Cargo sets the crate name for build scripts to `build_script_build`
258             cx.sess
259                 .opts
260                 .crate_name
261                 .as_ref()
262                 .map_or(false, |crate_name| crate_name == "build_script_build")
263         }
264
265         if mac.path == sym!(print) {
266             if !is_build_script(cx) {
267                 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`");
268             }
269             self.lint_print_with_newline(cx, mac);
270         } else if mac.path == sym!(println) {
271             if !is_build_script(cx) {
272                 span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`");
273             }
274             self.lint_println_empty_string(cx, mac);
275         } else if mac.path == sym!(eprint) {
276             span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprint!`");
277             self.lint_print_with_newline(cx, mac);
278         } else if mac.path == sym!(eprintln) {
279             span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprintln!`");
280             self.lint_println_empty_string(cx, mac);
281         } else if mac.path == sym!(write) {
282             if let (Some(fmt_str), dest) = self.check_tts(cx, mac.args.inner_tokens(), true) {
283                 if check_newlines(&fmt_str) {
284                     let (nl_span, only_nl) = newline_span(&fmt_str);
285                     let nl_span = match (dest, only_nl) {
286                         // Special case of `write!(buf, "\n")`: Mark everything from the end of
287                         // `buf` for removal so no trailing comma [`writeln!(buf, )`] remains.
288                         (Some(dest_expr), true) => Span::new(dest_expr.span.hi(), nl_span.hi(), nl_span.ctxt()),
289                         _ => nl_span,
290                     };
291                     span_lint_and_then(
292                         cx,
293                         WRITE_WITH_NEWLINE,
294                         mac.span(),
295                         "using `write!()` with a format string that ends in a single newline",
296                         |err| {
297                             err.multipart_suggestion(
298                                 "use `writeln!()` instead",
299                                 vec![(mac.path.span, String::from("writeln")), (nl_span, String::new())],
300                                 Applicability::MachineApplicable,
301                             );
302                         },
303                     );
304                 }
305             }
306         } else if mac.path == sym!(writeln) {
307             if let (Some(fmt_str), expr) = self.check_tts(cx, mac.args.inner_tokens(), true) {
308                 if fmt_str.symbol == kw::Empty {
309                     let mut applicability = Applicability::MachineApplicable;
310                     // FIXME: remove this `#[allow(...)]` once the issue #5822 gets fixed
311                     #[allow(clippy::option_if_let_else)]
312                     let suggestion = if let Some(e) = expr {
313                         snippet_with_applicability(cx, e.span, "v", &mut applicability)
314                     } else {
315                         applicability = Applicability::HasPlaceholders;
316                         Cow::Borrowed("v")
317                     };
318
319                     span_lint_and_sugg(
320                         cx,
321                         WRITELN_EMPTY_STRING,
322                         mac.span(),
323                         format!("using `writeln!({}, \"\")`", suggestion).as_str(),
324                         "replace it with",
325                         format!("writeln!({})", suggestion),
326                         applicability,
327                     );
328                 }
329             }
330         }
331     }
332 }
333
334 /// Given a format string that ends in a newline and its span, calculates the span of the
335 /// newline, or the format string itself if the format string consists solely of a newline.
336 /// Return this and a boolean indicating whether it only consisted of a newline.
337 fn newline_span(fmtstr: &StrLit) -> (Span, bool) {
338     let sp = fmtstr.span;
339     let contents = &fmtstr.symbol.as_str();
340
341     if *contents == r"\n" {
342         return (sp, true);
343     }
344
345     let newline_sp_hi = sp.hi()
346         - match fmtstr.style {
347             StrStyle::Cooked => BytePos(1),
348             StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
349         };
350
351     let newline_sp_len = if contents.ends_with('\n') {
352         BytePos(1)
353     } else if contents.ends_with(r"\n") {
354         BytePos(2)
355     } else {
356         panic!("expected format string to contain a newline");
357     };
358
359     (sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi), false)
360 }
361
362 /// Stores a list of replacement spans for each argument, but only if all the replacements used an
363 /// empty format string.
364 #[derive(Default)]
365 struct SimpleFormatArgs {
366     unnamed: Vec<Vec<Span>>,
367     named: Vec<(Symbol, Vec<Span>)>,
368 }
369 impl SimpleFormatArgs {
370     fn get_unnamed(&self) -> impl Iterator<Item = &[Span]> {
371         self.unnamed.iter().map(|x| match x.as_slice() {
372             // Ignore the dummy span added from out of order format arguments.
373             [DUMMY_SP] => &[],
374             x => x,
375         })
376     }
377
378     fn get_named(&self, n: &Path) -> &[Span] {
379         self.named.iter().find(|x| *n == x.0).map_or(&[], |x| x.1.as_slice())
380     }
381
382     fn push(&mut self, arg: rustc_parse_format::Argument<'_>, span: Span) {
383         use rustc_parse_format::{
384             AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied, FormatSpec,
385         };
386
387         const SIMPLE: FormatSpec<'_> = FormatSpec {
388             fill: None,
389             align: AlignUnknown,
390             flags: 0,
391             precision: CountImplied,
392             precision_span: None,
393             width: CountImplied,
394             width_span: None,
395             ty: "",
396             ty_span: None,
397         };
398
399         match arg.position {
400             ArgumentIs(n) | ArgumentImplicitlyIs(n) => {
401                 if self.unnamed.len() <= n {
402                     // Use a dummy span to mark all unseen arguments.
403                     self.unnamed.resize_with(n, || vec![DUMMY_SP]);
404                     if arg.format == SIMPLE {
405                         self.unnamed.push(vec![span]);
406                     } else {
407                         self.unnamed.push(Vec::new());
408                     }
409                 } else {
410                     let args = &mut self.unnamed[n];
411                     match (args.as_mut_slice(), arg.format == SIMPLE) {
412                         // A non-empty format string has been seen already.
413                         ([], _) => (),
414                         // Replace the dummy span, if it exists.
415                         ([dummy @ DUMMY_SP], true) => *dummy = span,
416                         ([_, ..], true) => args.push(span),
417                         ([_, ..], false) => *args = Vec::new(),
418                     }
419                 }
420             },
421             ArgumentNamed(n) => {
422                 if let Some(x) = self.named.iter_mut().find(|x| x.0 == n) {
423                     match x.1.as_slice() {
424                         // A non-empty format string has been seen already.
425                         [] => (),
426                         [_, ..] if arg.format == SIMPLE => x.1.push(span),
427                         [_, ..] => x.1 = Vec::new(),
428                     }
429                 } else if arg.format == SIMPLE {
430                     self.named.push((n, vec![span]));
431                 } else {
432                     self.named.push((n, Vec::new()));
433                 }
434             },
435         };
436     }
437 }
438
439 impl Write {
440     /// Parses a format string into a collection of spans for each argument. This only keeps track
441     /// of empty format arguments. Will also lint usages of debug format strings outside of debug
442     /// impls.
443     fn parse_fmt_string(&self, cx: &EarlyContext<'_>, str_lit: &StrLit) -> Option<SimpleFormatArgs> {
444         use rustc_parse_format::{ParseMode, Parser, Piece};
445
446         let str_sym = str_lit.symbol_unescaped.as_str();
447         let style = match str_lit.style {
448             StrStyle::Cooked => None,
449             StrStyle::Raw(n) => Some(n as usize),
450         };
451
452         let mut parser = Parser::new(&str_sym, style, snippet_opt(cx, str_lit.span), false, ParseMode::Format);
453         let mut args = SimpleFormatArgs::default();
454
455         while let Some(arg) = parser.next() {
456             let arg = match arg {
457                 Piece::String(_) => continue,
458                 Piece::NextArgument(arg) => arg,
459             };
460             let span = parser
461                 .arg_places
462                 .last()
463                 .map_or(DUMMY_SP, |&x| str_lit.span.from_inner(x));
464
465             if !self.in_debug_impl && arg.format.ty == "?" {
466                 // FIXME: modify rustc's fmt string parser to give us the current span
467                 span_lint(cx, USE_DEBUG, span, "use of `Debug`-based formatting");
468             }
469
470             args.push(arg, span);
471         }
472
473         parser.errors.is_empty().then(move || args)
474     }
475
476     /// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
477     /// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
478     /// the contents of the string, whether it's a raw string, and the span of the literal in the
479     /// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
480     /// `format_str` should be written to.
481     ///
482     /// Example:
483     ///
484     /// Calling this function on
485     /// ```rust
486     /// # use std::fmt::Write;
487     /// # let mut buf = String::new();
488     /// # let something = "something";
489     /// writeln!(buf, "string to write: {}", something);
490     /// ```
491     /// will return
492     /// ```rust,ignore
493     /// (Some("string to write: {}"), Some(buf))
494     /// ```
495     #[allow(clippy::too_many_lines)]
496     fn check_tts<'a>(&self, cx: &EarlyContext<'a>, tts: TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
497         let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, false, None);
498         let expr = if is_write {
499             match parser
500                 .parse_expr()
501                 .map(rustc_ast::ptr::P::into_inner)
502                 .map_err(|mut e| e.cancel())
503             {
504                 // write!(e, ...)
505                 Ok(p) if parser.eat(&token::Comma) => Some(p),
506                 // write!(e) or error
507                 e => return (None, e.ok()),
508             }
509         } else {
510             None
511         };
512
513         let fmtstr = match parser.parse_str_lit() {
514             Ok(fmtstr) => fmtstr,
515             Err(_) => return (None, expr),
516         };
517
518         let args = match self.parse_fmt_string(cx, &fmtstr) {
519             Some(args) => args,
520             None => return (Some(fmtstr), expr),
521         };
522
523         let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
524         let mut unnamed_args = args.get_unnamed();
525         loop {
526             if !parser.eat(&token::Comma) {
527                 return (Some(fmtstr), expr);
528             }
529
530             let comma_span = parser.prev_token.span;
531             let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
532                 expr
533             } else {
534                 return (Some(fmtstr), None);
535             };
536             let (fmt_spans, lit) = match &token_expr.kind {
537                 ExprKind::Lit(lit) => (unnamed_args.next().unwrap_or(&[]), lit),
538                 ExprKind::Assign(lhs, rhs, _) => match (&lhs.kind, &rhs.kind) {
539                     (ExprKind::Path(_, p), ExprKind::Lit(lit)) => (args.get_named(p), lit),
540                     _ => continue,
541                 },
542                 _ => {
543                     unnamed_args.next();
544                     continue;
545                 },
546             };
547
548             let replacement: String = match lit.token.kind {
549                 LitKind::Integer | LitKind::Float | LitKind::Err => continue,
550                 LitKind::StrRaw(_) | LitKind::ByteStrRaw(_) if matches!(fmtstr.style, StrStyle::Raw(_)) => {
551                     lit.token.symbol.as_str().replace("{", "{{").replace("}", "}}")
552                 },
553                 LitKind::Str | LitKind::ByteStr if matches!(fmtstr.style, StrStyle::Cooked) => {
554                     lit.token.symbol.as_str().replace("{", "{{").replace("}", "}}")
555                 },
556                 LitKind::StrRaw(_) | LitKind::Str | LitKind::ByteStrRaw(_) | LitKind::ByteStr => continue,
557                 LitKind::Byte | LitKind::Char => match &*lit.token.symbol.as_str() {
558                     "\"" if matches!(fmtstr.style, StrStyle::Cooked) => "\\\"",
559                     "\"" if matches!(fmtstr.style, StrStyle::Raw(0)) => continue,
560                     "\\\\" if matches!(fmtstr.style, StrStyle::Raw(_)) => "\\",
561                     "\\'" => "'",
562                     "{" => "{{",
563                     "}" => "}}",
564                     x if matches!(fmtstr.style, StrStyle::Raw(_)) && x.starts_with('\\') => continue,
565                     x => x,
566                 }
567                 .into(),
568                 LitKind::Bool => lit.token.symbol.as_str().deref().into(),
569             };
570
571             if !fmt_spans.is_empty() {
572                 span_lint_and_then(
573                     cx,
574                     lint,
575                     token_expr.span,
576                     "literal with an empty format string",
577                     |diag| {
578                         diag.multipart_suggestion(
579                             "try this",
580                             iter::once((comma_span.to(token_expr.span), String::new()))
581                                 .chain(fmt_spans.iter().copied().zip(iter::repeat(replacement)))
582                                 .collect(),
583                             Applicability::MachineApplicable,
584                         );
585                     },
586                 );
587             }
588         }
589     }
590
591     fn lint_println_empty_string(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
592         if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
593             if fmt_str.symbol == kw::Empty {
594                 let name = mac.path.segments[0].ident.name;
595                 span_lint_and_sugg(
596                     cx,
597                     PRINTLN_EMPTY_STRING,
598                     mac.span(),
599                     &format!("using `{}!(\"\")`", name),
600                     "replace it with",
601                     format!("{}!()", name),
602                     Applicability::MachineApplicable,
603                 );
604             }
605         }
606     }
607
608     fn lint_print_with_newline(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
609         if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
610             if check_newlines(&fmt_str) {
611                 let name = mac.path.segments[0].ident.name;
612                 let suggested = format!("{}ln", name);
613                 span_lint_and_then(
614                     cx,
615                     PRINT_WITH_NEWLINE,
616                     mac.span(),
617                     &format!("using `{}!()` with a format string that ends in a single newline", name),
618                     |err| {
619                         err.multipart_suggestion(
620                             &format!("use `{}!` instead", suggested),
621                             vec![(mac.path.span, suggested), (newline_span(&fmt_str).0, String::new())],
622                             Applicability::MachineApplicable,
623                         );
624                     },
625                 );
626             }
627         }
628     }
629 }
630
631 /// Checks if the format string contains a single newline that terminates it.
632 ///
633 /// Literal and escaped newlines are both checked (only literal for raw strings).
634 fn check_newlines(fmtstr: &StrLit) -> bool {
635     let mut has_internal_newline = false;
636     let mut last_was_cr = false;
637     let mut should_lint = false;
638
639     let contents = &fmtstr.symbol.as_str();
640
641     let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
642         let c = c.unwrap();
643
644         if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
645             should_lint = true;
646         } else {
647             last_was_cr = c == '\r';
648             if c == '\n' {
649                 has_internal_newline = true;
650             }
651         }
652     };
653
654     match fmtstr.style {
655         StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb),
656         StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb),
657     }
658
659     should_lint
660 }