]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/explicit_write.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[rust.git] / clippy_lints / src / explicit_write.rs
1 use crate::utils::{is_expn_of, match_def_path, resolve_node, span_lint, span_lint_and_sugg};
2 use if_chain::if_chain;
3 use rustc::hir::*;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::{declare_tool_lint, lint_array};
6 use rustc_errors::Applicability;
7 use syntax::ast::LitKind;
8
9 declare_clippy_lint! {
10     /// **What it does:** Checks for usage of `write!()` / `writeln()!` which can be
11     /// replaced with `(e)print!()` / `(e)println!()`
12     ///
13     /// **Why is this bad?** Using `(e)println! is clearer and more concise
14     ///
15     /// **Known problems:** None.
16     ///
17     /// **Example:**
18     /// ```rust
19     /// // this would be clearer as `eprintln!("foo: {:?}", bar);`
20     /// writeln!(&mut io::stderr(), "foo: {:?}", bar).unwrap();
21     /// ```
22     pub EXPLICIT_WRITE,
23     complexity,
24     "using the `write!()` family of functions instead of the `print!()` family of functions, when using the latter would work"
25 }
26
27 #[derive(Copy, Clone, Debug)]
28 pub struct Pass;
29
30 impl LintPass for Pass {
31     fn get_lints(&self) -> LintArray {
32         lint_array!(EXPLICIT_WRITE)
33     }
34
35     fn name(&self) -> &'static str {
36         "ExplicitWrite"
37     }
38 }
39
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
41     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
42         if_chain! {
43             // match call to unwrap
44             if let ExprKind::MethodCall(ref unwrap_fun, _, ref unwrap_args) = expr.node;
45             if unwrap_fun.ident.name == "unwrap";
46             // match call to write_fmt
47             if unwrap_args.len() > 0;
48             if let ExprKind::MethodCall(ref write_fun, _, ref write_args) =
49                 unwrap_args[0].node;
50             if write_fun.ident.name == "write_fmt";
51             // match calls to std::io::stdout() / std::io::stderr ()
52             if write_args.len() > 0;
53             if let ExprKind::Call(ref dest_fun, _) = write_args[0].node;
54             if let ExprKind::Path(ref qpath) = dest_fun.node;
55             if let Some(dest_fun_id) =
56                 resolve_node(cx, qpath, dest_fun.hir_id).opt_def_id();
57             if let Some(dest_name) = if match_def_path(cx.tcx, dest_fun_id, &["std", "io", "stdio", "stdout"]) {
58                 Some("stdout")
59             } else if match_def_path(cx.tcx, dest_fun_id, &["std", "io", "stdio", "stderr"]) {
60                 Some("stderr")
61             } else {
62                 None
63             };
64             then {
65                 let write_span = unwrap_args[0].span;
66                 let calling_macro =
67                     // ordering is important here, since `writeln!` uses `write!` internally
68                     if is_expn_of(write_span, "writeln").is_some() {
69                         Some("writeln")
70                     } else if is_expn_of(write_span, "write").is_some() {
71                         Some("write")
72                     } else {
73                         None
74                     };
75                 let prefix = if dest_name == "stderr" {
76                     "e"
77                 } else {
78                     ""
79                 };
80
81                 // We need to remove the last trailing newline from the string because the
82                 // underlying `fmt::write` function doesn't know whether `println!` or `print!` was
83                 // used.
84                 if let Some(mut write_output) = write_output_string(write_args) {
85                     if write_output.ends_with('\n') {
86                         write_output.pop();
87                     }
88
89                     if let Some(macro_name) = calling_macro {
90                         span_lint_and_sugg(
91                             cx,
92                             EXPLICIT_WRITE,
93                             expr.span,
94                             &format!(
95                                 "use of `{}!({}(), ...).unwrap()`",
96                                 macro_name,
97                                 dest_name
98                             ),
99                             "try this",
100                             format!("{}{}!(\"{}\")", prefix, macro_name.replace("write", "print"), write_output.escape_default()),
101                             Applicability::MachineApplicable
102                         );
103                     } else {
104                         span_lint_and_sugg(
105                             cx,
106                             EXPLICIT_WRITE,
107                             expr.span,
108                             &format!("use of `{}().write_fmt(...).unwrap()`", dest_name),
109                             "try this",
110                             format!("{}print!(\"{}\")", prefix, write_output.escape_default()),
111                             Applicability::MachineApplicable
112                         );
113                     }
114                 } else {
115                     // We don't have a proper suggestion
116                     if let Some(macro_name) = calling_macro {
117                         span_lint(
118                             cx,
119                             EXPLICIT_WRITE,
120                             expr.span,
121                             &format!(
122                                 "use of `{}!({}(), ...).unwrap()`. Consider using `{}{}!` instead",
123                                 macro_name,
124                                 dest_name,
125                                 prefix,
126                                 macro_name.replace("write", "print")
127                             )
128                         );
129                     } else {
130                         span_lint(
131                             cx,
132                             EXPLICIT_WRITE,
133                             expr.span,
134                             &format!("use of `{}().write_fmt(...).unwrap()`. Consider using `{}print!` instead", dest_name, prefix),
135                         );
136                     }
137                 }
138
139             }
140         }
141     }
142 }
143
144 // Extract the output string from the given `write_args`.
145 fn write_output_string(write_args: &HirVec<Expr>) -> Option<String> {
146     if_chain! {
147         // Obtain the string that should be printed
148         if write_args.len() > 1;
149         if let ExprKind::Call(_, ref output_args) = write_args[1].node;
150         if output_args.len() > 0;
151         if let ExprKind::AddrOf(_, ref output_string_expr) = output_args[0].node;
152         if let ExprKind::Array(ref string_exprs) = output_string_expr.node;
153         if string_exprs.len() > 0;
154         if let ExprKind::Lit(ref lit) = string_exprs[0].node;
155         if let LitKind::Str(ref write_output, _) = lit.node;
156         then {
157             return Some(write_output.to_string())
158         }
159     }
160     None
161 }