]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/inspector.rs
Auto merge of #4218 - lzutao:rustup, r=phansch
[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
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     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.node {
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::Type(_) => println!("associated type"),
67             hir::ImplItemKind::Existential(_) => 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         for pat in &arm.pats {
105             print_pat(cx, pat, 1);
106         }
107         if let Some(ref guard) = arm.guard {
108             println!("guard:");
109             print_guard(cx, guard, 1);
110         }
111         println!("body:");
112         print_expr(cx, &arm.body, 1);
113     }
114
115     fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
116         if !has_attr(cx.sess(), stmt.node.attrs()) {
117             return;
118         }
119         match stmt.node {
120             hir::StmtKind::Local(ref local) => {
121                 println!("local variable of type {}", cx.tables.node_type(local.hir_id));
122                 println!("pattern:");
123                 print_pat(cx, &local.pat, 0);
124                 if let Some(ref e) = local.init {
125                     println!("init expression:");
126                     print_expr(cx, e, 0);
127                 }
128             },
129             hir::StmtKind::Item(_) => println!("item decl"),
130             hir::StmtKind::Expr(ref e) | hir::StmtKind::Semi(ref e) => print_expr(cx, e, 0),
131         }
132     }
133     // fn check_foreign_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx
134     // hir::ForeignItem) {
135     // if !has_attr(&item.attrs) {
136     // return;
137     // }
138     // }
139     //
140 }
141
142 fn has_attr(sess: &Session, attrs: &[Attribute]) -> bool {
143     get_attr(sess, attrs, "dump").count() > 0
144 }
145
146 #[allow(clippy::similar_names)]
147 fn print_expr(cx: &LateContext<'_, '_>, expr: &hir::Expr, indent: usize) {
148     let ind = "  ".repeat(indent);
149     println!("{}+", ind);
150     println!("{}ty: {}", ind, cx.tables.expr_ty(expr));
151     println!("{}adjustments: {:?}", ind, cx.tables.adjustments().get(expr.hir_id));
152     match expr.node {
153         hir::ExprKind::Box(ref e) => {
154             println!("{}Box", ind);
155             print_expr(cx, e, indent + 1);
156         },
157         hir::ExprKind::Array(ref v) => {
158             println!("{}Array", ind);
159             for e in v {
160                 print_expr(cx, e, indent + 1);
161             }
162         },
163         hir::ExprKind::Call(ref func, ref args) => {
164             println!("{}Call", ind);
165             println!("{}function:", ind);
166             print_expr(cx, func, indent + 1);
167             println!("{}arguments:", ind);
168             for arg in args {
169                 print_expr(cx, arg, indent + 1);
170             }
171         },
172         hir::ExprKind::MethodCall(ref path, _, ref args) => {
173             println!("{}MethodCall", ind);
174             println!("{}method name: {}", ind, path.ident.name);
175             for arg in args {
176                 print_expr(cx, arg, indent + 1);
177             }
178         },
179         hir::ExprKind::Tup(ref v) => {
180             println!("{}Tup", ind);
181             for e in v {
182                 print_expr(cx, e, indent + 1);
183             }
184         },
185         hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
186             println!("{}Binary", ind);
187             println!("{}op: {:?}", ind, op.node);
188             println!("{}lhs:", ind);
189             print_expr(cx, lhs, indent + 1);
190             println!("{}rhs:", ind);
191             print_expr(cx, rhs, indent + 1);
192         },
193         hir::ExprKind::Unary(op, ref inner) => {
194             println!("{}Unary", ind);
195             println!("{}op: {:?}", ind, op);
196             print_expr(cx, inner, indent + 1);
197         },
198         hir::ExprKind::Lit(ref lit) => {
199             println!("{}Lit", ind);
200             println!("{}{:?}", ind, lit);
201         },
202         hir::ExprKind::Cast(ref e, ref target) => {
203             println!("{}Cast", ind);
204             print_expr(cx, e, indent + 1);
205             println!("{}target type: {:?}", ind, target);
206         },
207         hir::ExprKind::Type(ref e, ref target) => {
208             println!("{}Type", ind);
209             print_expr(cx, e, indent + 1);
210             println!("{}target type: {:?}", ind, target);
211         },
212         hir::ExprKind::While(ref cond, _, _) => {
213             println!("{}While", ind);
214             println!("{}condition:", ind);
215             print_expr(cx, cond, indent + 1);
216         },
217         hir::ExprKind::Loop(..) => {
218             println!("{}Loop", ind);
219         },
220         hir::ExprKind::Match(ref cond, _, ref source) => {
221             println!("{}Match", ind);
222             println!("{}condition:", ind);
223             print_expr(cx, cond, indent + 1);
224             println!("{}source: {:?}", ind, source);
225         },
226         hir::ExprKind::Closure(ref clause, _, _, _, _) => {
227             println!("{}Closure", ind);
228             println!("{}clause: {:?}", ind, clause);
229         },
230         hir::ExprKind::Yield(ref sub, _) => {
231             println!("{}Yield", ind);
232             print_expr(cx, sub, indent + 1);
233         },
234         hir::ExprKind::Block(_, _) => {
235             println!("{}Block", ind);
236         },
237         hir::ExprKind::Assign(ref lhs, ref rhs) => {
238             println!("{}Assign", ind);
239             println!("{}lhs:", ind);
240             print_expr(cx, lhs, indent + 1);
241             println!("{}rhs:", ind);
242             print_expr(cx, rhs, indent + 1);
243         },
244         hir::ExprKind::AssignOp(ref binop, ref lhs, ref rhs) => {
245             println!("{}AssignOp", ind);
246             println!("{}op: {:?}", ind, binop.node);
247             println!("{}lhs:", ind);
248             print_expr(cx, lhs, indent + 1);
249             println!("{}rhs:", ind);
250             print_expr(cx, rhs, indent + 1);
251         },
252         hir::ExprKind::Field(ref e, ident) => {
253             println!("{}Field", ind);
254             println!("{}field name: {}", ind, ident.name);
255             println!("{}struct expr:", ind);
256             print_expr(cx, e, indent + 1);
257         },
258         hir::ExprKind::Index(ref arr, ref idx) => {
259             println!("{}Index", ind);
260             println!("{}array expr:", ind);
261             print_expr(cx, arr, indent + 1);
262             println!("{}index expr:", ind);
263             print_expr(cx, idx, indent + 1);
264         },
265         hir::ExprKind::Path(hir::QPath::Resolved(ref ty, ref path)) => {
266             println!("{}Resolved Path, {:?}", ind, ty);
267             println!("{}path: {:?}", ind, path);
268         },
269         hir::ExprKind::Path(hir::QPath::TypeRelative(ref ty, ref seg)) => {
270             println!("{}Relative Path, {:?}", ind, ty);
271             println!("{}seg: {:?}", ind, seg);
272         },
273         hir::ExprKind::AddrOf(ref muta, ref e) => {
274             println!("{}AddrOf", ind);
275             println!("mutability: {:?}", muta);
276             print_expr(cx, e, indent + 1);
277         },
278         hir::ExprKind::Break(_, ref e) => {
279             println!("{}Break", ind);
280             if let Some(ref e) = *e {
281                 print_expr(cx, e, indent + 1);
282             }
283         },
284         hir::ExprKind::Continue(_) => println!("{}Again", ind),
285         hir::ExprKind::Ret(ref e) => {
286             println!("{}Ret", ind);
287             if let Some(ref e) = *e {
288                 print_expr(cx, e, indent + 1);
289             }
290         },
291         hir::ExprKind::InlineAsm(_, ref input, ref output) => {
292             println!("{}InlineAsm", ind);
293             println!("{}inputs:", ind);
294             for e in input {
295                 print_expr(cx, e, indent + 1);
296             }
297             println!("{}outputs:", ind);
298             for e in output {
299                 print_expr(cx, e, indent + 1);
300             }
301         },
302         hir::ExprKind::Struct(ref path, ref fields, ref base) => {
303             println!("{}Struct", ind);
304             println!("{}path: {:?}", ind, path);
305             for field in fields {
306                 println!("{}field \"{}\":", ind, field.ident.name);
307                 print_expr(cx, &field.expr, indent + 1);
308             }
309             if let Some(ref base) = *base {
310                 println!("{}base:", ind);
311                 print_expr(cx, base, indent + 1);
312             }
313         },
314         hir::ExprKind::Repeat(ref val, ref anon_const) => {
315             println!("{}Repeat", ind);
316             println!("{}value:", ind);
317             print_expr(cx, val, indent + 1);
318             println!("{}repeat count:", ind);
319             print_expr(cx, &cx.tcx.hir().body(anon_const.body).value, indent + 1);
320         },
321         hir::ExprKind::Err => {
322             println!("{}Err", ind);
323         },
324         hir::ExprKind::DropTemps(ref e) => {
325             println!("{}DropTemps", ind);
326             print_expr(cx, e, indent + 1);
327         },
328     }
329 }
330
331 fn print_item(cx: &LateContext<'_, '_>, item: &hir::Item) {
332     let did = cx.tcx.hir().local_def_id_from_hir_id(item.hir_id);
333     println!("item `{}`", item.ident.name);
334     match item.vis.node {
335         hir::VisibilityKind::Public => println!("public"),
336         hir::VisibilityKind::Crate(_) => println!("visible crate wide"),
337         hir::VisibilityKind::Restricted { ref path, .. } => println!(
338             "visible in module `{}`",
339             print::to_string(print::NO_ANN, |s| s.print_path(path, false))
340         ),
341         hir::VisibilityKind::Inherited => println!("visibility inherited from outer item"),
342     }
343     match item.node {
344         hir::ItemKind::ExternCrate(ref _renamed_from) => {
345             let def_id = cx.tcx.hir().local_def_id_from_hir_id(item.hir_id);
346             if let Some(crate_id) = cx.tcx.extern_mod_stmt_cnum(def_id) {
347                 let source = cx.tcx.used_crate_source(crate_id);
348                 if let Some(ref src) = source.dylib {
349                     println!("extern crate dylib source: {:?}", src.0);
350                 }
351                 if let Some(ref src) = source.rlib {
352                     println!("extern crate rlib source: {:?}", src.0);
353                 }
354             } else {
355                 println!("weird extern crate without a crate id");
356             }
357         },
358         hir::ItemKind::Use(ref path, ref kind) => println!("{:?}, {:?}", path, kind),
359         hir::ItemKind::Static(..) => println!("static item of type {:#?}", cx.tcx.type_of(did)),
360         hir::ItemKind::Const(..) => println!("const item of type {:#?}", cx.tcx.type_of(did)),
361         hir::ItemKind::Fn(..) => {
362             let item_ty = cx.tcx.type_of(did);
363             println!("function of type {:#?}", item_ty);
364         },
365         hir::ItemKind::Mod(..) => println!("module"),
366         hir::ItemKind::ForeignMod(ref fm) => println!("foreign module with abi: {}", fm.abi),
367         hir::ItemKind::GlobalAsm(ref asm) => println!("global asm: {:?}", asm),
368         hir::ItemKind::Ty(..) => {
369             println!("type alias for {:?}", cx.tcx.type_of(did));
370         },
371         hir::ItemKind::Existential(..) => {
372             println!("existential type with real type {:?}", cx.tcx.type_of(did));
373         },
374         hir::ItemKind::Enum(..) => {
375             println!("enum definition of type {:?}", cx.tcx.type_of(did));
376         },
377         hir::ItemKind::Struct(..) => {
378             println!("struct definition of type {:?}", cx.tcx.type_of(did));
379         },
380         hir::ItemKind::Union(..) => {
381             println!("union definition of type {:?}", cx.tcx.type_of(did));
382         },
383         hir::ItemKind::Trait(..) => {
384             println!("trait decl");
385             if cx.tcx.trait_is_auto(did) {
386                 println!("trait is auto");
387             } else {
388                 println!("trait is not auto");
389             }
390         },
391         hir::ItemKind::TraitAlias(..) => {
392             println!("trait alias");
393         },
394         hir::ItemKind::Impl(_, _, _, _, Some(ref _trait_ref), _, _) => {
395             println!("trait impl");
396         },
397         hir::ItemKind::Impl(_, _, _, _, None, _, _) => {
398             println!("impl");
399         },
400     }
401 }
402
403 #[allow(clippy::similar_names)]
404 fn print_pat(cx: &LateContext<'_, '_>, pat: &hir::Pat, indent: usize) {
405     let ind = "  ".repeat(indent);
406     println!("{}+", ind);
407     match pat.node {
408         hir::PatKind::Wild => println!("{}Wild", ind),
409         hir::PatKind::Binding(ref mode, .., ident, ref inner) => {
410             println!("{}Binding", ind);
411             println!("{}mode: {:?}", ind, mode);
412             println!("{}name: {}", ind, ident.name);
413             if let Some(ref inner) = *inner {
414                 println!("{}inner:", ind);
415                 print_pat(cx, inner, indent + 1);
416             }
417         },
418         hir::PatKind::Struct(ref path, ref fields, ignore) => {
419             println!("{}Struct", ind);
420             println!(
421                 "{}name: {}",
422                 ind,
423                 print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
424             );
425             println!("{}ignore leftover fields: {}", ind, ignore);
426             println!("{}fields:", ind);
427             for field in fields {
428                 println!("{}  field name: {}", ind, field.node.ident.name);
429                 if field.node.is_shorthand {
430                     println!("{}  in shorthand notation", ind);
431                 }
432                 print_pat(cx, &field.node.pat, indent + 1);
433             }
434         },
435         hir::PatKind::TupleStruct(ref path, ref fields, opt_dots_position) => {
436             println!("{}TupleStruct", ind);
437             println!(
438                 "{}path: {}",
439                 ind,
440                 print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
441             );
442             if let Some(dot_position) = opt_dots_position {
443                 println!("{}dot position: {}", ind, dot_position);
444             }
445             for field in fields {
446                 print_pat(cx, field, indent + 1);
447             }
448         },
449         hir::PatKind::Path(hir::QPath::Resolved(ref ty, ref path)) => {
450             println!("{}Resolved Path, {:?}", ind, ty);
451             println!("{}path: {:?}", ind, path);
452         },
453         hir::PatKind::Path(hir::QPath::TypeRelative(ref ty, ref seg)) => {
454             println!("{}Relative Path, {:?}", ind, ty);
455             println!("{}seg: {:?}", ind, seg);
456         },
457         hir::PatKind::Tuple(ref pats, opt_dots_position) => {
458             println!("{}Tuple", ind);
459             if let Some(dot_position) = opt_dots_position {
460                 println!("{}dot position: {}", ind, dot_position);
461             }
462             for field in pats {
463                 print_pat(cx, field, indent + 1);
464             }
465         },
466         hir::PatKind::Box(ref inner) => {
467             println!("{}Box", ind);
468             print_pat(cx, inner, indent + 1);
469         },
470         hir::PatKind::Ref(ref inner, ref muta) => {
471             println!("{}Ref", ind);
472             println!("{}mutability: {:?}", ind, muta);
473             print_pat(cx, inner, indent + 1);
474         },
475         hir::PatKind::Lit(ref e) => {
476             println!("{}Lit", ind);
477             print_expr(cx, e, indent + 1);
478         },
479         hir::PatKind::Range(ref l, ref r, ref range_end) => {
480             println!("{}Range", ind);
481             print_expr(cx, l, indent + 1);
482             print_expr(cx, r, indent + 1);
483             match *range_end {
484                 hir::RangeEnd::Included => println!("{} end included", ind),
485                 hir::RangeEnd::Excluded => println!("{} end excluded", ind),
486             }
487         },
488         hir::PatKind::Slice(ref first_pats, ref range, ref last_pats) => {
489             println!("{}Slice [a, b, ..i, y, z]", ind);
490             println!("[a, b]:");
491             for pat in first_pats {
492                 print_pat(cx, pat, indent + 1);
493             }
494             println!("i:");
495             if let Some(ref pat) = *range {
496                 print_pat(cx, pat, indent + 1);
497             }
498             println!("[y, z]:");
499             for pat in last_pats {
500                 print_pat(cx, pat, indent + 1);
501             }
502         },
503     }
504 }
505
506 fn print_guard(cx: &LateContext<'_, '_>, guard: &hir::Guard, indent: usize) {
507     let ind = "  ".repeat(indent);
508     println!("{}+", ind);
509     match guard {
510         hir::Guard::If(expr) => {
511             println!("{}If", ind);
512             print_expr(cx, expr, indent + 1);
513         },
514     }
515 }