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