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