]>
Commit | Line | Data |
---|---|---|
5099ac24 FG |
1 | use clippy_utils::diagnostics::span_lint_and_sugg; |
2 | use clippy_utils::macros::FormatArgsExpn; | |
3 | use clippy_utils::source::snippet_with_applicability; | |
cdc7bbd5 | 4 | use clippy_utils::{is_expn_of, match_function_call, paths}; |
f20569fa | 5 | use if_chain::if_chain; |
f20569fa | 6 | use rustc_errors::Applicability; |
923072b8 FG |
7 | use rustc_hir::def::Res; |
8 | use rustc_hir::{BindingAnnotation, Block, BlockCheckMode, Expr, ExprKind, Node, PatKind, QPath, Stmt, StmtKind}; | |
f20569fa XL |
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! { | |
94222f64 XL |
14 | /// ### What it does |
15 | /// Checks for usage of `write!()` / `writeln()!` which can be | |
f20569fa XL |
16 | /// replaced with `(e)print!()` / `(e)println!()` |
17 | /// | |
94222f64 XL |
18 | /// ### Why is this bad? |
19 | /// Using `(e)println! is clearer and more concise | |
f20569fa | 20 | /// |
94222f64 | 21 | /// ### Example |
f20569fa XL |
22 | /// ```rust |
23 | /// # use std::io::Write; | |
24 | /// # let bar = "furchtbar"; | |
f20569fa | 25 | /// writeln!(&mut std::io::stderr(), "foo: {:?}", bar).unwrap(); |
923072b8 FG |
26 | /// writeln!(&mut std::io::stdout(), "foo: {:?}", bar).unwrap(); |
27 | /// ``` | |
28 | /// | |
29 | /// Use instead: | |
30 | /// ```rust | |
31 | /// # use std::io::Write; | |
32 | /// # let bar = "furchtbar"; | |
33 | /// eprintln!("foo: {:?}", bar); | |
34 | /// println!("foo: {:?}", bar); | |
f20569fa | 35 | /// ``` |
a2a8927a | 36 | #[clippy::version = "pre 1.29.0"] |
f20569fa XL |
37 | pub EXPLICIT_WRITE, |
38 | complexity, | |
39 | "using the `write!()` family of functions instead of the `print!()` family of functions, when using the latter would work" | |
40 | } | |
41 | ||
42 | declare_lint_pass!(ExplicitWrite => [EXPLICIT_WRITE]); | |
43 | ||
44 | impl<'tcx> LateLintPass<'tcx> for ExplicitWrite { | |
45 | fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { | |
46 | if_chain! { | |
47 | // match call to unwrap | |
5099ac24 | 48 | if let ExprKind::MethodCall(unwrap_fun, [write_call], _) = expr.kind; |
f20569fa XL |
49 | if unwrap_fun.ident.name == sym::unwrap; |
50 | // match call to write_fmt | |
923072b8 | 51 | if let ExprKind::MethodCall(write_fun, [write_recv, write_arg], _) = look_in_block(cx, &write_call.kind); |
f20569fa XL |
52 | if write_fun.ident.name == sym!(write_fmt); |
53 | // match calls to std::io::stdout() / std::io::stderr () | |
136023e0 | 54 | if let Some(dest_name) = if match_function_call(cx, write_recv, &paths::STDOUT).is_some() { |
f20569fa | 55 | Some("stdout") |
136023e0 | 56 | } else if match_function_call(cx, write_recv, &paths::STDERR).is_some() { |
f20569fa XL |
57 | Some("stderr") |
58 | } else { | |
59 | None | |
60 | }; | |
5099ac24 | 61 | if let Some(format_args) = FormatArgsExpn::parse(cx, write_arg); |
f20569fa | 62 | then { |
f20569fa XL |
63 | let calling_macro = |
64 | // ordering is important here, since `writeln!` uses `write!` internally | |
136023e0 | 65 | if is_expn_of(write_call.span, "writeln").is_some() { |
f20569fa | 66 | Some("writeln") |
136023e0 | 67 | } else if is_expn_of(write_call.span, "write").is_some() { |
f20569fa XL |
68 | Some("write") |
69 | } else { | |
70 | None | |
71 | }; | |
72 | let prefix = if dest_name == "stderr" { | |
73 | "e" | |
74 | } else { | |
75 | "" | |
76 | }; | |
77 | ||
78 | // We need to remove the last trailing newline from the string because the | |
79 | // underlying `fmt::write` function doesn't know whether `println!` or `print!` was | |
80 | // used. | |
136023e0 XL |
81 | let (used, sugg_mac) = if let Some(macro_name) = calling_macro { |
82 | ( | |
83 | format!("{}!({}(), ...)", macro_name, dest_name), | |
84 | macro_name.replace("write", "print"), | |
85 | ) | |
86 | } else { | |
87 | ( | |
88 | format!("{}().write_fmt(...)", dest_name), | |
89 | "print".into(), | |
90 | ) | |
91 | }; | |
5099ac24 FG |
92 | let mut applicability = Applicability::MachineApplicable; |
93 | let inputs_snippet = snippet_with_applicability( | |
94 | cx, | |
95 | format_args.inputs_span(), | |
96 | "..", | |
97 | &mut applicability, | |
98 | ); | |
99 | span_lint_and_sugg( | |
100 | cx, | |
101 | EXPLICIT_WRITE, | |
102 | expr.span, | |
103 | &format!("use of `{}.unwrap()`", used), | |
104 | "try this", | |
105 | format!("{}{}!({})", prefix, sugg_mac, inputs_snippet), | |
106 | applicability, | |
107 | ) | |
f20569fa XL |
108 | } |
109 | } | |
110 | } | |
111 | } | |
923072b8 FG |
112 | |
113 | /// If `kind` is a block that looks like `{ let result = $expr; result }` then | |
114 | /// returns $expr. Otherwise returns `kind`. | |
115 | fn look_in_block<'tcx, 'hir>(cx: &LateContext<'tcx>, kind: &'tcx ExprKind<'hir>) -> &'tcx ExprKind<'hir> { | |
116 | if_chain! { | |
117 | if let ExprKind::Block(block, _label @ None) = kind; | |
118 | if let Block { | |
119 | stmts: [Stmt { kind: StmtKind::Local(local), .. }], | |
120 | expr: Some(expr_end_of_block), | |
121 | rules: BlockCheckMode::DefaultBlock, | |
122 | .. | |
123 | } = block; | |
124 | ||
125 | // Find id of the local that expr_end_of_block resolves to | |
126 | if let ExprKind::Path(QPath::Resolved(None, expr_path)) = expr_end_of_block.kind; | |
127 | if let Res::Local(expr_res) = expr_path.res; | |
128 | if let Some(Node::Binding(res_pat)) = cx.tcx.hir().find(expr_res); | |
129 | ||
130 | // Find id of the local we found in the block | |
131 | if let PatKind::Binding(BindingAnnotation::Unannotated, local_hir_id, _ident, None) = local.pat.kind; | |
132 | ||
133 | // If those two are the same hir id | |
134 | if res_pat.hir_id == local_hir_id; | |
135 | ||
136 | if let Some(init) = local.init; | |
137 | then { | |
138 | return &init.kind; | |
139 | } | |
140 | } | |
141 | kind | |
142 | } |