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