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