]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/explicit_write.rs
Merge branch 'master' into unneeded_wildcard_pattern
[rust.git] / clippy_lints / src / explicit_write.rs
1 use crate::utils::{is_expn_of, match_def_path, paths, 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_lint_pass, declare_tool_lint};
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     /// # use std::io::Write;
20     /// # let bar = "furchtbar";
21     /// // this would be clearer as `eprintln!("foo: {:?}", bar);`
22     /// writeln!(&mut std::io::stderr(), "foo: {:?}", bar).unwrap();
23     /// ```
24     pub EXPLICIT_WRITE,
25     complexity,
26     "using the `write!()` family of functions instead of the `print!()` family of functions, when using the latter would work"
27 }
28
29 declare_lint_pass!(ExplicitWrite => [EXPLICIT_WRITE]);
30
31 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ExplicitWrite {
32     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
33         if_chain! {
34             // match call to unwrap
35             if let ExprKind::MethodCall(ref unwrap_fun, _, ref unwrap_args) = expr.node;
36             if unwrap_fun.ident.name == sym!(unwrap);
37             // match call to write_fmt
38             if unwrap_args.len() > 0;
39             if let ExprKind::MethodCall(ref write_fun, _, ref write_args) =
40                 unwrap_args[0].node;
41             if write_fun.ident.name == sym!(write_fmt);
42             // match calls to std::io::stdout() / std::io::stderr ()
43             if write_args.len() > 0;
44             if let ExprKind::Call(ref dest_fun, _) = write_args[0].node;
45             if let ExprKind::Path(ref qpath) = dest_fun.node;
46             if let Some(dest_fun_id) = resolve_node(cx, qpath, dest_fun.hir_id).opt_def_id();
47             if let Some(dest_name) = if match_def_path(cx, dest_fun_id, &paths::STDOUT) {
48                 Some("stdout")
49             } else if match_def_path(cx, dest_fun_id, &paths::STDERR) {
50                 Some("stderr")
51             } else {
52                 None
53             };
54             then {
55                 let write_span = unwrap_args[0].span;
56                 let calling_macro =
57                     // ordering is important here, since `writeln!` uses `write!` internally
58                     if is_expn_of(write_span, "writeln").is_some() {
59                         Some("writeln")
60                     } else if is_expn_of(write_span, "write").is_some() {
61                         Some("write")
62                     } else {
63                         None
64                     };
65                 let prefix = if dest_name == "stderr" {
66                     "e"
67                 } else {
68                     ""
69                 };
70
71                 // We need to remove the last trailing newline from the string because the
72                 // underlying `fmt::write` function doesn't know whether `println!` or `print!` was
73                 // used.
74                 if let Some(mut write_output) = write_output_string(write_args) {
75                     if write_output.ends_with('\n') {
76                         write_output.pop();
77                     }
78
79                     if let Some(macro_name) = calling_macro {
80                         span_lint_and_sugg(
81                             cx,
82                             EXPLICIT_WRITE,
83                             expr.span,
84                             &format!(
85                                 "use of `{}!({}(), ...).unwrap()`",
86                                 macro_name,
87                                 dest_name
88                             ),
89                             "try this",
90                             format!("{}{}!(\"{}\")", prefix, macro_name.replace("write", "print"), write_output.escape_default()),
91                             Applicability::MachineApplicable
92                         );
93                     } else {
94                         span_lint_and_sugg(
95                             cx,
96                             EXPLICIT_WRITE,
97                             expr.span,
98                             &format!("use of `{}().write_fmt(...).unwrap()`", dest_name),
99                             "try this",
100                             format!("{}print!(\"{}\")", prefix, write_output.escape_default()),
101                             Applicability::MachineApplicable
102                         );
103                     }
104                 } else {
105                     // We don't have a proper suggestion
106                     if let Some(macro_name) = calling_macro {
107                         span_lint(
108                             cx,
109                             EXPLICIT_WRITE,
110                             expr.span,
111                             &format!(
112                                 "use of `{}!({}(), ...).unwrap()`. Consider using `{}{}!` instead",
113                                 macro_name,
114                                 dest_name,
115                                 prefix,
116                                 macro_name.replace("write", "print")
117                             )
118                         );
119                     } else {
120                         span_lint(
121                             cx,
122                             EXPLICIT_WRITE,
123                             expr.span,
124                             &format!("use of `{}().write_fmt(...).unwrap()`. Consider using `{}print!` instead", dest_name, prefix),
125                         );
126                     }
127                 }
128
129             }
130         }
131     }
132 }
133
134 // Extract the output string from the given `write_args`.
135 fn write_output_string(write_args: &HirVec<Expr>) -> Option<String> {
136     if_chain! {
137         // Obtain the string that should be printed
138         if write_args.len() > 1;
139         if let ExprKind::Call(_, ref output_args) = write_args[1].node;
140         if output_args.len() > 0;
141         if let ExprKind::AddrOf(_, ref output_string_expr) = output_args[0].node;
142         if let ExprKind::Array(ref string_exprs) = output_string_expr.node;
143         // we only want to provide an automatic suggestion for simple (non-format) strings
144         if string_exprs.len() == 1;
145         if let ExprKind::Lit(ref lit) = string_exprs[0].node;
146         if let LitKind::Str(ref write_output, _) = lit.node;
147         then {
148             return Some(write_output.to_string())
149         }
150     }
151     None
152 }