]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/explicit_write.rs
Merge pull request #3269 from rust-lang-nursery/relicense
[rust.git] / clippy_lints / src / explicit_write.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use if_chain::if_chain;
15 use crate::utils::{is_expn_of, match_def_path, resolve_node, span_lint};
16 use crate::utils::opt_def_id;
17
18 /// **What it does:** Checks for usage of `write!()` / `writeln()!` which can be
19 /// replaced with `(e)print!()` / `(e)println!()`
20 ///
21 /// **Why is this bad?** Using `(e)println! is clearer and more concise
22 ///
23 /// **Known problems:** None.
24 ///
25 /// **Example:**
26 /// ```rust
27 /// // this would be clearer as `eprintln!("foo: {:?}", bar);`
28 /// writeln!(&mut io::stderr(), "foo: {:?}", bar).unwrap();
29 /// ```
30 declare_clippy_lint! {
31     pub EXPLICIT_WRITE,
32     complexity,
33     "using the `write!()` family of functions instead of the `print!()` family \
34      of functions, when using the latter would work"
35 }
36
37 #[derive(Copy, Clone, Debug)]
38 pub struct Pass;
39
40 impl LintPass for Pass {
41     fn get_lints(&self) -> LintArray {
42         lint_array!(EXPLICIT_WRITE)
43     }
44 }
45
46 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
47     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
48         if_chain! {
49             // match call to unwrap
50             if let ExprKind::MethodCall(ref unwrap_fun, _, ref unwrap_args) = expr.node;
51             if unwrap_fun.ident.name == "unwrap";
52             // match call to write_fmt
53             if unwrap_args.len() > 0;
54             if let ExprKind::MethodCall(ref write_fun, _, ref write_args) =
55                 unwrap_args[0].node;
56             if write_fun.ident.name == "write_fmt";
57             // match calls to std::io::stdout() / std::io::stderr ()
58             if write_args.len() > 0;
59             if let ExprKind::Call(ref dest_fun, _) = write_args[0].node;
60             if let ExprKind::Path(ref qpath) = dest_fun.node;
61             if let Some(dest_fun_id) =
62                 opt_def_id(resolve_node(cx, qpath, dest_fun.hir_id));
63             if let Some(dest_name) = if match_def_path(cx.tcx, dest_fun_id, &["std", "io", "stdio", "stdout"]) {
64                 Some("stdout")
65             } else if match_def_path(cx.tcx, dest_fun_id, &["std", "io", "stdio", "stderr"]) {
66                 Some("stderr")
67             } else {
68                 None
69             };
70             then {
71                 let write_span = unwrap_args[0].span;
72                 let calling_macro =
73                     // ordering is important here, since `writeln!` uses `write!` internally
74                     if is_expn_of(write_span, "writeln").is_some() {
75                         Some("writeln")
76                     } else if is_expn_of(write_span, "write").is_some() {
77                         Some("write")
78                     } else {
79                         None
80                     };
81                 let prefix = if dest_name == "stderr" {
82                     "e"
83                 } else {
84                     ""
85                 };
86                 if let Some(macro_name) = calling_macro {
87                     span_lint(
88                         cx,
89                         EXPLICIT_WRITE,
90                         expr.span,
91                         &format!(
92                             "use of `{}!({}(), ...).unwrap()`. Consider using `{}{}!` instead",
93                             macro_name,
94                             dest_name,
95                             prefix,
96                             macro_name.replace("write", "print")
97                         )
98                     );
99                 } else {
100                     span_lint(
101                         cx,
102                         EXPLICIT_WRITE,
103                         expr.span,
104                         &format!(
105                             "use of `{}().write_fmt(...).unwrap()`. Consider using `{}print!` instead",
106                             dest_name,
107                             prefix,
108                         )
109                     );
110                 }
111             }
112         }
113     }
114 }