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