]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/formatting.rs
result_map_or_into_option: destructure lint tuple or return early
[rust.git] / 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             match (&w[0].kind, &w[1].kind) {
116                 (&StmtKind::Expr(ref first), &StmtKind::Expr(ref second))
117                 | (&StmtKind::Expr(ref first), &StmtKind::Semi(ref second)) => {
118                     check_missing_else(cx, first, second);
119                 },
120                 _ => (),
121             }
122         }
123     }
124
125     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
126         check_assign(cx, expr);
127         check_unop(cx, expr);
128         check_else(cx, expr);
129         check_array(cx, expr);
130     }
131 }
132
133 /// Implementation of the `SUSPICIOUS_ASSIGNMENT_FORMATTING` lint.
134 fn check_assign(cx: &EarlyContext<'_>, expr: &Expr) {
135     if let ExprKind::Assign(ref lhs, ref rhs, _) = expr.kind {
136         if !differing_macro_contexts(lhs.span, rhs.span) && !lhs.span.from_expansion() {
137             let eq_span = lhs.span.between(rhs.span);
138             if let ExprKind::Unary(op, ref sub_rhs) = rhs.kind {
139                 if let Some(eq_snippet) = snippet_opt(cx, eq_span) {
140                     let op = UnOp::to_string(op);
141                     let eqop_span = lhs.span.between(sub_rhs.span);
142                     if eq_snippet.ends_with('=') {
143                         span_lint_and_note(
144                             cx,
145                             SUSPICIOUS_ASSIGNMENT_FORMATTING,
146                             eqop_span,
147                             &format!(
148                                 "this looks like you are trying to use `.. {op}= ..`, but you \
149                                  really are doing `.. = ({op} ..)`",
150                                 op = op
151                             ),
152                             eqop_span,
153                             &format!("to remove this lint, use either `{op}=` or `= {op}`", op = op),
154                         );
155                     }
156                 }
157             }
158         }
159     }
160 }
161
162 /// Implementation of the `SUSPICIOUS_UNARY_OP_FORMATTING` lint.
163 fn check_unop(cx: &EarlyContext<'_>, expr: &Expr) {
164     if_chain! {
165         if let ExprKind::Binary(ref binop, ref lhs, ref rhs) = expr.kind;
166         if !differing_macro_contexts(lhs.span, rhs.span) && !lhs.span.from_expansion();
167         // span between BinOp LHS and RHS
168         let binop_span = lhs.span.between(rhs.span);
169         // if RHS is a UnOp
170         if let ExprKind::Unary(op, ref un_rhs) = rhs.kind;
171         // from UnOp operator to UnOp operand
172         let unop_operand_span = rhs.span.until(un_rhs.span);
173         if let Some(binop_snippet) = snippet_opt(cx, binop_span);
174         if let Some(unop_operand_snippet) = snippet_opt(cx, unop_operand_span);
175         let binop_str = BinOpKind::to_string(&binop.node);
176         // no space after BinOp operator and space after UnOp operator
177         if binop_snippet.ends_with(binop_str) && unop_operand_snippet.ends_with(' ');
178         then {
179             let unop_str = UnOp::to_string(op);
180             let eqop_span = lhs.span.between(un_rhs.span);
181             span_lint_and_help(
182                 cx,
183                 SUSPICIOUS_UNARY_OP_FORMATTING,
184                 eqop_span,
185                 &format!(
186                     "by not having a space between `{binop}` and `{unop}` it looks like \
187                      `{binop}{unop}` is a single operator",
188                     binop = binop_str,
189                     unop = unop_str
190                 ),
191                 &format!(
192                     "put a space between `{binop}` and `{unop}` and remove the space after `{unop}`",
193                     binop = binop_str,
194                     unop = unop_str
195                 ),
196             );
197         }
198     }
199 }
200
201 /// Implementation of the `SUSPICIOUS_ELSE_FORMATTING` lint for weird `else`.
202 fn check_else(cx: &EarlyContext<'_>, expr: &Expr) {
203     if_chain! {
204         if let ExprKind::If(_, then, Some(else_)) = &expr.kind;
205         if is_block(else_) || is_if(else_);
206         if !differing_macro_contexts(then.span, else_.span);
207         if !then.span.from_expansion() && !in_external_macro(cx.sess, expr.span);
208
209         // workaround for rust-lang/rust#43081
210         if expr.span.lo().0 != 0 && expr.span.hi().0 != 0;
211
212         // this will be a span from the closing ‘}’ of the “then” block (excluding) to
213         // the “if” of the “else if” block (excluding)
214         let else_span = then.span.between(else_.span);
215
216         // the snippet should look like " else \n    " with maybe comments anywhere
217         // it’s bad when there is a ‘\n’ after the “else”
218         if let Some(else_snippet) = snippet_opt(cx, else_span);
219         if let Some(else_pos) = else_snippet.find("else");
220         if else_snippet[else_pos..].contains('\n');
221         let else_desc = if is_if(else_) { "if" } else { "{..}" };
222
223         then {
224             span_lint_and_note(
225                 cx,
226                 SUSPICIOUS_ELSE_FORMATTING,
227                 else_span,
228                 &format!("this is an `else {}` but the formatting might hide it", else_desc),
229                 else_span,
230                 &format!(
231                     "to remove this lint, remove the `else` or remove the new line between \
232                      `else` and `{}`",
233                     else_desc,
234                 ),
235             );
236         }
237     }
238 }
239
240 #[must_use]
241 fn has_unary_equivalent(bin_op: BinOpKind) -> bool {
242     // &, *, -
243     bin_op == BinOpKind::And || bin_op == BinOpKind::Mul || bin_op == BinOpKind::Sub
244 }
245
246 fn indentation(cx: &EarlyContext<'_>, span: Span) -> usize {
247     cx.sess.source_map().lookup_char_pos(span.lo()).col.0
248 }
249
250 /// Implementation of the `POSSIBLE_MISSING_COMMA` lint for array
251 fn check_array(cx: &EarlyContext<'_>, expr: &Expr) {
252     if let ExprKind::Array(ref array) = expr.kind {
253         for element in array {
254             if_chain! {
255                 if let ExprKind::Binary(ref op, ref lhs, _) = element.kind;
256                 if has_unary_equivalent(op.node) && !differing_macro_contexts(lhs.span, op.span);
257                 let space_span = lhs.span.between(op.span);
258                 if let Some(space_snippet) = snippet_opt(cx, space_span);
259                 let lint_span = lhs.span.with_lo(lhs.span.hi());
260                 if space_snippet.contains('\n');
261                 if indentation(cx, op.span) <= indentation(cx, lhs.span);
262                 then {
263                     span_lint_and_note(
264                         cx,
265                         POSSIBLE_MISSING_COMMA,
266                         lint_span,
267                         "possibly missing a comma here",
268                         lint_span,
269                         "to remove this lint, add a comma or write the expr in a single line",
270                     );
271                 }
272             }
273         }
274     }
275 }
276
277 fn check_missing_else(cx: &EarlyContext<'_>, first: &Expr, second: &Expr) {
278     if !differing_macro_contexts(first.span, second.span)
279         && !first.span.from_expansion()
280         && is_if(first)
281         && (is_block(second) || is_if(second))
282     {
283         // where the else would be
284         let else_span = first.span.between(second.span);
285
286         if let Some(else_snippet) = snippet_opt(cx, else_span) {
287             if !else_snippet.contains('\n') {
288                 let (looks_like, next_thing) = if is_if(second) {
289                     ("an `else if`", "the second `if`")
290                 } else {
291                     ("an `else {..}`", "the next block")
292                 };
293
294                 span_lint_and_note(
295                     cx,
296                     SUSPICIOUS_ELSE_FORMATTING,
297                     else_span,
298                     &format!("this looks like {} but the `else` is missing", looks_like),
299                     else_span,
300                     &format!(
301                         "to remove this lint, add the missing `else` or add a new line before {}",
302                         next_thing,
303                     ),
304                 );
305             }
306         }
307     }
308 }
309
310 fn is_block(expr: &Expr) -> bool {
311     if let ExprKind::Block(..) = expr.kind {
312         true
313     } else {
314         false
315     }
316 }
317
318 /// Check if the expression is an `if` or `if let`
319 fn is_if(expr: &Expr) -> bool {
320     if let ExprKind::If(..) = expr.kind {
321         true
322     } else {
323         false
324     }
325 }