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