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