]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/formatting.rs
Auto merge of #3511 - phansch:remove_allow_doc_markdown, r=phansch
[rust.git] / clippy_lints / src / formatting.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
11 use crate::rustc::{declare_tool_lint, lint_array};
12 use crate::syntax::ast;
13 use crate::syntax::ptr::P;
14 use crate::utils::{differing_macro_contexts, in_macro, snippet_opt, span_note_and_lint};
15
16 /// **What it does:** Checks for use of the non-existent `=*`, `=!` and `=-`
17 /// operators.
18 ///
19 /// **Why is this bad?** This is either a typo of `*=`, `!=` or `-=` or
20 /// confusing.
21 ///
22 /// **Known problems:** None.
23 ///
24 /// **Example:**
25 /// ```rust,ignore
26 /// a =- 42; // confusing, should it be `a -= 42` or `a = -42`?
27 /// ```
28 declare_clippy_lint! {
29     pub SUSPICIOUS_ASSIGNMENT_FORMATTING,
30     style,
31     "suspicious formatting of `*=`, `-=` or `!=`"
32 }
33
34 /// **What it does:** Checks for formatting of `else if`. It lints if the `else`
35 /// and `if` are not on the same line or the `else` seems to be missing.
36 ///
37 /// **Why is this bad?** This is probably some refactoring remnant, even if the
38 /// code is correct, it might look confusing.
39 ///
40 /// **Known problems:** None.
41 ///
42 /// **Example:**
43 /// ```rust,ignore
44 /// if foo {
45 /// } if bar { // looks like an `else` is missing here
46 /// }
47 ///
48 /// if foo {
49 /// } else
50 ///
51 /// if bar { // this is the `else` block of the previous `if`, but should it be?
52 /// }
53 /// ```
54 declare_clippy_lint! {
55     pub SUSPICIOUS_ELSE_FORMATTING,
56     style,
57     "suspicious formatting of `else if`"
58 }
59
60 /// **What it does:** Checks for possible missing comma in an array. It lints if
61 /// an array element is a binary operator expression and it lies on two lines.
62 ///
63 /// **Why is this bad?** This could lead to unexpected results.
64 ///
65 /// **Known problems:** None.
66 ///
67 /// **Example:**
68 /// ```rust,ignore
69 /// let a = &[
70 ///     -1, -2, -3 // <= no comma here
71 ///     -4, -5, -6
72 /// ];
73 /// ```
74 declare_clippy_lint! {
75     pub POSSIBLE_MISSING_COMMA,
76     correctness,
77     "possible missing comma in array"
78 }
79
80 #[derive(Copy, Clone)]
81 pub struct Formatting;
82
83 impl LintPass for Formatting {
84     fn get_lints(&self) -> LintArray {
85         lint_array!(
86             SUSPICIOUS_ASSIGNMENT_FORMATTING,
87             SUSPICIOUS_ELSE_FORMATTING,
88             POSSIBLE_MISSING_COMMA
89         )
90     }
91 }
92
93 impl EarlyLintPass for Formatting {
94     fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
95         for w in block.stmts.windows(2) {
96             match (&w[0].node, &w[1].node) {
97                 (&ast::StmtKind::Expr(ref first), &ast::StmtKind::Expr(ref second))
98                 | (&ast::StmtKind::Expr(ref first), &ast::StmtKind::Semi(ref second)) => {
99                     check_consecutive_ifs(cx, first, second);
100                 },
101                 _ => (),
102             }
103         }
104     }
105
106     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
107         check_assign(cx, expr);
108         check_else_if(cx, expr);
109         check_array(cx, expr);
110     }
111 }
112
113 /// Implementation of the `SUSPICIOUS_ASSIGNMENT_FORMATTING` lint.
114 fn check_assign(cx: &EarlyContext<'_>, expr: &ast::Expr) {
115     if let ast::ExprKind::Assign(ref lhs, ref rhs) = expr.node {
116         if !differing_macro_contexts(lhs.span, rhs.span) && !in_macro(lhs.span) {
117             let eq_span = lhs.span.between(rhs.span);
118             if let ast::ExprKind::Unary(op, ref sub_rhs) = rhs.node {
119                 if let Some(eq_snippet) = snippet_opt(cx, eq_span) {
120                     let op = ast::UnOp::to_string(op);
121                     let eqop_span = lhs.span.between(sub_rhs.span);
122                     if eq_snippet.ends_with('=') {
123                         span_note_and_lint(
124                             cx,
125                             SUSPICIOUS_ASSIGNMENT_FORMATTING,
126                             eqop_span,
127                             &format!(
128                                 "this looks like you are trying to use `.. {op}= ..`, but you \
129                                  really are doing `.. = ({op} ..)`",
130                                 op = op
131                             ),
132                             eqop_span,
133                             &format!("to remove this lint, use either `{op}=` or `= {op}`", op = op),
134                         );
135                     }
136                 }
137             }
138         }
139     }
140 }
141
142 /// Implementation of the `SUSPICIOUS_ELSE_FORMATTING` lint for weird `else if`.
143 fn check_else_if(cx: &EarlyContext<'_>, expr: &ast::Expr) {
144     if let Some((then, &Some(ref else_))) = unsugar_if(expr) {
145         if unsugar_if(else_).is_some() && !differing_macro_contexts(then.span, else_.span) && !in_macro(then.span) {
146             // this will be a span from the closing ‘}’ of the “then” block (excluding) to
147             // the
148             // “if” of the “else if” block (excluding)
149             let else_span = then.span.between(else_.span);
150
151             // the snippet should look like " else \n    " with maybe comments anywhere
152             // it’s bad when there is a ‘\n’ after the “else”
153             if let Some(else_snippet) = snippet_opt(cx, else_span) {
154                 let else_pos = else_snippet.find("else").expect("there must be a `else` here");
155
156                 if else_snippet[else_pos..].contains('\n') {
157                     span_note_and_lint(
158                         cx,
159                         SUSPICIOUS_ELSE_FORMATTING,
160                         else_span,
161                         "this is an `else if` but the formatting might hide it",
162                         else_span,
163                         "to remove this lint, remove the `else` or remove the new line between `else` \
164                          and `if`",
165                     );
166                 }
167             }
168         }
169     }
170 }
171
172 fn has_unary_equivalent(bin_op: ast::BinOpKind) -> bool {
173     // &, *, -
174     bin_op == ast::BinOpKind::And || bin_op == ast::BinOpKind::Mul || bin_op == ast::BinOpKind::Sub
175 }
176
177 /// Implementation of the `POSSIBLE_MISSING_COMMA` lint for array
178 fn check_array(cx: &EarlyContext<'_>, expr: &ast::Expr) {
179     if let ast::ExprKind::Array(ref array) = expr.node {
180         for element in array {
181             if let ast::ExprKind::Binary(ref op, ref lhs, _) = element.node {
182                 if has_unary_equivalent(op.node) && !differing_macro_contexts(lhs.span, op.span) {
183                     let space_span = lhs.span.between(op.span);
184                     if let Some(space_snippet) = snippet_opt(cx, space_span) {
185                         let lint_span = lhs.span.with_lo(lhs.span.hi());
186                         if space_snippet.contains('\n') {
187                             span_note_and_lint(
188                                 cx,
189                                 POSSIBLE_MISSING_COMMA,
190                                 lint_span,
191                                 "possibly missing a comma here",
192                                 lint_span,
193                                 "to remove this lint, add a comma or write the expr in a single line",
194                             );
195                         }
196                     }
197                 }
198             }
199         }
200     }
201 }
202
203 /// Implementation of the `SUSPICIOUS_ELSE_FORMATTING` lint for consecutive ifs.
204 fn check_consecutive_ifs(cx: &EarlyContext<'_>, first: &ast::Expr, second: &ast::Expr) {
205     if !differing_macro_contexts(first.span, second.span)
206         && !in_macro(first.span)
207         && unsugar_if(first).is_some()
208         && unsugar_if(second).is_some()
209     {
210         // where the else would be
211         let else_span = first.span.between(second.span);
212
213         if let Some(else_snippet) = snippet_opt(cx, else_span) {
214             if !else_snippet.contains('\n') {
215                 span_note_and_lint(
216                     cx,
217                     SUSPICIOUS_ELSE_FORMATTING,
218                     else_span,
219                     "this looks like an `else if` but the `else` is missing",
220                     else_span,
221                     "to remove this lint, add the missing `else` or add a new line before the second \
222                      `if`",
223                 );
224             }
225         }
226     }
227 }
228
229 /// Match `if` or `if let` expressions and return the `then` and `else` block.
230 fn unsugar_if(expr: &ast::Expr) -> Option<(&P<ast::Block>, &Option<P<ast::Expr>>)> {
231     match expr.node {
232         ast::ExprKind::If(_, ref then, ref else_) | ast::ExprKind::IfLet(_, _, ref then, ref else_) => {
233             Some((then, else_))
234         },
235         _ => None,
236     }
237 }