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