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