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