]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/author.rs
Document the 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};
10 use syntax::ast::{self, Attribute, LitKind, DUMMY_NODE_ID};
11 use std::collections::HashMap;
12
13 /// **What it does:** Generates clippy code that detects the offending pattern
14 ///
15 /// **Example:**
16 /// ```rust
17 /// // ./tests/ui/my_lint.rs
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 /// Running `TESTNAME=ui/my_lint cargo test --test compile-test` will produce
29 /// a `./tests/ui/new_lint.stdout` file with the generated code:
30 ///
31 /// ```rust
32 /// // ./tests/ui/new_lint.stdout
33 /// if_chain!{
34 ///     if let Expr_::ExprIf(ref cond, ref then, None) = item.node,
35 ///     if let Expr_::ExprBinary(BinOp::Eq, ref left, ref right) = cond.node,
36 ///     if let Expr_::ExprPath(ref path) = left.node,
37 ///     if let Expr_::ExprLit(ref lit) = right.node,
38 ///     if let LitKind::Int(42, _) = lit.node,
39 ///     then {
40 ///         // report your lint here
41 ///     }
42 /// }
43 /// ```
44 declare_clippy_lint! {
45     pub LINT_AUTHOR,
46     internal_warn,
47     "helper for writing lints"
48 }
49
50 pub struct Pass;
51
52 impl LintPass for Pass {
53     fn get_lints(&self) -> LintArray {
54         lint_array!(LINT_AUTHOR)
55     }
56 }
57
58 fn prelude() {
59     println!("if_chain! {{");
60 }
61
62 fn done() {
63     println!("    then {{");
64     println!("        // report your lint here");
65     println!("    }}");
66     println!("}}");
67 }
68
69 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
70     fn check_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
71         if !has_attr(&item.attrs) {
72             return;
73         }
74         prelude();
75         PrintVisitor::new("item").visit_item(item);
76         done();
77     }
78
79     fn check_impl_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem) {
80         if !has_attr(&item.attrs) {
81             return;
82         }
83         prelude();
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     fn print_qpath(&mut self, path: &QPath) {
178         print!("    if match_qpath({}, &[", self.current);
179         print_path(path, &mut true);
180         println!("]);");
181     }
182 }
183
184 struct PrintVisitor {
185     /// Fields are the current index that needs to be appended to pattern
186     /// binding names
187     ids: HashMap<&'static str, usize>,
188     /// the name that needs to be destructured
189     current: String,
190 }
191
192 impl<'tcx> Visitor<'tcx> for PrintVisitor {
193     fn visit_expr(&mut self, expr: &Expr) {
194         print!("    if let Expr_::Expr");
195         let current = format!("{}.node", self.current);
196         match expr.node {
197             Expr_::ExprBox(ref inner) => {
198                 let inner_pat = self.next("inner");
199                 println!("Box(ref {}) = {};", inner_pat, current);
200                 self.current = inner_pat;
201                 self.visit_expr(inner);
202             },
203             Expr_::ExprArray(ref elements) => {
204                 let elements_pat = self.next("elements");
205                 println!("Array(ref {}) = {};", elements_pat, current);
206                 println!("    if {}.len() == {};", elements_pat, elements.len());
207                 for (i, element) in elements.iter().enumerate() {
208                     self.current = format!("{}[{}]", elements_pat, i);
209                     self.visit_expr(element);
210                 }
211             },
212             Expr_::ExprCall(ref _func, ref _args) => {
213                 println!("Call(ref func, ref args) = {};", current);
214                 println!("    // unimplemented: `ExprCall` is not further destructured at the moment");
215             },
216             Expr_::ExprMethodCall(ref _method_name, ref _generics, ref _args) => {
217                 println!("MethodCall(ref method_name, ref generics, ref args) = {};", current);
218                 println!("    // unimplemented: `ExprMethodCall` is not further destructured at the moment");
219             },
220             Expr_::ExprTup(ref elements) => {
221                 let elements_pat = self.next("elements");
222                 println!("Tup(ref {}) = {};", elements_pat, current);
223                 println!("    if {}.len() == {};", elements_pat, elements.len());
224                 for (i, element) in elements.iter().enumerate() {
225                     self.current = format!("{}[{}]", elements_pat, i);
226                     self.visit_expr(element);
227                 }
228             },
229             Expr_::ExprBinary(ref op, ref left, ref right) => {
230                 let op_pat = self.next("op");
231                 let left_pat = self.next("left");
232                 let right_pat = self.next("right");
233                 println!("Binary(ref {}, ref {}, ref {}) = {};", op_pat, left_pat, right_pat, current);
234                 println!("    if BinOp_::{:?} == {}.node;", op.node, op_pat);
235                 self.current = left_pat;
236                 self.visit_expr(left);
237                 self.current = right_pat;
238                 self.visit_expr(right);
239             },
240             Expr_::ExprUnary(ref op, ref inner) => {
241                 let inner_pat = self.next("inner");
242                 println!("Unary(UnOp::{:?}, ref {}) = {};", op, inner_pat, current);
243                 self.current = inner_pat;
244                 self.visit_expr(inner);
245             },
246             Expr_::ExprLit(ref lit) => {
247                 let lit_pat = self.next("lit");
248                 println!("Lit(ref {}) = {};", lit_pat, current);
249                 match lit.node {
250                     LitKind::Bool(val) => println!("    if let LitKind::Bool({:?}) = {}.node;", val, lit_pat),
251                     LitKind::Char(c) => println!("    if let LitKind::Char({:?}) = {}.node;", c, lit_pat),
252                     LitKind::Byte(b) => println!("    if let LitKind::Byte({}) = {}.node;", b, lit_pat),
253                     // FIXME: also check int type
254                     LitKind::Int(i, _) => println!("    if let LitKind::Int({}, _) = {}.node;", i, lit_pat),
255                     LitKind::Float(..) => println!("    if let LitKind::Float(..) = {}.node;", lit_pat),
256                     LitKind::FloatUnsuffixed(_) => {
257                         println!("    if let LitKind::FloatUnsuffixed(_) = {}.node;", lit_pat)
258                     },
259                     LitKind::ByteStr(ref vec) => {
260                         let vec_pat = self.next("vec");
261                         println!("    if let LitKind::ByteStr(ref {}) = {}.node;", vec_pat, lit_pat);
262                         println!("    if let [{:?}] = **{};", vec, vec_pat);
263                     },
264                     LitKind::Str(ref text, _) => {
265                         let str_pat = self.next("s");
266                         println!("    if let LitKind::Str(ref {}) = {}.node;", str_pat, lit_pat);
267                         println!("    if {}.as_str() == {:?}", str_pat, &*text.as_str())
268                     },
269                 }
270             },
271             Expr_::ExprCast(ref expr, ref ty) => {
272                 let cast_pat = self.next("expr");
273                 let cast_ty = self.next("cast_ty");
274                 let qp_label = self.next("qp");
275
276                 println!("Cast(ref {}, ref {}) = {};", cast_pat, cast_ty, current);
277                 if let Ty_::TyPath(ref qp) = ty.node {
278                     println!("    if let Ty_::TyPath(ref {}) = {}.node;", qp_label, cast_ty);
279                     self.current = qp_label;
280                     self.print_qpath(qp);
281                 }
282                 self.current = cast_pat;
283                 self.visit_expr(expr);
284             },
285             Expr_::ExprType(ref expr, ref _ty) => {
286                 let cast_pat = self.next("expr");
287                 println!("Type(ref {}, _) = {};", cast_pat, current);
288                 self.current = cast_pat;
289                 self.visit_expr(expr);
290             },
291             Expr_::ExprIf(ref cond, ref then, ref opt_else) => {
292                 let cond_pat = self.next("cond");
293                 let then_pat = self.next("then");
294                 if let Some(ref else_) = *opt_else {
295                     let else_pat = self.next("else_");
296                     println!("If(ref {}, ref {}, Some(ref {})) = {};", cond_pat, then_pat, else_pat, current);
297                     self.current = else_pat;
298                     self.visit_expr(else_);
299                 } else {
300                     println!("If(ref {}, ref {}, None) = {};", cond_pat, then_pat, current);
301                 }
302                 self.current = cond_pat;
303                 self.visit_expr(cond);
304                 self.current = then_pat;
305                 self.visit_expr(then);
306             },
307             Expr_::ExprWhile(ref cond, ref body, _) => {
308                 let cond_pat = self.next("cond");
309                 let body_pat = self.next("body");
310                 let label_pat = self.next("label");
311                 println!("While(ref {}, ref {}, ref {}) = {};", cond_pat, body_pat, label_pat, current);
312                 self.current = cond_pat;
313                 self.visit_expr(cond);
314                 self.current = body_pat;
315                 self.visit_block(body);
316             },
317             Expr_::ExprLoop(ref body, _, desugaring) => {
318                 let body_pat = self.next("body");
319                 let des = loop_desugaring_name(desugaring);
320                 let label_pat = self.next("label");
321                 println!("Loop(ref {}, ref {}, {}) = {};", body_pat, label_pat, des, current);
322                 self.current = body_pat;
323                 self.visit_block(body);
324             },
325             Expr_::ExprMatch(ref _expr, ref _arms, desugaring) => {
326                 let des = desugaring_name(desugaring);
327                 println!("Match(ref expr, ref arms, {}) = {};", des, current);
328                 println!("    // unimplemented: `ExprMatch` is not further destructured at the moment");
329             },
330             Expr_::ExprClosure(ref _capture_clause, ref _func, _, _, _) => {
331                 println!("Closure(ref capture_clause, ref func, _, _, _) = {};", current);
332                 println!("    // unimplemented: `ExprClosure` is not further destructured at the moment");
333             },
334             Expr_::ExprYield(ref sub) => {
335                 let sub_pat = self.next("sub");
336                 println!("Yield(ref sub) = {};", current);
337                 self.current = sub_pat;
338                 self.visit_expr(sub);
339             },
340             Expr_::ExprBlock(ref block) => {
341                 let block_pat = self.next("block");
342                 println!("Block(ref {}) = {};", block_pat, current);
343                 self.current = block_pat;
344                 self.visit_block(block);
345             },
346             Expr_::ExprAssign(ref target, ref value) => {
347                 let target_pat = self.next("target");
348                 let value_pat = self.next("value");
349                 println!("Assign(ref {}, ref {}) = {};", target_pat, value_pat, current);
350                 self.current = target_pat;
351                 self.visit_expr(target);
352                 self.current = value_pat;
353                 self.visit_expr(value);
354             },
355             Expr_::ExprAssignOp(ref op, ref target, ref value) => {
356                 let op_pat = self.next("op");
357                 let target_pat = self.next("target");
358                 let value_pat = self.next("value");
359                 println!("AssignOp(ref {}, ref {}, ref {}) = {};", op_pat, target_pat, value_pat, current);
360                 println!("    if BinOp_::{:?} == {}.node;", op.node, op_pat);
361                 self.current = target_pat;
362                 self.visit_expr(target);
363                 self.current = value_pat;
364                 self.visit_expr(value);
365             },
366             Expr_::ExprField(ref object, ref field_name) => {
367                 let obj_pat = self.next("object");
368                 let field_name_pat = self.next("field_name");
369                 println!("Field(ref {}, ref {}) = {};", obj_pat, field_name_pat, current);
370                 println!("    if {}.node.as_str() == {:?}", field_name_pat, field_name.node.as_str());
371                 self.current = obj_pat;
372                 self.visit_expr(object);
373             },
374             Expr_::ExprTupField(ref object, ref field_id) => {
375                 let obj_pat = self.next("object");
376                 let field_id_pat = self.next("field_id");
377                 println!("TupField(ref {}, ref {}) = {};", obj_pat, field_id_pat, current);
378                 println!("    if {}.node == {}", field_id_pat, field_id.node);
379                 self.current = obj_pat;
380                 self.visit_expr(object);
381             },
382             Expr_::ExprIndex(ref object, ref index) => {
383                 let object_pat = self.next("object");
384                 let index_pat = self.next("index");
385                 println!("Index(ref {}, ref {}) = {};", object_pat, index_pat, current);
386                 self.current = object_pat;
387                 self.visit_expr(object);
388                 self.current = index_pat;
389                 self.visit_expr(index);
390             },
391             Expr_::ExprPath(ref path) => {
392                 let path_pat = self.next("path");
393                 println!("Path(ref {}) = {};", path_pat, current);
394                 self.current = path_pat;
395                 self.print_qpath(path);
396             },
397             Expr_::ExprAddrOf(mutability, ref inner) => {
398                 let inner_pat = self.next("inner");
399                 println!("AddrOf({:?}, ref {}) = {};", mutability, inner_pat, current);
400                 self.current = inner_pat;
401                 self.visit_expr(inner);
402             },
403             Expr_::ExprBreak(ref _destination, ref opt_value) => {
404                 let destination_pat = self.next("destination");
405                 if let Some(ref value) = *opt_value {
406                     let value_pat = self.next("value");
407                     println!("Break(ref {}, Some(ref {})) = {};", destination_pat, value_pat, current);
408                     self.current = value_pat;
409                     self.visit_expr(value);
410                 } else {
411                     println!("Break(ref {}, None) = {};", destination_pat, current);
412                 }
413                 // FIXME: implement label printing
414             },
415             Expr_::ExprAgain(ref _destination) => {
416                 let destination_pat = self.next("destination");
417                 println!("Again(ref {}) = {};", destination_pat, current);
418                 // FIXME: implement label printing
419             },
420             Expr_::ExprRet(ref opt_value) => if let Some(ref value) = *opt_value {
421                 let value_pat = self.next("value");
422                 println!("Ret(Some(ref {})) = {};", value_pat, current);
423                 self.current = value_pat;
424                 self.visit_expr(value);
425             } else {
426                 println!("Ret(None) = {};", current);
427             },
428             Expr_::ExprInlineAsm(_, ref _input, ref _output) => {
429                 println!("InlineAsm(_, ref input, ref output) = {};", current);
430                 println!("    // unimplemented: `ExprInlineAsm` is not further destructured at the moment");
431             },
432             Expr_::ExprStruct(ref path, ref fields, ref opt_base) => {
433                 let path_pat = self.next("path");
434                 let fields_pat = self.next("fields");
435                 if let Some(ref base) = *opt_base {
436                     let base_pat = self.next("base");
437                     println!(
438                         "Struct(ref {}, ref {}, Some(ref {})) = {};",
439                         path_pat,
440                         fields_pat,
441                         base_pat,
442                         current
443                     );
444                     self.current = base_pat;
445                     self.visit_expr(base);
446                 } else {
447                     println!("Struct(ref {}, ref {}, None) = {};", path_pat, fields_pat, current);
448                 }
449                 self.current = path_pat;
450                 self.print_qpath(path);
451                 println!("    if {}.len() == {};", fields_pat, fields.len());
452                 println!("    // unimplemented: field checks");
453             },
454             // FIXME: compute length (needs type info)
455             Expr_::ExprRepeat(ref value, _) => {
456                 let value_pat = self.next("value");
457                 println!("Repeat(ref {}, _) = {};", value_pat, current);
458                 println!("// unimplemented: repeat count check");
459                 self.current = value_pat;
460                 self.visit_expr(value);
461             },
462         }
463     }
464
465     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
466         NestedVisitorMap::None
467     }
468 }
469
470 fn has_attr(attrs: &[Attribute]) -> bool {
471     attrs.iter().any(|attr| {
472         attr.check_name("clippy") && attr.meta_item_list().map_or(false, |list| {
473             list.len() == 1 && match list[0].node {
474                 ast::NestedMetaItemKind::MetaItem(ref it) => it.name == "author",
475                 ast::NestedMetaItemKind::Literal(_) => false,
476             }
477         })
478     })
479 }
480
481 fn desugaring_name(des: hir::MatchSource) -> String {
482     match des {
483         hir::MatchSource::ForLoopDesugar => "MatchSource::ForLoopDesugar".to_string(),
484         hir::MatchSource::TryDesugar => "MatchSource::TryDesugar".to_string(),
485         hir::MatchSource::WhileLetDesugar => "MatchSource::WhileLetDesugar".to_string(),
486         hir::MatchSource::Normal => "MatchSource::Normal".to_string(),
487         hir::MatchSource::IfLetDesugar { contains_else_clause } => format!("MatchSource::IfLetDesugar {{ contains_else_clause: {} }}", contains_else_clause),
488     }
489 }
490
491 fn loop_desugaring_name(des: hir::LoopSource) -> &'static str {
492     match des {
493         hir::LoopSource::ForLoop => "LoopSource::ForLoop",
494         hir::LoopSource::Loop => "LoopSource::Loop",
495         hir::LoopSource::WhileLet => "LoopSource::WhileLet",
496     }
497 }
498
499 fn print_path(path: &QPath, first: &mut bool) {
500     match *path {
501         QPath::Resolved(_, ref path) => for segment in &path.segments {
502             if *first {
503                 *first = false;
504             } else {
505                 print!(", ");
506             }
507             print!("{:?}", segment.name.as_str());
508         },
509         QPath::TypeRelative(ref ty, ref segment) => match ty.node {
510             hir::Ty_::TyPath(ref inner_path) => {
511                 print_path(inner_path, first);
512                 if *first {
513                     *first = false;
514                 } else {
515                     print!(", ");
516                 }
517                 print!("{:?}", segment.name.as_str());
518             },
519             ref other => print!("/* unimplemented: {:?}*/", other),
520         },
521     }
522 }