]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/explicit_write.rs
Auto merge of #85690 - bstrie:m2_arena, r=jackh726,nagisa
[rust.git] / src / tools / clippy / clippy_lints / src / explicit_write.rs
1 use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg};
2 use clippy_utils::higher::FormatArgsExpn;
3 use clippy_utils::{is_expn_of, match_function_call, paths};
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::{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
13     /// Checks for usage of `write!()` / `writeln()!` which can be
14     /// replaced with `(e)print!()` / `(e)println!()`
15     ///
16     /// ### Why is this bad?
17     /// Using `(e)println! is clearer and more concise
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, _, [write_call], _) = expr.kind;
38             if unwrap_fun.ident.name == sym::unwrap;
39             // match call to write_fmt
40             if let ExprKind::MethodCall(write_fun, _, [write_recv, write_arg], _) = write_call.kind;
41             if write_fun.ident.name == sym!(write_fmt);
42             // match calls to std::io::stdout() / std::io::stderr ()
43             if let Some(dest_name) = if match_function_call(cx, write_recv, &paths::STDOUT).is_some() {
44                 Some("stdout")
45             } else if match_function_call(cx, write_recv, &paths::STDERR).is_some() {
46                 Some("stderr")
47             } else {
48                 None
49             };
50             if let Some(format_args) = FormatArgsExpn::parse(write_arg);
51             then {
52                 let calling_macro =
53                     // ordering is important here, since `writeln!` uses `write!` internally
54                     if is_expn_of(write_call.span, "writeln").is_some() {
55                         Some("writeln")
56                     } else if is_expn_of(write_call.span, "write").is_some() {
57                         Some("write")
58                     } else {
59                         None
60                     };
61                 let prefix = if dest_name == "stderr" {
62                     "e"
63                 } else {
64                     ""
65                 };
66
67                 // We need to remove the last trailing newline from the string because the
68                 // underlying `fmt::write` function doesn't know whether `println!` or `print!` was
69                 // used.
70                 let (used, sugg_mac) = if let Some(macro_name) = calling_macro {
71                     (
72                         format!("{}!({}(), ...)", macro_name, dest_name),
73                         macro_name.replace("write", "print"),
74                     )
75                 } else {
76                     (
77                         format!("{}().write_fmt(...)", dest_name),
78                         "print".into(),
79                     )
80                 };
81                 let msg = format!("use of `{}.unwrap()`", used);
82                 if let [write_output] = *format_args.format_string_symbols {
83                     let mut write_output = write_output.to_string();
84                     if write_output.ends_with('\n') {
85                         write_output.pop();
86                     }
87
88                     let sugg = format!("{}{}!(\"{}\")", prefix, sugg_mac, write_output.escape_default());
89                     span_lint_and_sugg(
90                         cx,
91                         EXPLICIT_WRITE,
92                         expr.span,
93                         &msg,
94                         "try this",
95                         sugg,
96                         Applicability::MachineApplicable
97                     );
98                 } else {
99                     // We don't have a proper suggestion
100                     let help = format!("consider using `{}{}!` instead", prefix, sugg_mac);
101                     span_lint_and_help(cx, EXPLICIT_WRITE, expr.span, &msg, None, &help);
102                 }
103             }
104         }
105     }
106 }