]> git.lizzy.rs Git - rust.git/blob - src/misc_early.rs
Don't panic if cargo rustc fails
[rust.git] / src / misc_early.rs
1 use rustc::lint::*;
2 use std::collections::HashMap;
3 use syntax::ast::*;
4 use syntax::codemap::Span;
5 use syntax::visit::FnKind;
6 use utils::{span_lint, span_help_and_lint, snippet, span_lint_and_then};
7 /// **What it does:** This lint checks for structure field patterns bound to wildcards.
8 ///
9 /// **Why is this bad?** Using `..` instead is shorter and leaves the focus on the fields that are actually bound.
10 ///
11 /// **Known problems:** None.
12 ///
13 /// **Example:** `let { a: _, b: ref b, c: _ } = ..`
14 declare_lint! {
15     pub UNNEEDED_FIELD_PATTERN, Warn,
16     "Struct fields are bound to a wildcard instead of using `..`"
17 }
18
19 /// **What it does:** This lint checks for function arguments having the similar names differing by an underscore
20 ///
21 /// **Why is this bad?** It affects code readability
22 ///
23 /// **Known problems:** None.
24 ///
25 /// **Example:** `fn foo(a: i32, _a: i32) {}`
26 declare_lint! {
27     pub DUPLICATE_UNDERSCORE_ARGUMENT, Warn,
28     "Function arguments having names which only differ by an underscore"
29 }
30
31 /// **What it does:** This lint detects closures called in the same expression where they are defined.
32 ///
33 /// **Why is this bad?** It is unnecessarily adding to the expression's complexity.
34 ///
35 /// **Known problems:** None.
36 ///
37 /// **Example:** `(|| 42)()`
38 declare_lint! {
39     pub REDUNDANT_CLOSURE_CALL, Warn,
40     "Closures should not be called in the expression they are defined"
41 }
42
43 #[derive(Copy, Clone)]
44 pub struct MiscEarly;
45
46 impl LintPass for MiscEarly {
47     fn get_lints(&self) -> LintArray {
48         lint_array!(UNNEEDED_FIELD_PATTERN, DUPLICATE_UNDERSCORE_ARGUMENT, REDUNDANT_CLOSURE_CALL)
49     }
50 }
51
52 impl EarlyLintPass for MiscEarly {
53     fn check_pat(&mut self, cx: &EarlyContext, pat: &Pat) {
54         if let PatKind::Struct(ref npat, ref pfields, _) = pat.node {
55             let mut wilds = 0;
56             let type_name = npat.segments.last().expect("A path must have at least one segment").identifier.name;
57
58             for field in pfields {
59                 if field.node.pat.node == PatKind::Wild {
60                     wilds += 1;
61                 }
62             }
63             if !pfields.is_empty() && wilds == pfields.len() {
64                 span_help_and_lint(cx,
65                                    UNNEEDED_FIELD_PATTERN,
66                                    pat.span,
67                                    "All the struct fields are matched to a wildcard pattern, consider using `..`.",
68                                    &format!("Try with `{} {{ .. }}` instead", type_name));
69                 return;
70             }
71             if wilds > 0 {
72                 let mut normal = vec![];
73
74                 for field in pfields {
75                     if field.node.pat.node != PatKind::Wild {
76                         if let Ok(n) = cx.sess().codemap().span_to_snippet(field.span) {
77                             normal.push(n);
78                         }
79                     }
80                 }
81                 for field in pfields {
82                     if field.node.pat.node == PatKind::Wild {
83                         wilds -= 1;
84                         if wilds > 0 {
85                             span_lint(cx,
86                                       UNNEEDED_FIELD_PATTERN,
87                                       field.span,
88                                       "You matched a field with a wildcard pattern. Consider using `..` instead");
89                         } else {
90                             span_help_and_lint(cx,
91                                                UNNEEDED_FIELD_PATTERN,
92                                                field.span,
93                                                "You matched a field with a wildcard pattern. Consider using `..` \
94                                                 instead",
95                                                &format!("Try with `{} {{ {}, .. }}`",
96                                                         type_name,
97                                                         normal[..].join(", ")));
98                         }
99                     }
100                 }
101             }
102         }
103     }
104
105     fn check_fn(&mut self, cx: &EarlyContext, _: FnKind, decl: &FnDecl, _: &Block, _: Span, _: NodeId) {
106         let mut registered_names: HashMap<String, Span> = HashMap::new();
107
108         for ref arg in &decl.inputs {
109             if let PatKind::Ident(_, sp_ident, None) = arg.pat.node {
110                 let arg_name = sp_ident.node.to_string();
111
112                 if arg_name.starts_with('_') {
113                     if let Some(correspondence) = registered_names.get(&arg_name[1..]) {
114                         span_lint(cx,
115                                   DUPLICATE_UNDERSCORE_ARGUMENT,
116                                   *correspondence,
117                                   &format!("`{}` already exists, having another argument having almost the same \
118                                             name makes code comprehension and documentation more difficult",
119                                            arg_name[1..].to_owned()));;
120                     }
121                 } else {
122                     registered_names.insert(arg_name, arg.pat.span);
123                 }
124             }
125         }
126     }
127
128     fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
129         if let ExprKind::Call(ref paren, _) = expr.node {
130             if let ExprKind::Paren(ref closure) = paren.node {
131                 if let ExprKind::Closure(_, ref decl, ref block, _) = closure.node {
132                     span_lint_and_then(cx,
133                                        REDUNDANT_CLOSURE_CALL,
134                                        expr.span,
135                                        "Try not to call a closure in the expression where it is declared.",
136                                        |db| {
137                                            if decl.inputs.is_empty() {
138                                                let hint = format!("{}", snippet(cx, block.span, ".."));
139                                                db.span_suggestion(expr.span, "Try doing something like: ", hint);
140                                            }
141                                        });
142                 }
143             }
144         }
145     }
146
147     fn check_block(&mut self, cx: &EarlyContext, block: &Block) {
148         for w in block.stmts.windows(2) {
149             if_let_chain! {[
150                 let StmtKind::Decl(ref first, _) = w[0].node,
151                 let DeclKind::Local(ref local) = first.node,
152                 let Option::Some(ref t) = local.init,
153                 let ExprKind::Closure(_,_,_,_) = t.node,
154                 let PatKind::Ident(_,sp_ident,_) = local.pat.node,
155                 let StmtKind::Semi(ref second,_) = w[1].node,
156                 let ExprKind::Assign(_,ref call) = second.node,
157                 let ExprKind::Call(ref closure,_) = call.node,
158                 let ExprKind::Path(_,ref path) = closure.node
159             ], {
160                 if sp_ident.node == (&path.segments[0]).identifier {
161                     span_lint(cx, REDUNDANT_CLOSURE_CALL, second.span, "Closure called just once immediately after it was declared");
162                 }
163             }}
164         }
165     }
166 }