]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/explicit_write.rs
Make docs more consistent
[rust.git] / clippy_lints / src / explicit_write.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::macros::FormatArgsExpn;
3 use clippy_utils::source::snippet_with_applicability;
4 use clippy_utils::{is_expn_of, match_function_call, paths};
5 use if_chain::if_chain;
6 use rustc_errors::Applicability;
7 use rustc_hir::{Expr, ExprKind};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::sym;
11
12 declare_clippy_lint! {
13     /// ### What it does
14     /// Checks for usage of `write!()` / `writeln()!` which can be
15     /// replaced with `(e)print!()` / `(e)println!()`
16     ///
17     /// ### Why is this bad?
18     /// Using `(e)println! is clearer and more concise
19     ///
20     /// ### Example
21     /// ```rust
22     /// # use std::io::Write;
23     /// # let bar = "furchtbar";
24     /// writeln!(&mut std::io::stderr(), "foo: {:?}", bar).unwrap();
25     /// writeln!(&mut std::io::stdout(), "foo: {:?}", bar).unwrap();
26     /// ```
27     ///
28     /// Use instead:
29     /// ```rust
30     /// # use std::io::Write;
31     /// # let bar = "furchtbar";
32     /// eprintln!("foo: {:?}", bar);
33     /// println!("foo: {:?}", bar);
34     /// ```
35     #[clippy::version = "pre 1.29.0"]
36     pub EXPLICIT_WRITE,
37     complexity,
38     "using the `write!()` family of functions instead of the `print!()` family of functions, when using the latter would work"
39 }
40
41 declare_lint_pass!(ExplicitWrite => [EXPLICIT_WRITE]);
42
43 impl<'tcx> LateLintPass<'tcx> for ExplicitWrite {
44     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
45         if_chain! {
46             // match call to unwrap
47             if let ExprKind::MethodCall(unwrap_fun, [write_call], _) = expr.kind;
48             if unwrap_fun.ident.name == sym::unwrap;
49             // match call to write_fmt
50             if let ExprKind::MethodCall(write_fun, [write_recv, write_arg], _) = write_call.kind;
51             if write_fun.ident.name == sym!(write_fmt);
52             // match calls to std::io::stdout() / std::io::stderr ()
53             if let Some(dest_name) = if match_function_call(cx, write_recv, &paths::STDOUT).is_some() {
54                 Some("stdout")
55             } else if match_function_call(cx, write_recv, &paths::STDERR).is_some() {
56                 Some("stderr")
57             } else {
58                 None
59             };
60             if let Some(format_args) = FormatArgsExpn::parse(cx, write_arg);
61             then {
62                 let calling_macro =
63                     // ordering is important here, since `writeln!` uses `write!` internally
64                     if is_expn_of(write_call.span, "writeln").is_some() {
65                         Some("writeln")
66                     } else if is_expn_of(write_call.span, "write").is_some() {
67                         Some("write")
68                     } else {
69                         None
70                     };
71                 let prefix = if dest_name == "stderr" {
72                     "e"
73                 } else {
74                     ""
75                 };
76
77                 // We need to remove the last trailing newline from the string because the
78                 // underlying `fmt::write` function doesn't know whether `println!` or `print!` was
79                 // used.
80                 let (used, sugg_mac) = if let Some(macro_name) = calling_macro {
81                     (
82                         format!("{}!({}(), ...)", macro_name, dest_name),
83                         macro_name.replace("write", "print"),
84                     )
85                 } else {
86                     (
87                         format!("{}().write_fmt(...)", dest_name),
88                         "print".into(),
89                     )
90                 };
91                 let mut applicability = Applicability::MachineApplicable;
92                 let inputs_snippet = snippet_with_applicability(
93                     cx,
94                     format_args.inputs_span(),
95                     "..",
96                     &mut applicability,
97                 );
98                 span_lint_and_sugg(
99                     cx,
100                     EXPLICIT_WRITE,
101                     expr.span,
102                     &format!("use of `{}.unwrap()`", used),
103                     "try this",
104                     format!("{}{}!({})", prefix, sugg_mac, inputs_snippet),
105                     applicability,
106                 )
107             }
108         }
109     }
110 }