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