]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/explicit_write.rs
Rollup merge of #97264 - TaKO8Ki:suggest-extern-crate-when-failing-to-resolve-use...
[rust.git] / src / tools / clippy / 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::def::Res;
8 use rustc_hir::{BindingAnnotation, Block, BlockCheckMode, Expr, ExprKind, Node, PatKind, QPath, Stmt, StmtKind};
9 use rustc_lint::{LateContext, LateLintPass};
10 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 use rustc_span::sym;
12
13 declare_clippy_lint! {
14     /// ### What it does
15     /// Checks for usage of `write!()` / `writeln()!` which can be
16     /// replaced with `(e)print!()` / `(e)println!()`
17     ///
18     /// ### Why is this bad?
19     /// Using `(e)println! is clearer and more concise
20     ///
21     /// ### Example
22     /// ```rust
23     /// # use std::io::Write;
24     /// # let bar = "furchtbar";
25     /// // this would be clearer as `eprintln!("foo: {:?}", bar);`
26     /// writeln!(&mut std::io::stderr(), "foo: {:?}", bar).unwrap();
27     /// ```
28     #[clippy::version = "pre 1.29.0"]
29     pub EXPLICIT_WRITE,
30     complexity,
31     "using the `write!()` family of functions instead of the `print!()` family of functions, when using the latter would work"
32 }
33
34 declare_lint_pass!(ExplicitWrite => [EXPLICIT_WRITE]);
35
36 impl<'tcx> LateLintPass<'tcx> for ExplicitWrite {
37     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
38         if_chain! {
39             // match call to unwrap
40             if let ExprKind::MethodCall(unwrap_fun, [write_call], _) = expr.kind;
41             if unwrap_fun.ident.name == sym::unwrap;
42             // match call to write_fmt
43             if let ExprKind::MethodCall(write_fun, [write_recv, write_arg], _) = look_in_block(cx, &write_call.kind);
44             if write_fun.ident.name == sym!(write_fmt);
45             // match calls to std::io::stdout() / std::io::stderr ()
46             if let Some(dest_name) = if match_function_call(cx, write_recv, &paths::STDOUT).is_some() {
47                 Some("stdout")
48             } else if match_function_call(cx, write_recv, &paths::STDERR).is_some() {
49                 Some("stderr")
50             } else {
51                 None
52             };
53             if let Some(format_args) = FormatArgsExpn::parse(cx, write_arg);
54             then {
55                 let calling_macro =
56                     // ordering is important here, since `writeln!` uses `write!` internally
57                     if is_expn_of(write_call.span, "writeln").is_some() {
58                         Some("writeln")
59                     } else if is_expn_of(write_call.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                 let (used, sugg_mac) = if let Some(macro_name) = calling_macro {
74                     (
75                         format!("{}!({}(), ...)", macro_name, dest_name),
76                         macro_name.replace("write", "print"),
77                     )
78                 } else {
79                     (
80                         format!("{}().write_fmt(...)", dest_name),
81                         "print".into(),
82                     )
83                 };
84                 let mut applicability = Applicability::MachineApplicable;
85                 let inputs_snippet = snippet_with_applicability(
86                     cx,
87                     format_args.inputs_span(),
88                     "..",
89                     &mut applicability,
90                 );
91                 span_lint_and_sugg(
92                     cx,
93                     EXPLICIT_WRITE,
94                     expr.span,
95                     &format!("use of `{}.unwrap()`", used),
96                     "try this",
97                     format!("{}{}!({})", prefix, sugg_mac, inputs_snippet),
98                     applicability,
99                 )
100             }
101         }
102     }
103 }
104
105 /// If `kind` is a block that looks like `{ let result = $expr; result }` then
106 /// returns $expr. Otherwise returns `kind`.
107 fn look_in_block<'tcx, 'hir>(cx: &LateContext<'tcx>, kind: &'tcx ExprKind<'hir>) -> &'tcx ExprKind<'hir> {
108     if_chain! {
109         if let ExprKind::Block(block, _label @ None) = kind;
110         if let Block {
111             stmts: [Stmt { kind: StmtKind::Local(local), .. }],
112             expr: Some(expr_end_of_block),
113             rules: BlockCheckMode::DefaultBlock,
114             ..
115         } = block;
116
117         // Find id of the local that expr_end_of_block resolves to
118         if let ExprKind::Path(QPath::Resolved(None, expr_path)) = expr_end_of_block.kind;
119         if let Res::Local(expr_res) = expr_path.res;
120         if let Some(Node::Binding(res_pat)) = cx.tcx.hir().find(expr_res);
121
122         // Find id of the local we found in the block
123         if let PatKind::Binding(BindingAnnotation::Unannotated, local_hir_id, _ident, None) = local.pat.kind;
124
125         // If those two are the same hir id
126         if res_pat.hir_id == local_hir_id;
127
128         if let Some(init) = local.init;
129         then {
130             return &init.kind;
131         }
132     }
133     kind
134 }