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