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