]> git.lizzy.rs Git - rust.git/blob - src/formatting.rs
Rustup to *1.10.0-nightly (cd6a40017 2016-05-16)*
[rust.git] / src / formatting.rs
1 use rustc::lint::*;
2 use syntax::codemap::mk_sp;
3 use syntax::ast;
4 use utils::{differing_macro_contexts, in_macro, snippet_opt, span_note_and_lint};
5 use syntax::ptr::P;
6
7 /// **What it does:** This lint looks for use of the non-existent `=*`, `=!` and `=-` operators.
8 ///
9 /// **Why is this bad?** This is either a typo of `*=`, `!=` or `-=` or confusing.
10 ///
11 /// **Known problems:** None.
12 ///
13 /// **Example:**
14 /// ```rust,ignore
15 /// a =- 42; // confusing, should it be `a -= 42` or `a = -42`?
16 /// ```
17 declare_lint! {
18     pub SUSPICIOUS_ASSIGNMENT_FORMATTING,
19     Warn,
20     "suspicious formatting of `*=`, `-=` or `!=`"
21 }
22
23 /// **What it does:** This lint checks for formatting of `else if`. It lints if the `else` and `if`
24 /// are not on the same line or the `else` seems to be missing.
25 ///
26 /// **Why is this bad?** This is probably some refactoring remnant, even if the code is correct, it
27 /// might look confusing.
28 ///
29 /// **Known problems:** None.
30 ///
31 /// **Example:**
32 /// ```rust,ignore
33 /// if foo {
34 /// } if bar { // looks like an `else` is missing here
35 /// }
36 ///
37 /// if foo {
38 /// } else
39 ///
40 /// if bar { // this is the `else` block of the previous `if`, but should it be?
41 /// }
42 /// ```
43 declare_lint! {
44     pub SUSPICIOUS_ELSE_FORMATTING,
45     Warn,
46     "suspicious formatting of `else if`"
47 }
48
49 #[derive(Copy,Clone)]
50 pub struct Formatting;
51
52 impl LintPass for Formatting {
53     fn get_lints(&self) -> LintArray {
54         lint_array![SUSPICIOUS_ASSIGNMENT_FORMATTING, SUSPICIOUS_ELSE_FORMATTING]
55     }
56 }
57
58 impl EarlyLintPass for Formatting {
59     fn check_block(&mut self, cx: &EarlyContext, block: &ast::Block) {
60         for w in block.stmts.windows(2) {
61             match (&w[0].node, &w[1].node) {
62                 (&ast::StmtKind::Expr(ref first, _), &ast::StmtKind::Expr(ref second, _)) |
63                 (&ast::StmtKind::Expr(ref first, _), &ast::StmtKind::Semi(ref second, _)) => {
64                     check_consecutive_ifs(cx, first, second);
65                 }
66                 _ => (),
67             }
68         }
69
70         if let Some(ref expr) = block.expr {
71             if let Some(ref stmt) = block.stmts.iter().last() {
72                 if let ast::StmtKind::Expr(ref first, _) = stmt.node {
73                     check_consecutive_ifs(cx, first, expr);
74                 }
75             }
76         }
77     }
78
79     fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
80         check_assign(cx, expr);
81         check_else_if(cx, expr);
82     }
83 }
84
85 /// Implementation of the `SUSPICIOUS_ASSIGNMENT_FORMATTING` lint.
86 fn check_assign(cx: &EarlyContext, expr: &ast::Expr) {
87     if let ast::ExprKind::Assign(ref lhs, ref rhs) = expr.node {
88         if !differing_macro_contexts(lhs.span, rhs.span) && !in_macro(cx, lhs.span) {
89             let eq_span = mk_sp(lhs.span.hi, rhs.span.lo);
90
91             if let ast::ExprKind::Unary(op, ref sub_rhs) = rhs.node {
92                 if let Some(eq_snippet) = snippet_opt(cx, eq_span) {
93                     let op = ast::UnOp::to_string(op);
94                     let eqop_span = mk_sp(lhs.span.hi, sub_rhs.span.lo);
95                     if eq_snippet.ends_with('=') {
96                         span_note_and_lint(cx,
97                                            SUSPICIOUS_ASSIGNMENT_FORMATTING,
98                                            eqop_span,
99                                            &format!("this looks like you are trying to use `.. {op}= ..`, but you \
100                                                      really are doing `.. = ({op} ..)`",
101                                                     op = op),
102                                            eqop_span,
103                                            &format!("to remove this lint, use either `{op}=` or `= {op}`", op = op));
104                     }
105                 }
106             }
107         }
108     }
109 }
110
111 /// Implementation of the `SUSPICIOUS_ELSE_FORMATTING` lint for weird `else if`.
112 fn check_else_if(cx: &EarlyContext, expr: &ast::Expr) {
113     if let Some((then, &Some(ref else_))) = unsugar_if(expr) {
114         if unsugar_if(else_).is_some() && !differing_macro_contexts(then.span, else_.span) && !in_macro(cx, then.span) {
115             // this will be a span from the closing ‘}’ of the “then” block (excluding) to the
116             // “if” of the “else if” block (excluding)
117             let else_span = mk_sp(then.span.hi, else_.span.lo);
118
119             // the snippet should look like " else \n    " with maybe comments anywhere
120             // it’s bad when there is a ‘\n’ after the “else”
121             if let Some(else_snippet) = snippet_opt(cx, else_span) {
122                 let else_pos = else_snippet.find("else").expect("there must be a `else` here");
123
124                 if else_snippet[else_pos..].contains('\n') {
125                     span_note_and_lint(cx,
126                                        SUSPICIOUS_ELSE_FORMATTING,
127                                        else_span,
128                                        "this is an `else if` but the formatting might hide it",
129                                        else_span,
130                                        "to remove this lint, remove the `else` or remove the new line between `else` \
131                                         and `if`");
132                 }
133             }
134         }
135     }
136 }
137
138 /// Implementation of the `SUSPICIOUS_ELSE_FORMATTING` lint for consecutive ifs.
139 fn check_consecutive_ifs(cx: &EarlyContext, first: &ast::Expr, second: &ast::Expr) {
140     if !differing_macro_contexts(first.span, second.span) && !in_macro(cx, first.span) &&
141        unsugar_if(first).is_some() && unsugar_if(second).is_some() {
142         // where the else would be
143         let else_span = mk_sp(first.span.hi, second.span.lo);
144
145         if let Some(else_snippet) = snippet_opt(cx, else_span) {
146             if !else_snippet.contains('\n') {
147                 span_note_and_lint(cx,
148                                    SUSPICIOUS_ELSE_FORMATTING,
149                                    else_span,
150                                    "this looks like an `else if` but the `else` is missing",
151                                    else_span,
152                                    "to remove this lint, add the missing `else` or add a new line before the second \
153                                     `if`");
154             }
155         }
156     }
157 }
158
159 /// Match `if` or `else if` expressions and return the `then` and `else` block.
160 fn unsugar_if(expr: &ast::Expr) -> Option<(&P<ast::Block>, &Option<P<ast::Expr>>)> {
161     match expr.node {
162         ast::ExprKind::If(_, ref then, ref else_) |
163         ast::ExprKind::IfLet(_, _, ref then, ref else_) => Some((then, else_)),
164         _ => None,
165     }
166 }