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