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