]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/formatting.rs
b10e83c0ea819e5c1c891d310d6a3b7cd3288a72
[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(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_lint_and_note(
224                 cx,
225                 SUSPICIOUS_ELSE_FORMATTING,
226                 else_span,
227                 &format!("this is an `else {}` but the formatting might hide it", else_desc),
228                 None,
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 fn indentation(cx: &EarlyContext<'_>, span: Span) -> usize {
246     cx.sess.source_map().lookup_char_pos(span.lo()).col.0
247 }
248
249 /// Implementation of the `POSSIBLE_MISSING_COMMA` lint for array
250 fn check_array(cx: &EarlyContext<'_>, expr: &Expr) {
251     if let ExprKind::Array(ref array) = expr.kind {
252         for element in array {
253             if_chain! {
254                 if let ExprKind::Binary(ref op, ref lhs, _) = element.kind;
255                 if has_unary_equivalent(op.node) && !differing_macro_contexts(lhs.span, op.span);
256                 let space_span = lhs.span.between(op.span);
257                 if let Some(space_snippet) = snippet_opt(cx, space_span);
258                 let lint_span = lhs.span.with_lo(lhs.span.hi());
259                 if space_snippet.contains('\n');
260                 if indentation(cx, op.span) <= indentation(cx, lhs.span);
261                 then {
262                     span_lint_and_note(
263                         cx,
264                         POSSIBLE_MISSING_COMMA,
265                         lint_span,
266                         "possibly missing a comma here",
267                         None,
268                         "to remove this lint, add a comma or write the expr in a single line",
269                     );
270                 }
271             }
272         }
273     }
274 }
275
276 fn check_missing_else(cx: &EarlyContext<'_>, first: &Expr, second: &Expr) {
277     if !differing_macro_contexts(first.span, second.span)
278         && !first.span.from_expansion()
279         && is_if(first)
280         && (is_block(second) || is_if(second))
281     {
282         // where the else would be
283         let else_span = first.span.between(second.span);
284
285         if let Some(else_snippet) = snippet_opt(cx, else_span) {
286             if !else_snippet.contains('\n') {
287                 let (looks_like, next_thing) = if is_if(second) {
288                     ("an `else if`", "the second `if`")
289                 } else {
290                     ("an `else {..}`", "the next block")
291                 };
292
293                 span_lint_and_note(
294                     cx,
295                     SUSPICIOUS_ELSE_FORMATTING,
296                     else_span,
297                     &format!("this looks like {} but the `else` is missing", looks_like),
298                     None,
299                     &format!(
300                         "to remove this lint, add the missing `else` or add a new line before {}",
301                         next_thing,
302                     ),
303                 );
304             }
305         }
306     }
307 }
308
309 fn is_block(expr: &Expr) -> bool {
310     matches!(expr.kind, ExprKind::Block(..))
311 }
312
313 /// Check if the expression is an `if` or `if let`
314 fn is_if(expr: &Expr) -> bool {
315     matches!(expr.kind, ExprKind::If(..))
316 }