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