]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/inspector.rs
lint all guard types, not just lock functions
[rust.git] / clippy_lints / src / utils / inspector.rs
1 //! checks for attributes
2
3 use crate::utils::get_attr;
4 use rustc::session::Session;
5 use rustc_hir as hir;
6 use rustc_hir::print;
7 use rustc_lint::{LateContext, LateLintPass, LintContext};
8 use rustc_session::{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(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, 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, _, 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(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(kind, ref muta, ref e) => {
268             println!("{}AddrOf", ind);
269             println!("kind: {:?}", kind);
270             println!("mutability: {:?}", muta);
271             print_expr(cx, e, indent + 1);
272         },
273         hir::ExprKind::Break(_, ref e) => {
274             println!("{}Break", ind);
275             if let Some(ref e) = *e {
276                 print_expr(cx, e, indent + 1);
277             }
278         },
279         hir::ExprKind::Continue(_) => println!("{}Again", ind),
280         hir::ExprKind::Ret(ref e) => {
281             println!("{}Ret", ind);
282             if let Some(ref e) = *e {
283                 print_expr(cx, e, indent + 1);
284             }
285         },
286         hir::ExprKind::InlineAsm(ref asm) => {
287             let inputs = &asm.inputs_exprs;
288             let outputs = &asm.outputs_exprs;
289             println!("{}InlineAsm", ind);
290             println!("{}inputs:", ind);
291             for e in inputs.iter() {
292                 print_expr(cx, e, indent + 1);
293             }
294             println!("{}outputs:", ind);
295             for e in outputs.iter() {
296                 print_expr(cx, e, indent + 1);
297             }
298         },
299         hir::ExprKind::Struct(ref path, fields, ref base) => {
300             println!("{}Struct", ind);
301             println!("{}path: {:?}", ind, path);
302             for field in fields {
303                 println!("{}field \"{}\":", ind, field.ident.name);
304                 print_expr(cx, &field.expr, indent + 1);
305             }
306             if let Some(ref base) = *base {
307                 println!("{}base:", ind);
308                 print_expr(cx, base, indent + 1);
309             }
310         },
311         hir::ExprKind::Repeat(ref val, ref anon_const) => {
312             println!("{}Repeat", ind);
313             println!("{}value:", ind);
314             print_expr(cx, val, indent + 1);
315             println!("{}repeat count:", ind);
316             print_expr(cx, &cx.tcx.hir().body(anon_const.body).value, indent + 1);
317         },
318         hir::ExprKind::Err => {
319             println!("{}Err", ind);
320         },
321         hir::ExprKind::DropTemps(ref e) => {
322             println!("{}DropTemps", ind);
323             print_expr(cx, e, indent + 1);
324         },
325     }
326 }
327
328 fn print_item(cx: &LateContext<'_, '_>, item: &hir::Item<'_>) {
329     let did = cx.tcx.hir().local_def_id(item.hir_id);
330     println!("item `{}`", item.ident.name);
331     match item.vis.node {
332         hir::VisibilityKind::Public => println!("public"),
333         hir::VisibilityKind::Crate(_) => println!("visible crate wide"),
334         hir::VisibilityKind::Restricted { ref path, .. } => println!(
335             "visible in module `{}`",
336             print::to_string(print::NO_ANN, |s| s.print_path(path, false))
337         ),
338         hir::VisibilityKind::Inherited => println!("visibility inherited from outer item"),
339     }
340     match item.kind {
341         hir::ItemKind::ExternCrate(ref _renamed_from) => {
342             let def_id = cx.tcx.hir().local_def_id(item.hir_id);
343             if let Some(crate_id) = cx.tcx.extern_mod_stmt_cnum(def_id) {
344                 let source = cx.tcx.used_crate_source(crate_id);
345                 if let Some(ref src) = source.dylib {
346                     println!("extern crate dylib source: {:?}", src.0);
347                 }
348                 if let Some(ref src) = source.rlib {
349                     println!("extern crate rlib source: {:?}", src.0);
350                 }
351             } else {
352                 println!("weird extern crate without a crate id");
353             }
354         },
355         hir::ItemKind::Use(ref path, ref kind) => println!("{:?}, {:?}", path, kind),
356         hir::ItemKind::Static(..) => println!("static item of type {:#?}", cx.tcx.type_of(did)),
357         hir::ItemKind::Const(..) => println!("const item of type {:#?}", cx.tcx.type_of(did)),
358         hir::ItemKind::Fn(..) => {
359             let item_ty = cx.tcx.type_of(did);
360             println!("function of type {:#?}", item_ty);
361         },
362         hir::ItemKind::Mod(..) => println!("module"),
363         hir::ItemKind::ForeignMod(ref fm) => println!("foreign module with abi: {}", fm.abi),
364         hir::ItemKind::GlobalAsm(ref asm) => println!("global asm: {:?}", asm),
365         hir::ItemKind::TyAlias(..) => {
366             println!("type alias for {:?}", cx.tcx.type_of(did));
367         },
368         hir::ItemKind::OpaqueTy(..) => {
369             println!("existential type with real type {:?}", cx.tcx.type_of(did));
370         },
371         hir::ItemKind::Enum(..) => {
372             println!("enum definition of type {:?}", cx.tcx.type_of(did));
373         },
374         hir::ItemKind::Struct(..) => {
375             println!("struct definition of type {:?}", cx.tcx.type_of(did));
376         },
377         hir::ItemKind::Union(..) => {
378             println!("union definition of type {:?}", cx.tcx.type_of(did));
379         },
380         hir::ItemKind::Trait(..) => {
381             println!("trait decl");
382             if cx.tcx.trait_is_auto(did) {
383                 println!("trait is auto");
384             } else {
385                 println!("trait is not auto");
386             }
387         },
388         hir::ItemKind::TraitAlias(..) => {
389             println!("trait alias");
390         },
391         hir::ItemKind::Impl {
392             of_trait: Some(ref _trait_ref),
393             ..
394         } => {
395             println!("trait impl");
396         },
397         hir::ItemKind::Impl { of_trait: None, .. } => {
398             println!("impl");
399         },
400     }
401 }
402
403 #[allow(clippy::similar_names)]
404 #[allow(clippy::too_many_lines)]
405 fn print_pat(cx: &LateContext<'_, '_>, pat: &hir::Pat<'_>, indent: usize) {
406     let ind = "  ".repeat(indent);
407     println!("{}+", ind);
408     match pat.kind {
409         hir::PatKind::Wild => println!("{}Wild", ind),
410         hir::PatKind::Binding(ref mode, .., ident, ref inner) => {
411             println!("{}Binding", ind);
412             println!("{}mode: {:?}", ind, mode);
413             println!("{}name: {}", ind, ident.name);
414             if let Some(ref inner) = *inner {
415                 println!("{}inner:", ind);
416                 print_pat(cx, inner, indent + 1);
417             }
418         },
419         hir::PatKind::Or(fields) => {
420             println!("{}Or", ind);
421             for field in fields {
422                 print_pat(cx, field, indent + 1);
423             }
424         },
425         hir::PatKind::Struct(ref path, fields, ignore) => {
426             println!("{}Struct", ind);
427             println!(
428                 "{}name: {}",
429                 ind,
430                 print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
431             );
432             println!("{}ignore leftover fields: {}", ind, ignore);
433             println!("{}fields:", ind);
434             for field in fields {
435                 println!("{}  field name: {}", ind, field.ident.name);
436                 if field.is_shorthand {
437                     println!("{}  in shorthand notation", ind);
438                 }
439                 print_pat(cx, &field.pat, indent + 1);
440             }
441         },
442         hir::PatKind::TupleStruct(ref path, fields, opt_dots_position) => {
443             println!("{}TupleStruct", ind);
444             println!(
445                 "{}path: {}",
446                 ind,
447                 print::to_string(print::NO_ANN, |s| s.print_qpath(path, false))
448             );
449             if let Some(dot_position) = opt_dots_position {
450                 println!("{}dot position: {}", ind, dot_position);
451             }
452             for field in fields {
453                 print_pat(cx, field, indent + 1);
454             }
455         },
456         hir::PatKind::Path(hir::QPath::Resolved(ref ty, ref path)) => {
457             println!("{}Resolved Path, {:?}", ind, ty);
458             println!("{}path: {:?}", ind, path);
459         },
460         hir::PatKind::Path(hir::QPath::TypeRelative(ref ty, ref seg)) => {
461             println!("{}Relative Path, {:?}", ind, ty);
462             println!("{}seg: {:?}", ind, seg);
463         },
464         hir::PatKind::Tuple(pats, opt_dots_position) => {
465             println!("{}Tuple", ind);
466             if let Some(dot_position) = opt_dots_position {
467                 println!("{}dot position: {}", ind, dot_position);
468             }
469             for field in pats {
470                 print_pat(cx, field, indent + 1);
471             }
472         },
473         hir::PatKind::Box(ref inner) => {
474             println!("{}Box", ind);
475             print_pat(cx, inner, indent + 1);
476         },
477         hir::PatKind::Ref(ref inner, ref muta) => {
478             println!("{}Ref", ind);
479             println!("{}mutability: {:?}", ind, muta);
480             print_pat(cx, inner, indent + 1);
481         },
482         hir::PatKind::Lit(ref e) => {
483             println!("{}Lit", ind);
484             print_expr(cx, e, indent + 1);
485         },
486         hir::PatKind::Range(ref l, ref r, ref range_end) => {
487             println!("{}Range", ind);
488             if let Some(expr) = l {
489                 print_expr(cx, expr, indent + 1);
490             }
491             if let Some(expr) = r {
492                 print_expr(cx, expr, indent + 1);
493             }
494             match *range_end {
495                 hir::RangeEnd::Included => println!("{} end included", ind),
496                 hir::RangeEnd::Excluded => println!("{} end excluded", ind),
497             }
498         },
499         hir::PatKind::Slice(first_pats, ref range, last_pats) => {
500             println!("{}Slice [a, b, ..i, y, z]", ind);
501             println!("[a, b]:");
502             for pat in first_pats {
503                 print_pat(cx, pat, indent + 1);
504             }
505             println!("i:");
506             if let Some(ref pat) = *range {
507                 print_pat(cx, pat, indent + 1);
508             }
509             println!("[y, z]:");
510             for pat in last_pats {
511                 print_pat(cx, pat, indent + 1);
512             }
513         },
514     }
515 }
516
517 fn print_guard(cx: &LateContext<'_, '_>, guard: &hir::Guard<'_>, indent: usize) {
518     let ind = "  ".repeat(indent);
519     println!("{}+", ind);
520     match guard {
521         hir::Guard::If(expr) => {
522             println!("{}If", ind);
523             print_expr(cx, expr, indent + 1);
524         },
525     }
526 }