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