]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/inspector.rs
Merge branch 'master' into fix-4727
[rust.git] / clippy_lints / src / utils / inspector.rs
1 //! checks for attributes
2
3 use crate::utils::get_attr;
4 use rustc::hir;
5 use rustc::hir::print;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass};
7 use rustc::session::Session;
8 use rustc::{declare_lint_pass, declare_tool_lint};
9 use syntax::ast::Attribute;
10
11 declare_clippy_lint! {
12     /// **What it does:** Dumps every ast/hir node which has the `#[clippy::dump]`
13     /// attribute
14     ///
15     /// **Example:**
16     /// ```rust,ignore
17     /// #[clippy::dump]
18     /// extern crate foo;
19     /// ```
20     ///
21     /// prints
22     ///
23     /// ```text
24     /// item `foo`
25     /// visibility inherited from outer item
26     /// extern crate dylib source: "/path/to/foo.so"
27     /// ```
28     pub DEEP_CODE_INSPECTION,
29     internal_warn,
30     "helper to dump info about code"
31 }
32
33 declare_lint_pass!(DeepCodeInspector => [DEEP_CODE_INSPECTION]);
34
35 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DeepCodeInspector {
36     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
37         if !has_attr(cx.sess(), &item.attrs) {
38             return;
39         }
40         print_item(cx, item);
41     }
42
43     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem) {
44         if !has_attr(cx.sess(), &item.attrs) {
45             return;
46         }
47         println!("impl item `{}`", item.ident.name);
48         match item.vis.node {
49             hir::VisibilityKind::Public => println!("public"),
50             hir::VisibilityKind::Crate(_) => println!("visible crate wide"),
51             hir::VisibilityKind::Restricted { ref path, .. } => println!(
52                 "visible in module `{}`",
53                 print::to_string(print::NO_ANN, |s| s.print_path(path, false))
54             ),
55             hir::VisibilityKind::Inherited => println!("visibility inherited from outer item"),
56         }
57         if item.defaultness.is_default() {
58             println!("default");
59         }
60         match item.kind {
61             hir::ImplItemKind::Const(_, body_id) => {
62                 println!("associated constant");
63                 print_expr(cx, &cx.tcx.hir().body(body_id).value, 1);
64             },
65             hir::ImplItemKind::Method(..) => println!("method"),
66             hir::ImplItemKind::TyAlias(_) => println!("associated type"),
67             hir::ImplItemKind::OpaqueTy(_) => println!("existential type"),
68         }
69     }
70     // fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx
71     // hir::TraitItem) {
72     // if !has_attr(&item.attrs) {
73     // return;
74     // }
75     // }
76     //
77     // fn check_variant(&mut self, cx: &LateContext<'a, 'tcx>, var: &'tcx
78     // hir::Variant, _:
79     // &hir::Generics) {
80     // if !has_attr(&var.node.attrs) {
81     // return;
82     // }
83     // }
84     //
85     // fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx
86     // hir::StructField) {
87     // if !has_attr(&field.attrs) {
88     // return;
89     // }
90     // }
91     //
92
93     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
94         if !has_attr(cx.sess(), &expr.attrs) {
95             return;
96         }
97         print_expr(cx, expr, 0);
98     }
99
100     fn check_arm(&mut self, cx: &LateContext<'a, 'tcx>, arm: &'tcx hir::Arm) {
101         if !has_attr(cx.sess(), &arm.attrs) {
102             return;
103         }
104         print_pat(cx, &arm.pat, 1);
105         if let Some(ref guard) = arm.guard {
106             println!("guard:");
107             print_guard(cx, guard, 1);
108         }
109         println!("body:");
110         print_expr(cx, &arm.body, 1);
111     }
112
113     fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
114         if !has_attr(cx.sess(), stmt.kind.attrs()) {
115             return;
116         }
117         match stmt.kind {
118             hir::StmtKind::Local(ref local) => {
119                 println!("local variable of type {}", cx.tables.node_type(local.hir_id));
120                 println!("pattern:");
121                 print_pat(cx, &local.pat, 0);
122                 if let Some(ref e) = local.init {
123                     println!("init expression:");
124                     print_expr(cx, e, 0);
125                 }
126             },
127             hir::StmtKind::Item(_) => println!("item decl"),
128             hir::StmtKind::Expr(ref e) | hir::StmtKind::Semi(ref e) => print_expr(cx, e, 0),
129         }
130     }
131     // fn check_foreign_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx
132     // hir::ForeignItem) {
133     // if !has_attr(&item.attrs) {
134     // return;
135     // }
136     // }
137     //
138 }
139
140 fn has_attr(sess: &Session, attrs: &[Attribute]) -> bool {
141     get_attr(sess, attrs, "dump").count() > 0
142 }
143
144 #[allow(clippy::similar_names)]
145 #[allow(clippy::too_many_lines)]
146 fn print_expr(cx: &LateContext<'_, '_>, expr: &hir::Expr, indent: usize) {
147     let ind = "  ".repeat(indent);
148     println!("{}+", ind);
149     println!("{}ty: {}", ind, cx.tables.expr_ty(expr));
150     println!("{}adjustments: {:?}", ind, cx.tables.adjustments().get(expr.hir_id));
151     match expr.kind {
152         hir::ExprKind::Box(ref e) => {
153             println!("{}Box", ind);
154             print_expr(cx, e, indent + 1);
155         },
156         hir::ExprKind::Array(ref v) => {
157             println!("{}Array", ind);
158             for e in v {
159                 print_expr(cx, e, indent + 1);
160             }
161         },
162         hir::ExprKind::Call(ref func, ref args) => {
163             println!("{}Call", ind);
164             println!("{}function:", ind);
165             print_expr(cx, func, indent + 1);
166             println!("{}arguments:", ind);
167             for arg in args {
168                 print_expr(cx, arg, indent + 1);
169             }
170         },
171         hir::ExprKind::MethodCall(ref path, _, ref args) => {
172             println!("{}MethodCall", ind);
173             println!("{}method name: {}", ind, path.ident.name);
174             for arg in args {
175                 print_expr(cx, arg, indent + 1);
176             }
177         },
178         hir::ExprKind::Tup(ref v) => {
179             println!("{}Tup", ind);
180             for e in v {
181                 print_expr(cx, e, indent + 1);
182             }
183         },
184         hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
185             println!("{}Binary", ind);
186             println!("{}op: {:?}", ind, op.node);
187             println!("{}lhs:", ind);
188             print_expr(cx, lhs, indent + 1);
189             println!("{}rhs:", ind);
190             print_expr(cx, rhs, indent + 1);
191         },
192         hir::ExprKind::Unary(op, ref inner) => {
193             println!("{}Unary", ind);
194             println!("{}op: {:?}", ind, op);
195             print_expr(cx, inner, indent + 1);
196         },
197         hir::ExprKind::Lit(ref lit) => {
198             println!("{}Lit", ind);
199             println!("{}{:?}", ind, lit);
200         },
201         hir::ExprKind::Cast(ref e, ref target) => {
202             println!("{}Cast", ind);
203             print_expr(cx, e, indent + 1);
204             println!("{}target type: {:?}", ind, target);
205         },
206         hir::ExprKind::Type(ref e, ref target) => {
207             println!("{}Type", ind);
208             print_expr(cx, e, indent + 1);
209             println!("{}target type: {:?}", ind, target);
210         },
211         hir::ExprKind::Loop(..) => {
212             println!("{}Loop", ind);
213         },
214         hir::ExprKind::Match(ref cond, _, ref source) => {
215             println!("{}Match", ind);
216             println!("{}condition:", ind);
217             print_expr(cx, cond, indent + 1);
218             println!("{}source: {:?}", ind, source);
219         },
220         hir::ExprKind::Closure(ref clause, _, _, _, _) => {
221             println!("{}Closure", ind);
222             println!("{}clause: {:?}", ind, clause);
223         },
224         hir::ExprKind::Yield(ref sub, _) => {
225             println!("{}Yield", ind);
226             print_expr(cx, sub, indent + 1);
227         },
228         hir::ExprKind::Block(_, _) => {
229             println!("{}Block", ind);
230         },
231         hir::ExprKind::Assign(ref lhs, ref rhs) => {
232             println!("{}Assign", ind);
233             println!("{}lhs:", ind);
234             print_expr(cx, lhs, indent + 1);
235             println!("{}rhs:", ind);
236             print_expr(cx, rhs, indent + 1);
237         },
238         hir::ExprKind::AssignOp(ref binop, ref lhs, ref rhs) => {
239             println!("{}AssignOp", ind);
240             println!("{}op: {:?}", ind, binop.node);
241             println!("{}lhs:", ind);
242             print_expr(cx, lhs, indent + 1);
243             println!("{}rhs:", ind);
244             print_expr(cx, rhs, indent + 1);
245         },
246         hir::ExprKind::Field(ref e, ident) => {
247             println!("{}Field", ind);
248             println!("{}field name: {}", ind, ident.name);
249             println!("{}struct expr:", ind);
250             print_expr(cx, e, indent + 1);
251         },
252         hir::ExprKind::Index(ref arr, ref idx) => {
253             println!("{}Index", ind);
254             println!("{}array expr:", ind);
255             print_expr(cx, arr, indent + 1);
256             println!("{}index expr:", ind);
257             print_expr(cx, idx, indent + 1);
258         },
259         hir::ExprKind::Path(hir::QPath::Resolved(ref ty, ref path)) => {
260             println!("{}Resolved Path, {:?}", ind, ty);
261             println!("{}path: {:?}", ind, path);
262         },
263         hir::ExprKind::Path(hir::QPath::TypeRelative(ref ty, ref seg)) => {
264             println!("{}Relative Path, {:?}", ind, ty);
265             println!("{}seg: {:?}", ind, seg);
266         },
267         hir::ExprKind::AddrOf(ref muta, ref e) => {
268             println!("{}AddrOf", ind);
269             println!("mutability: {:?}", muta);
270             print_expr(cx, e, indent + 1);
271         },
272         hir::ExprKind::Break(_, ref e) => {
273             println!("{}Break", ind);
274             if let Some(ref e) = *e {
275                 print_expr(cx, e, indent + 1);
276             }
277         },
278         hir::ExprKind::Continue(_) => println!("{}Again", ind),
279         hir::ExprKind::Ret(ref e) => {
280             println!("{}Ret", ind);
281             if let Some(ref e) = *e {
282                 print_expr(cx, e, indent + 1);
283             }
284         },
285         hir::ExprKind::InlineAsm(_, ref input, ref output) => {
286             println!("{}InlineAsm", ind);
287             println!("{}inputs:", ind);
288             for e in input {
289                 print_expr(cx, e, indent + 1);
290             }
291             println!("{}outputs:", ind);
292             for e in output {
293                 print_expr(cx, e, indent + 1);
294             }
295         },
296         hir::ExprKind::Struct(ref path, ref fields, ref base) => {
297             println!("{}Struct", ind);
298             println!("{}path: {:?}", ind, path);
299             for field in fields {
300                 println!("{}field \"{}\":", ind, field.ident.name);
301                 print_expr(cx, &field.expr, indent + 1);
302             }
303             if let Some(ref base) = *base {
304                 println!("{}base:", ind);
305                 print_expr(cx, base, indent + 1);
306             }
307         },
308         hir::ExprKind::Repeat(ref val, ref anon_const) => {
309             println!("{}Repeat", ind);
310             println!("{}value:", ind);
311             print_expr(cx, val, indent + 1);
312             println!("{}repeat count:", ind);
313             print_expr(cx, &cx.tcx.hir().body(anon_const.body).value, indent + 1);
314         },
315         hir::ExprKind::Err => {
316             println!("{}Err", ind);
317         },
318         hir::ExprKind::DropTemps(ref e) => {
319             println!("{}DropTemps", ind);
320             print_expr(cx, e, indent + 1);
321         },
322     }
323 }
324
325 fn print_item(cx: &LateContext<'_, '_>, item: &hir::Item) {
326     let did = cx.tcx.hir().local_def_id(item.hir_id);
327     println!("item `{}`", item.ident.name);
328     match item.vis.node {
329         hir::VisibilityKind::Public => println!("public"),
330         hir::VisibilityKind::Crate(_) => println!("visible crate wide"),
331         hir::VisibilityKind::Restricted { ref path, .. } => println!(
332             "visible in module `{}`",
333             print::to_string(print::NO_ANN, |s| s.print_path(path, false))
334         ),
335         hir::VisibilityKind::Inherited => println!("visibility inherited from outer item"),
336     }
337     match item.kind {
338         hir::ItemKind::ExternCrate(ref _renamed_from) => {
339             let def_id = cx.tcx.hir().local_def_id(item.hir_id);
340             if let Some(crate_id) = cx.tcx.extern_mod_stmt_cnum(def_id) {
341                 let source = cx.tcx.used_crate_source(crate_id);
342                 if let Some(ref src) = source.dylib {
343                     println!("extern crate dylib source: {:?}", src.0);
344                 }
345                 if let Some(ref src) = source.rlib {
346                     println!("extern crate rlib source: {:?}", src.0);
347                 }
348             } else {
349                 println!("weird extern crate without a crate id");
350             }
351         },
352         hir::ItemKind::Use(ref path, ref kind) => println!("{:?}, {:?}", path, kind),
353         hir::ItemKind::Static(..) => println!("static item of type {:#?}", cx.tcx.type_of(did)),
354         hir::ItemKind::Const(..) => println!("const item of type {:#?}", cx.tcx.type_of(did)),
355         hir::ItemKind::Fn(..) => {
356             let item_ty = cx.tcx.type_of(did);
357             println!("function of type {:#?}", item_ty);
358         },
359         hir::ItemKind::Mod(..) => println!("module"),
360         hir::ItemKind::ForeignMod(ref fm) => println!("foreign module with abi: {}", fm.abi),
361         hir::ItemKind::GlobalAsm(ref asm) => println!("global asm: {:?}", asm),
362         hir::ItemKind::TyAlias(..) => {
363             println!("type alias for {:?}", cx.tcx.type_of(did));
364         },
365         hir::ItemKind::OpaqueTy(..) => {
366             println!("existential type with real type {:?}", cx.tcx.type_of(did));
367         },
368         hir::ItemKind::Enum(..) => {
369             println!("enum definition of type {:?}", cx.tcx.type_of(did));
370         },
371         hir::ItemKind::Struct(..) => {
372             println!("struct definition of type {:?}", cx.tcx.type_of(did));
373         },
374         hir::ItemKind::Union(..) => {
375             println!("union definition of type {:?}", cx.tcx.type_of(did));
376         },
377         hir::ItemKind::Trait(..) => {
378             println!("trait decl");
379             if cx.tcx.trait_is_auto(did) {
380                 println!("trait is auto");
381             } else {
382                 println!("trait is not auto");
383             }
384         },
385         hir::ItemKind::TraitAlias(..) => {
386             println!("trait alias");
387         },
388         hir::ItemKind::Impl(_, _, _, _, Some(ref _trait_ref), _, _) => {
389             println!("trait impl");
390         },
391         hir::ItemKind::Impl(_, _, _, _, None, _, _) => {
392             println!("impl");
393         },
394     }
395 }
396
397 #[allow(clippy::similar_names)]
398 #[allow(clippy::too_many_lines)]
399 fn print_pat(cx: &LateContext<'_, '_>, pat: &hir::Pat, indent: usize) {
400     let ind = "  ".repeat(indent);
401     println!("{}+", ind);
402     match pat.kind {
403         hir::PatKind::Wild => println!("{}Wild", ind),
404         hir::PatKind::Binding(ref mode, .., ident, ref inner) => {
405             println!("{}Binding", ind);
406             println!("{}mode: {:?}", ind, mode);
407             println!("{}name: {}", ind, ident.name);
408             if let Some(ref inner) = *inner {
409                 println!("{}inner:", ind);
410                 print_pat(cx, inner, indent + 1);
411             }
412         },
413         hir::PatKind::Or(ref fields) => {
414             println!("{}Or", ind);
415             for field in fields {
416                 print_pat(cx, field, indent + 1);
417             }
418         },
419         hir::PatKind::Struct(ref path, ref fields, ignore) => {
420             println!("{}Struct", ind);
421             println!(
422                 "{}name: {}",
423                 ind,
424                 print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
425             );
426             println!("{}ignore leftover fields: {}", ind, ignore);
427             println!("{}fields:", ind);
428             for field in fields {
429                 println!("{}  field name: {}", ind, field.ident.name);
430                 if field.is_shorthand {
431                     println!("{}  in shorthand notation", ind);
432                 }
433                 print_pat(cx, &field.pat, indent + 1);
434             }
435         },
436         hir::PatKind::TupleStruct(ref path, ref fields, opt_dots_position) => {
437             println!("{}TupleStruct", ind);
438             println!(
439                 "{}path: {}",
440                 ind,
441                 print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
442             );
443             if let Some(dot_position) = opt_dots_position {
444                 println!("{}dot position: {}", ind, dot_position);
445             }
446             for field in fields {
447                 print_pat(cx, field, indent + 1);
448             }
449         },
450         hir::PatKind::Path(hir::QPath::Resolved(ref ty, ref path)) => {
451             println!("{}Resolved Path, {:?}", ind, ty);
452             println!("{}path: {:?}", ind, path);
453         },
454         hir::PatKind::Path(hir::QPath::TypeRelative(ref ty, ref seg)) => {
455             println!("{}Relative Path, {:?}", ind, ty);
456             println!("{}seg: {:?}", ind, seg);
457         },
458         hir::PatKind::Tuple(ref pats, opt_dots_position) => {
459             println!("{}Tuple", ind);
460             if let Some(dot_position) = opt_dots_position {
461                 println!("{}dot position: {}", ind, dot_position);
462             }
463             for field in pats {
464                 print_pat(cx, field, indent + 1);
465             }
466         },
467         hir::PatKind::Box(ref inner) => {
468             println!("{}Box", ind);
469             print_pat(cx, inner, indent + 1);
470         },
471         hir::PatKind::Ref(ref inner, ref muta) => {
472             println!("{}Ref", ind);
473             println!("{}mutability: {:?}", ind, muta);
474             print_pat(cx, inner, indent + 1);
475         },
476         hir::PatKind::Lit(ref e) => {
477             println!("{}Lit", ind);
478             print_expr(cx, e, indent + 1);
479         },
480         hir::PatKind::Range(ref l, ref r, ref range_end) => {
481             println!("{}Range", ind);
482             print_expr(cx, l, indent + 1);
483             print_expr(cx, r, indent + 1);
484             match *range_end {
485                 hir::RangeEnd::Included => println!("{} end included", ind),
486                 hir::RangeEnd::Excluded => println!("{} end excluded", ind),
487             }
488         },
489         hir::PatKind::Slice(ref first_pats, ref range, ref last_pats) => {
490             println!("{}Slice [a, b, ..i, y, z]", ind);
491             println!("[a, b]:");
492             for pat in first_pats {
493                 print_pat(cx, pat, indent + 1);
494             }
495             println!("i:");
496             if let Some(ref pat) = *range {
497                 print_pat(cx, pat, indent + 1);
498             }
499             println!("[y, z]:");
500             for pat in last_pats {
501                 print_pat(cx, pat, indent + 1);
502             }
503         },
504     }
505 }
506
507 fn print_guard(cx: &LateContext<'_, '_>, guard: &hir::Guard, indent: usize) {
508     let ind = "  ".repeat(indent);
509     println!("{}+", ind);
510     match guard {
511         hir::Guard::If(expr) => {
512             println!("{}If", ind);
513             print_expr(cx, expr, indent + 1);
514         },
515     }
516 }