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