1 use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_note};
2 use clippy_utils::is_span_if;
3 use clippy_utils::source::snippet_opt;
4 use if_chain::if_chain;
5 use rustc_ast::ast::{BinOpKind, Block, Expr, ExprKind, StmtKind, UnOp};
6 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
7 use rustc_middle::lint::in_external_macro;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::source_map::Span;
10
11 declare_clippy_lint! {
12 /// ### What it does
13 /// Checks for usage of the non-existent `=*`, `=!` and `=-`
14 /// operators.
15 ///
16 /// ### Why is this bad?
17 /// This is either a typo of `*=`, `!=` or `-=` or
18 /// confusing.
19 ///
20 /// ### Example
21 /// ```rust,ignore
22 /// a =- 42; // confusing, should it be `a -= 42` or `a = -42`?
23 /// ```
24 #[clippy::version = "pre 1.29.0"]
25 pub SUSPICIOUS_ASSIGNMENT_FORMATTING,
26 suspicious,
27 "suspicious formatting of `*=`, `-=` or `!=`"
28 }
29
30 declare_clippy_lint! {
31 /// ### What it does
32 /// Checks the formatting of a unary operator on the right hand side
33 /// of a binary operator. It lints if there is no space between the binary and unary operators,
34 /// but there is a space between the unary and its operand.
35 ///
36 /// ### Why is this bad?
37 /// This is either a typo in the binary operator or confusing.
38 ///
39 /// ### Example
40 /// ```rust
41 /// # let foo = true;
42 /// # let bar = false;
43 /// // &&! looks like a different operator
44 /// if foo &&! bar {}
45 /// ```
46 ///
47 /// Use instead:
48 /// ```rust
49 /// # let foo = true;
50 /// # let bar = false;
51 /// if foo && !bar {}
52 /// ```
53 #[clippy::version = "1.40.0"]
54 pub SUSPICIOUS_UNARY_OP_FORMATTING,
55 suspicious,
56 "suspicious formatting of unary `-` or `!` on the RHS of a BinOp"
57 }
58
59 declare_clippy_lint! {
60 /// ### What it does
61 /// Checks for formatting of `else`. It lints if the `else`
62 /// is followed immediately by a newline or the `else` seems to be missing.
63 ///
64 /// ### Why is this bad?
65 /// This is probably some refactoring remnant, even if the
66 /// code is correct, it might look confusing.
67 ///
68 /// ### Example
69 /// ```rust,ignore
70 /// if foo {
71 /// } { // looks like an `else` is missing here
72 /// }
73 ///
74 /// if foo {
75 /// } if bar { // looks like an `else` is missing here
76 /// }
77 ///
78 /// if foo {
79 /// } else
80 ///
81 /// { // this is the `else` block of the previous `if`, but should it be?
82 /// }
83 ///
84 /// if foo {
85 /// } else
86 ///
87 /// if bar { // this is the `else` block of the previous `if`, but should it be?
88 /// }
89 /// ```
90 #[clippy::version = "pre 1.29.0"]
91 pub SUSPICIOUS_ELSE_FORMATTING,
92 suspicious,
93 "suspicious formatting of `else`"
94 }
95
96 declare_clippy_lint! {
97 /// ### What it does
98 /// Checks for possible missing comma in an array. It lints if
99 /// an array element is a binary operator expression and it lies on two lines.
100 ///
101 /// ### Why is this bad?
102 /// This could lead to unexpected results.
103 ///
104 /// ### Example
105 /// ```rust,ignore
106 /// let a = &[
107 /// -1, -2, -3 // <= no comma here
108 /// -4, -5, -6
109 /// ];
110 /// ```
111 #[clippy::version = "pre 1.29.0"]
112 pub POSSIBLE_MISSING_COMMA,
113 correctness,
114 "possible missing comma in array"
115 }
116
117 declare_lint_pass!(Formatting => [
118 SUSPICIOUS_ASSIGNMENT_FORMATTING,
119 SUSPICIOUS_UNARY_OP_FORMATTING,
120 SUSPICIOUS_ELSE_FORMATTING,
121 POSSIBLE_MISSING_COMMA
122 ]);
123
124 impl EarlyLintPass for Formatting {
check_block(&mut self, cx: &EarlyContext<'_>, block: &Block)125 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &Block) {
126 for w in block.stmts.windows(2) {
127 if let (StmtKind::Expr(first), StmtKind::Expr(second) | StmtKind::Semi(second)) = (&w[0].kind, &w[1].kind) {
128 check_missing_else(cx, first, second);
129 }
130 }
131 }
132
check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr)133 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
134 check_assign(cx, expr);
135 check_unop(cx, expr);
136 check_else(cx, expr);
137 check_array(cx, expr);
138 }
139 }
140
141 /// Implementation of the `SUSPICIOUS_ASSIGNMENT_FORMATTING` lint.
check_assign(cx: &EarlyContext<'_>, expr: &Expr)142 fn check_assign(cx: &EarlyContext<'_>, expr: &Expr) {
143 if let ExprKind::Assign(ref lhs, ref rhs, _) = expr.kind {
144 if !lhs.span.from_expansion() && !rhs.span.from_expansion() {
145 let eq_span = lhs.span.between(rhs.span);
146 if let ExprKind::Unary(op, ref sub_rhs) = rhs.kind {
147 if let Some(eq_snippet) = snippet_opt(cx, eq_span) {
148 let op = UnOp::to_string(op);
149 let eqop_span = lhs.span.between(sub_rhs.span);
150 if eq_snippet.ends_with('=') {
151 span_lint_and_note(
152 cx,
153 SUSPICIOUS_ASSIGNMENT_FORMATTING,
154 eqop_span,
155 &format!(
156 "this looks like you are trying to use `.. {op}= ..`, but you \
157 really are doing `.. = ({op} ..)`"
158 ),
159 None,
160 &format!("to remove this lint, use either `{op}=` or `= {op}`"),
161 );
162 }
163 }
164 }
165 }
166 }
167 }
168
169 /// Implementation of the `SUSPICIOUS_UNARY_OP_FORMATTING` lint.
check_unop(cx: &EarlyContext<'_>, expr: &Expr)170 fn check_unop(cx: &EarlyContext<'_>, expr: &Expr) {
171 if_chain! {
172 if let ExprKind::Binary(ref binop, ref lhs, ref rhs) = expr.kind;
173 if !lhs.span.from_expansion() && !rhs.span.from_expansion();
174 // span between BinOp LHS and RHS
175 let binop_span = lhs.span.between(rhs.span);
176 // if RHS is an UnOp
177 if let ExprKind::Unary(op, ref un_rhs) = rhs.kind;
178 // from UnOp operator to UnOp operand
179 let unop_operand_span = rhs.span.until(un_rhs.span);
180 if let Some(binop_snippet) = snippet_opt(cx, binop_span);
181 if let Some(unop_operand_snippet) = snippet_opt(cx, unop_operand_span);
182 let binop_str = BinOpKind::to_string(&binop.node);
183 // no space after BinOp operator and space after UnOp operator
184 if binop_snippet.ends_with(binop_str) && unop_operand_snippet.ends_with(' ');
185 then {
186 let unop_str = UnOp::to_string(op);
187 let eqop_span = lhs.span.between(un_rhs.span);
188 span_lint_and_help(
189 cx,
190 SUSPICIOUS_UNARY_OP_FORMATTING,
191 eqop_span,
192 &format!(
193 "by not having a space between `{binop_str}` and `{unop_str}` it looks like \
194 `{binop_str}{unop_str}` is a single operator"
195 ),
196 None,
197 &format!(
198 "put a space between `{binop_str}` and `{unop_str}` and remove the space after `{unop_str}`"
199 ),
200 );
201 }
202 }
203 }
204
205 /// Implementation of the `SUSPICIOUS_ELSE_FORMATTING` lint for weird `else`.
check_else(cx: &EarlyContext<'_>, expr: &Expr)206 fn check_else(cx: &EarlyContext<'_>, expr: &Expr) {
207 if_chain! {
208 if let ExprKind::If(_, then, Some(else_)) = &expr.kind;
209 if is_block(else_) || is_if(else_);
210 if !then.span.from_expansion() && !else_.span.from_expansion();
211 if !in_external_macro(cx.sess(), expr.span);
212
213 // workaround for rust-lang/rust#43081
214 if expr.span.lo().0 != 0 && expr.span.hi().0 != 0;
215
216 // this will be a span from the closing ‘}’ of the “then” block (excluding) to
217 // the “if” of the “else if” block (excluding)
218 let else_span = then.span.between(else_.span);
219
220 // the snippet should look like " else \n " with maybe comments anywhere
221 // it’s bad when there is a ‘\n’ after the “else”
222 if let Some(else_snippet) = snippet_opt(cx, else_span);
223 if let Some((pre_else, post_else)) = else_snippet.split_once("else");
224 if let Some((_, post_else_post_eol)) = post_else.split_once('\n');
225
226 then {
227 // Allow allman style braces `} \n else \n {`
228 if_chain! {
229 if is_block(else_);
230 if let Some((_, pre_else_post_eol)) = pre_else.split_once('\n');
231 // Exactly one eol before and after the else
232 if !pre_else_post_eol.contains('\n');
233 if !post_else_post_eol.contains('\n');
234 then {
235 return;
236 }
237 }
238
239 // Don't warn if the only thing inside post_else_post_eol is a comment block.
240 let trimmed_post_else_post_eol = post_else_post_eol.trim();
241 if trimmed_post_else_post_eol.starts_with("/*") && trimmed_post_else_post_eol.ends_with("*/") {
242 return
243 }
244
245 let else_desc = if is_if(else_) { "if" } else { "{..}" };
246 span_lint_and_note(
247 cx,
248 SUSPICIOUS_ELSE_FORMATTING,
249 else_span,
250 &format!("this is an `else {else_desc}` but the formatting might hide it"),
251 None,
252 &format!(
253 "to remove this lint, remove the `else` or remove the new line between \
254 `else` and `{else_desc}`",
255 ),
256 );
257 }
258 }
259 }
260
261 #[must_use]
has_unary_equivalent(bin_op: BinOpKind) -> bool262 fn has_unary_equivalent(bin_op: BinOpKind) -> bool {
263 // &, *, -
264 bin_op == BinOpKind::And || bin_op == BinOpKind::Mul || bin_op == BinOpKind::Sub
265 }
266
indentation(cx: &EarlyContext<'_>, span: Span) -> usize267 fn indentation(cx: &EarlyContext<'_>, span: Span) -> usize {
268 cx.sess().source_map().lookup_char_pos(span.lo()).col.0
269 }
270
271 /// Implementation of the `POSSIBLE_MISSING_COMMA` lint for array
check_array(cx: &EarlyContext<'_>, expr: &Expr)272 fn check_array(cx: &EarlyContext<'_>, expr: &Expr) {
273 if let ExprKind::Array(ref array) = expr.kind {
274 for element in array {
275 if_chain! {
276 if let ExprKind::Binary(ref op, ref lhs, _) = element.kind;
277 if has_unary_equivalent(op.node) && lhs.span.ctxt() == op.span.ctxt();
278 let space_span = lhs.span.between(op.span);
279 if let Some(space_snippet) = snippet_opt(cx, space_span);
280 let lint_span = lhs.span.with_lo(lhs.span.hi());
281 if space_snippet.contains('\n');
282 if indentation(cx, op.span) <= indentation(cx, lhs.span);
283 then {
284 span_lint_and_note(
285 cx,
286 POSSIBLE_MISSING_COMMA,
287 lint_span,
288 "possibly missing a comma here",
289 None,
290 "to remove this lint, add a comma or write the expr in a single line",
291 );
292 }
293 }
294 }
295 }
296 }
297
check_missing_else(cx: &EarlyContext<'_>, first: &Expr, second: &Expr)298 fn check_missing_else(cx: &EarlyContext<'_>, first: &Expr, second: &Expr) {
299 if_chain! {
300 if !first.span.from_expansion() && !second.span.from_expansion();
301 if matches!(first.kind, ExprKind::If(..));
302 if is_block(second) || is_if(second);
303
304 // Proc-macros can give weird spans. Make sure this is actually an `if`.
305 if is_span_if(cx, first.span);
306
307 // If there is a line break between the two expressions, don't lint.
308 // If there is a non-whitespace character, this span came from a proc-macro.
309 let else_span = first.span.between(second.span);
310 if let Some(else_snippet) = snippet_opt(cx, else_span);
311 if !else_snippet.chars().any(|c| c == '\n' || !c.is_whitespace());
312 then {
313 let (looks_like, next_thing) = if is_if(second) {
314 ("an `else if`", "the second `if`")
315 } else {
316 ("an `else {..}`", "the next block")
317 };
318
319 span_lint_and_note(
320 cx,
321 SUSPICIOUS_ELSE_FORMATTING,
322 else_span,
323 &format!("this looks like {looks_like} but the `else` is missing"),
324 None,
325 &format!(
326 "to remove this lint, add the missing `else` or add a new line before {next_thing}",
327 ),
328 );
329 }
330 }
331 }
332
is_block(expr: &Expr) -> bool333 fn is_block(expr: &Expr) -> bool {
334 matches!(expr.kind, ExprKind::Block(..))
335 }
336
337 /// Check if the expression is an `if` or `if let`
is_if(expr: &Expr) -> bool338 fn is_if(expr: &Expr) -> bool {
339 matches!(expr.kind, ExprKind::If(..))
340 }
341