]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/author.rs
Merge branch 'pr-2140'
[rust.git] / clippy_lints / src / utils / author.rs
1 //! A group of attributes that can be attached to Rust code in order
2 //! to generate a clippy lint detecting said code automatically.
3
4 #![allow(print_stdout, use_debug)]
5
6 use rustc::lint::*;
7 use rustc::hir;
8 use rustc::hir::{Expr, Expr_, QPath};
9 use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
10 use syntax::ast::{self, Attribute, LitKind, NodeId, DUMMY_NODE_ID};
11 use syntax::codemap::Span;
12 use std::collections::HashMap;
13
14 /// **What it does:** Generates clippy code that detects the offending pattern
15 ///
16 /// **Example:**
17 /// ```rust
18 /// fn foo() {
19 ///     // detect the following pattern
20 ///     #[clippy(author)]
21 ///     if x == 42 {
22 ///         // but ignore everything from here on
23 ///         #![clippy(author = "ignore")]
24 ///     }
25 /// }
26 /// ```
27 ///
28 /// prints
29 ///
30 /// ```
31 /// if_chain!{
32 ///     if let Expr_::ExprIf(ref cond, ref then, None) = item.node,
33 ///     if let Expr_::ExprBinary(BinOp::Eq, ref left, ref right) = cond.node,
34 ///     if let Expr_::ExprPath(ref path) = left.node,
35 ///     if let Expr_::ExprLit(ref lit) = right.node,
36 ///     if let LitKind::Int(42, _) = lit.node,
37 ///     then {
38 ///         // report your lint here
39 ///     }
40 /// }
41 /// ```
42 declare_lint! {
43     pub LINT_AUTHOR,
44     Warn,
45     "helper for writing lints"
46 }
47
48 pub struct Pass;
49
50 impl LintPass for Pass {
51     fn get_lints(&self) -> LintArray {
52         lint_array!(LINT_AUTHOR)
53     }
54 }
55
56 fn prelude() {
57     println!("if_chain! {{");
58 }
59
60 fn done() {
61     println!("    then {{");
62     println!("        // report your lint here");
63     println!("    }}");
64     println!("}}");
65 }
66
67 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
68     fn check_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
69         if !has_attr(&item.attrs) {
70             return;
71         }
72         prelude();
73         PrintVisitor::new("item").visit_item(item);
74         done();
75     }
76
77     fn check_impl_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem) {
78         if !has_attr(&item.attrs) {
79             return;
80         }
81         prelude();
82         PrintVisitor::new("item").visit_impl_item(item);
83         done();
84     }
85
86     fn check_trait_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
87         if !has_attr(&item.attrs) {
88             return;
89         }
90         prelude();
91         PrintVisitor::new("item").visit_trait_item(item);
92         done();
93     }
94
95     fn check_variant(&mut self, _cx: &LateContext<'a, 'tcx>, var: &'tcx hir::Variant, generics: &hir::Generics) {
96         if !has_attr(&var.node.attrs) {
97             return;
98         }
99         prelude();
100         PrintVisitor::new("var").visit_variant(var, generics, DUMMY_NODE_ID);
101         done();
102     }
103
104     fn check_struct_field(&mut self, _cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField) {
105         if !has_attr(&field.attrs) {
106             return;
107         }
108         prelude();
109         PrintVisitor::new("field").visit_struct_field(field);
110         done();
111     }
112
113     fn check_expr(&mut self, _cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
114         if !has_attr(&expr.attrs) {
115             return;
116         }
117         prelude();
118         PrintVisitor::new("expr").visit_expr(expr);
119         done();
120     }
121
122     fn check_arm(&mut self, _cx: &LateContext<'a, 'tcx>, arm: &'tcx hir::Arm) {
123         if !has_attr(&arm.attrs) {
124             return;
125         }
126         prelude();
127         PrintVisitor::new("arm").visit_arm(arm);
128         done();
129     }
130
131     fn check_stmt(&mut self, _cx: &LateContext<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
132         if !has_attr(stmt.node.attrs()) {
133             return;
134         }
135         prelude();
136         PrintVisitor::new("stmt").visit_stmt(stmt);
137         done();
138     }
139
140     fn check_foreign_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ForeignItem) {
141         if !has_attr(&item.attrs) {
142             return;
143         }
144         prelude();
145         PrintVisitor::new("item").visit_foreign_item(item);
146         done();
147     }
148 }
149
150 impl PrintVisitor {
151     fn new(s: &'static str) -> Self {
152         Self {
153             ids: HashMap::new(),
154             current: s.to_owned(),
155         }
156     }
157
158     fn next(&mut self, s: &'static str) -> String {
159         use std::collections::hash_map::Entry::*;
160         match self.ids.entry(s) {
161             // already there: start numbering from `1`
162             Occupied(mut occ) => {
163                 let val = occ.get_mut();
164                 *val += 1;
165                 format!("{}{}", s, *val)
166             },
167             // not there: insert and return name as given
168             Vacant(vac) => {
169                 vac.insert(0);
170                 s.to_owned()
171             },
172         }
173     }
174 }
175
176 struct PrintVisitor {
177     /// Fields are the current index that needs to be appended to pattern
178     /// binding names
179     ids: HashMap<&'static str, usize>,
180     /// the name that needs to be destructured
181     current: String,
182 }
183
184 impl<'tcx> Visitor<'tcx> for PrintVisitor {
185     fn visit_expr(&mut self, expr: &Expr) {
186         print!("    if let Expr_::Expr");
187         let current = format!("{}.node", self.current);
188         match expr.node {
189             Expr_::ExprBox(ref inner) => {
190                 let inner_pat = self.next("inner");
191                 println!("Box(ref {}) = {};", inner_pat, current);
192                 self.current = inner_pat;
193                 self.visit_expr(inner);
194             },
195             Expr_::ExprArray(ref elements) => {
196                 let elements_pat = self.next("elements");
197                 println!("Array(ref {}) = {};", elements_pat, current);
198                 println!("    if {}.len() == {};", elements_pat, elements.len());
199                 for (i, element) in elements.iter().enumerate() {
200                     self.current = format!("{}[{}]", elements_pat, i);
201                     self.visit_expr(element);
202                 }
203             },
204             Expr_::ExprCall(ref _func, ref _args) => {
205                 println!("Call(ref func, ref args) = {};", current);
206                 println!("    // unimplemented: `ExprCall` is not further destructured at the moment");
207             },
208             Expr_::ExprMethodCall(ref _method_name, ref _generics, ref _args) => {
209                 println!("MethodCall(ref method_name, ref generics, ref args) = {};", current);
210                 println!("    // unimplemented: `ExprMethodCall` is not further destructured at the moment");
211             },
212             Expr_::ExprTup(ref elements) => {
213                 let elements_pat = self.next("elements");
214                 println!("Tup(ref {}) = {};", elements_pat, current);
215                 println!("    if {}.len() == {};", elements_pat, elements.len());
216                 for (i, element) in elements.iter().enumerate() {
217                     self.current = format!("{}[{}]", elements_pat, i);
218                     self.visit_expr(element);
219                 }
220             },
221             Expr_::ExprBinary(ref op, ref left, ref right) => {
222                 let op_pat = self.next("op");
223                 let left_pat = self.next("left");
224                 let right_pat = self.next("right");
225                 println!("Binary(ref {}, ref {}, ref {}) = {};", op_pat, left_pat, right_pat, current);
226                 println!("    if BinOp_::{:?} == {}.node;", op.node, op_pat);
227                 self.current = left_pat;
228                 self.visit_expr(left);
229                 self.current = right_pat;
230                 self.visit_expr(right);
231             },
232             Expr_::ExprUnary(ref op, ref inner) => {
233                 let inner_pat = self.next("inner");
234                 println!("Unary(UnOp::{:?}, ref {}) = {};", op, inner_pat, current);
235                 self.current = inner_pat;
236                 self.visit_expr(inner);
237             },
238             Expr_::ExprLit(ref lit) => {
239                 let lit_pat = self.next("lit");
240                 println!("Lit(ref {}) = {};", lit_pat, current);
241                 match lit.node {
242                     LitKind::Bool(val) => println!("    if let LitKind::Bool({:?}) = {}.node;", val, lit_pat),
243                     LitKind::Char(c) => println!("    if let LitKind::Char({:?}) = {}.node;", c, lit_pat),
244                     LitKind::Byte(b) => println!("    if let LitKind::Byte({}) = {}.node;", b, lit_pat),
245                     // FIXME: also check int type
246                     LitKind::Int(i, _) => println!("    if let LitKind::Int({}, _) = {}.node;", i, lit_pat),
247                     LitKind::Float(..) => println!("    if let LitKind::Float(..) = {}.node;", lit_pat),
248                     LitKind::FloatUnsuffixed(_) => println!("    if let LitKind::FloatUnsuffixed(_) = {}.node;", lit_pat),
249                     LitKind::ByteStr(ref vec) => {
250                         let vec_pat = self.next("vec");
251                         println!("    if let LitKind::ByteStr(ref {}) = {}.node;", vec_pat, lit_pat);
252                         println!("    if let [{:?}] = **{};", vec, vec_pat);
253                     },
254                     LitKind::Str(ref text, _) => {
255                         let str_pat = self.next("s");
256                         println!("    if let LitKind::Str(ref {}) = {}.node;", str_pat, lit_pat);
257                         println!("    if {}.as_str() == {:?}", str_pat, &*text.as_str())
258                     },
259                 }
260             },
261             Expr_::ExprCast(ref expr, ref _ty) => {
262                 let cast_pat = self.next("expr");
263                 println!("Cast(ref {}, _) = {};", cast_pat, current);
264                 self.current = cast_pat;
265                 self.visit_expr(expr);
266             },
267             Expr_::ExprType(ref expr, ref _ty) => {
268                 let cast_pat = self.next("expr");
269                 println!("Type(ref {}, _) = {};", cast_pat, current);
270                 self.current = cast_pat;
271                 self.visit_expr(expr);
272             },
273             Expr_::ExprIf(ref cond, ref then, ref opt_else) => {
274                 let cond_pat = self.next("cond");
275                 let then_pat = self.next("then");
276                 if let Some(ref else_) = *opt_else {
277                     let else_pat = self.next("else_");
278                     println!("If(ref {}, ref {}, Some(ref {})) = {};", cond_pat, then_pat, else_pat, current);
279                     self.current = else_pat;
280                     self.visit_expr(else_);
281                 } else {
282                     println!("If(ref {}, ref {}, None) = {};", cond_pat, then_pat, current);
283                 }
284                 self.current = cond_pat;
285                 self.visit_expr(cond);
286                 self.current = then_pat;
287                 self.visit_expr(then);
288             },
289             Expr_::ExprWhile(ref _cond, ref _body, ref _opt_label) => {
290                 println!("While(ref cond, ref body, ref opt_label) = {};", current);
291                 println!("    // unimplemented: `ExprWhile` is not further destructured at the moment");
292             },
293             Expr_::ExprLoop(ref _body, ref _opt_label, ref _desuraging) => {
294                 println!("Loop(ref body, ref opt_label, ref desugaring) = {};", current);
295                 println!("    // unimplemented: `ExprLoop` is not further destructured at the moment");
296             },
297             Expr_::ExprMatch(ref _expr, ref _arms, ref _desugaring) => {
298                 println!("Match(ref expr, ref arms, ref desugaring) = {};", current);
299                 println!("    // unimplemented: `ExprMatch` is not further destructured at the moment");
300             },
301             Expr_::ExprClosure(ref _capture_clause, ref _func, _, _, _) => {
302                 println!("Closure(ref capture_clause, ref func, _, _, _) = {};", current);
303                 println!("    // unimplemented: `ExprClosure` is not further destructured at the moment");
304             },
305             Expr_::ExprYield(ref sub) => {
306                 let sub_pat = self.next("sub");
307                 println!("Yield(ref sub) = {};", current);
308                 self.current = sub_pat;
309                 self.visit_expr(sub);
310             },
311             Expr_::ExprBlock(ref block) => {
312                 let block_pat = self.next("block");
313                 println!("Block(ref {}) = {};", block_pat, current);
314                 self.current = block_pat;
315                 self.visit_block(block);
316             },
317             Expr_::ExprAssign(ref target, ref value) => {
318                 let target_pat = self.next("target");
319                 let value_pat = self.next("value");
320                 println!("Assign(ref {}, ref {}) = {};", target_pat, value_pat, current);
321                 self.current = target_pat;
322                 self.visit_expr(target);
323                 self.current = value_pat;
324                 self.visit_expr(value);
325             },
326             Expr_::ExprAssignOp(ref op, ref target, ref value) => {
327                 let op_pat = self.next("op");
328                 let target_pat = self.next("target");
329                 let value_pat = self.next("value");
330                 println!("AssignOp(ref {}, ref {}, ref {}) = {};", op_pat, target_pat, value_pat, current);
331                 println!("    if BinOp_::{:?} == {}.node;", op.node, op_pat);
332                 self.current = target_pat;
333                 self.visit_expr(target);
334                 self.current = value_pat;
335                 self.visit_expr(value);
336             },
337             Expr_::ExprField(ref object, ref field_name) => {
338                 let obj_pat = self.next("object");
339                 let field_name_pat = self.next("field_name");
340                 println!("Field(ref {}, ref {}) = {};", obj_pat, field_name_pat, current);
341                 println!("    if {}.node.as_str() == {:?}", field_name_pat, field_name.node.as_str());
342                 self.current = obj_pat;
343                 self.visit_expr(object);
344             },
345             Expr_::ExprTupField(ref object, ref field_id) => {
346                 let obj_pat = self.next("object");
347                 let field_id_pat = self.next("field_id");
348                 println!("TupField(ref {}, ref {}) = {};", obj_pat, field_id_pat, current);
349                 println!("    if {}.node == {}", field_id_pat, field_id.node);
350                 self.current = obj_pat;
351                 self.visit_expr(object);
352             },
353             Expr_::ExprIndex(ref object, ref index) => {
354                 let object_pat = self.next("object");
355                 let index_pat = self.next("index");
356                 println!("Index(ref {}, ref {}) = {};", object_pat, index_pat, current);
357                 self.current = object_pat;
358                 self.visit_expr(object);
359                 self.current = index_pat;
360                 self.visit_expr(index);
361             },
362             Expr_::ExprPath(ref path) => {
363                 let path_pat = self.next("path");
364                 println!("Path(ref {}) = {};", path_pat, current);
365                 self.current = path_pat;
366                 self.visit_qpath(path, expr.id, expr.span);
367             },
368             Expr_::ExprAddrOf(mutability, ref inner) => {
369                 let inner_pat = self.next("inner");
370                 println!("AddrOf({:?}, ref {}) = {};", mutability, inner_pat, current);
371                 self.current = inner_pat;
372                 self.visit_expr(inner);
373             },
374             Expr_::ExprBreak(ref _destination, ref opt_value) => {
375                 let destination_pat = self.next("destination");
376                 if let Some(ref value) = *opt_value {
377                     let value_pat = self.next("value");
378                     println!("Break(ref {}, Some(ref {})) = {};", destination_pat, value_pat, current);
379                     self.current = value_pat;
380                     self.visit_expr(value);
381                 } else {
382                     println!("Break(ref {}, None) = {};", destination_pat, current);
383                 }
384                 // FIXME: implement label printing
385             },
386             Expr_::ExprAgain(ref _destination) => {
387                 let destination_pat = self.next("destination");
388                 println!("Again(ref {}) = {};", destination_pat, current);
389                 // FIXME: implement label printing
390             },
391             Expr_::ExprRet(ref opt_value) => if let Some(ref value) = *opt_value {
392                 let value_pat = self.next("value");
393                 println!("Ret(Some(ref {})) = {};", value_pat, current);
394                 self.current = value_pat;
395                 self.visit_expr(value);
396             } else {
397                 println!("Ret(None) = {};", current);
398             },
399             Expr_::ExprInlineAsm(_, ref _input, ref _output) => {
400                 println!("InlineAsm(_, ref input, ref output) = {};", current);
401                 println!("    // unimplemented: `ExprInlineAsm` is not further destructured at the moment");
402             },
403             Expr_::ExprStruct(ref path, ref fields, ref opt_base) => {
404                 let path_pat = self.next("path");
405                 let fields_pat = self.next("fields");
406                 if let Some(ref base) = *opt_base {
407                     let base_pat = self.next("base");
408                     println!(
409                         "Struct(ref {}, ref {}, Some(ref {})) = {};",
410                         path_pat,
411                         fields_pat,
412                         base_pat,
413                         current
414                     );
415                     self.current = base_pat;
416                     self.visit_expr(base);
417                 } else {
418                     println!("Struct(ref {}, ref {}, None) = {};", path_pat, fields_pat, current);
419                 }
420                 self.current = path_pat;
421                 self.visit_qpath(path, expr.id, expr.span);
422                 println!("    if {}.len() == {};", fields_pat, fields.len());
423                 println!("    // unimplemented: field checks");
424             },
425             // FIXME: compute length (needs type info)
426             Expr_::ExprRepeat(ref value, _) => {
427                 let value_pat = self.next("value");
428                 println!("Repeat(ref {}, _) = {};", value_pat, current);
429                 println!("// unimplemented: repeat count check");
430                 self.current = value_pat;
431                 self.visit_expr(value);
432             },
433         }
434     }
435
436     fn visit_qpath(&mut self, path: &QPath, _: NodeId, _: Span) {
437         print!("    if match_qpath({}, &[", self.current);
438         print_path(path, &mut true);
439         println!("]);");
440     }
441     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
442         NestedVisitorMap::None
443     }
444 }
445
446 fn has_attr(attrs: &[Attribute]) -> bool {
447     attrs.iter().any(|attr| {
448         attr.check_name("clippy") && attr.meta_item_list().map_or(false, |list| {
449             list.len() == 1 && match list[0].node {
450                 ast::NestedMetaItemKind::MetaItem(ref it) => it.name == "author",
451                 ast::NestedMetaItemKind::Literal(_) => false,
452             }
453         })
454     })
455 }
456
457 fn print_path(path: &QPath, first: &mut bool) {
458     match *path {
459         QPath::Resolved(_, ref path) => for segment in &path.segments {
460             if *first {
461                 *first = false;
462             } else {
463                 print!(", ");
464             }
465             print!("{:?}", segment.name.as_str());
466         },
467         QPath::TypeRelative(ref ty, ref segment) => match ty.node {
468             hir::Ty_::TyPath(ref inner_path) => {
469                 print_path(inner_path, first);
470                 if *first {
471                     *first = false;
472                 } else {
473                     print!(", ");
474                 }
475                 print!("{:?}", segment.name.as_str());
476             },
477             ref other => print!("/* unimplemented: {:?}*/", other),
478         },
479     }
480 }