]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/utils/inspector.rs
Use `summary_opts()` in another spot
[rust.git] / src / tools / clippy / clippy_lints / src / utils / inspector.rs
1 //! checks for attributes
2
3 use crate::utils::get_attr;
4 use rustc_ast::ast::{Attribute, InlineAsmTemplatePiece};
5 use rustc_hir as hir;
6 use rustc_lint::{LateContext, LateLintPass, LintContext};
7 use rustc_session::Session;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9
10 declare_clippy_lint! {
11     /// **What it does:** Dumps every ast/hir node which has the `#[clippy::dump]`
12     /// attribute
13     ///
14     /// **Example:**
15     /// ```rust,ignore
16     /// #[clippy::dump]
17     /// extern crate foo;
18     /// ```
19     ///
20     /// prints
21     ///
22     /// ```text
23     /// item `foo`
24     /// visibility inherited from outer item
25     /// extern crate dylib source: "/path/to/foo.so"
26     /// ```
27     pub DEEP_CODE_INSPECTION,
28     internal_warn,
29     "helper to dump info about code"
30 }
31
32 declare_lint_pass!(DeepCodeInspector => [DEEP_CODE_INSPECTION]);
33
34 impl<'tcx> LateLintPass<'tcx> for DeepCodeInspector {
35     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
36         if !has_attr(cx.sess(), &item.attrs) {
37             return;
38         }
39         print_item(cx, item);
40     }
41
42     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
43         if !has_attr(cx.sess(), &item.attrs) {
44             return;
45         }
46         println!("impl item `{}`", item.ident.name);
47         match item.vis.node {
48             hir::VisibilityKind::Public => println!("public"),
49             hir::VisibilityKind::Crate(_) => println!("visible crate wide"),
50             hir::VisibilityKind::Restricted { ref path, .. } => println!(
51                 "visible in module `{}`",
52                 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_path(path, false))
53             ),
54             hir::VisibilityKind::Inherited => println!("visibility inherited from outer item"),
55         }
56         if item.defaultness.is_default() {
57             println!("default");
58         }
59         match item.kind {
60             hir::ImplItemKind::Const(_, body_id) => {
61                 println!("associated constant");
62                 print_expr(cx, &cx.tcx.hir().body(body_id).value, 1);
63             },
64             hir::ImplItemKind::Fn(..) => println!("method"),
65             hir::ImplItemKind::TyAlias(_) => println!("associated type"),
66         }
67     }
68     // fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx
69     // hir::TraitItem) {
70     // if !has_attr(&item.attrs) {
71     // return;
72     // }
73     // }
74     //
75     // fn check_variant(&mut self, cx: &LateContext<'tcx>, var: &'tcx
76     // hir::Variant, _:
77     // &hir::Generics) {
78     // if !has_attr(&var.node.attrs) {
79     // return;
80     // }
81     // }
82     //
83     // fn check_struct_field(&mut self, cx: &LateContext<'tcx>, field: &'tcx
84     // hir::StructField) {
85     // if !has_attr(&field.attrs) {
86     // return;
87     // }
88     // }
89     //
90
91     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
92         if !has_attr(cx.sess(), &expr.attrs) {
93             return;
94         }
95         print_expr(cx, expr, 0);
96     }
97
98     fn check_arm(&mut self, cx: &LateContext<'tcx>, arm: &'tcx hir::Arm<'_>) {
99         if !has_attr(cx.sess(), &arm.attrs) {
100             return;
101         }
102         print_pat(cx, &arm.pat, 1);
103         if let Some(ref guard) = arm.guard {
104             println!("guard:");
105             print_guard(cx, guard, 1);
106         }
107         println!("body:");
108         print_expr(cx, &arm.body, 1);
109     }
110
111     fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx hir::Stmt<'_>) {
112         if !has_attr(cx.sess(), stmt.kind.attrs(|id| cx.tcx.hir().item(id.id))) {
113             return;
114         }
115         match stmt.kind {
116             hir::StmtKind::Local(ref local) => {
117                 println!("local variable of type {}", cx.typeck_results().node_type(local.hir_id));
118                 println!("pattern:");
119                 print_pat(cx, &local.pat, 0);
120                 if let Some(ref e) = local.init {
121                     println!("init expression:");
122                     print_expr(cx, e, 0);
123                 }
124             },
125             hir::StmtKind::Item(_) => println!("item decl"),
126             hir::StmtKind::Expr(ref e) | hir::StmtKind::Semi(ref e) => print_expr(cx, e, 0),
127         }
128     }
129     // fn check_foreign_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx
130     // hir::ForeignItem) {
131     // if !has_attr(&item.attrs) {
132     // return;
133     // }
134     // }
135     //
136 }
137
138 fn has_attr(sess: &Session, attrs: &[Attribute]) -> bool {
139     get_attr(sess, attrs, "dump").count() > 0
140 }
141
142 #[allow(clippy::similar_names)]
143 #[allow(clippy::too_many_lines)]
144 fn print_expr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, indent: usize) {
145     let ind = "  ".repeat(indent);
146     println!("{}+", ind);
147     println!("{}ty: {}", ind, cx.typeck_results().expr_ty(expr));
148     println!(
149         "{}adjustments: {:?}",
150         ind,
151         cx.typeck_results().adjustments().get(expr.hir_id)
152     );
153     match expr.kind {
154         hir::ExprKind::Box(ref e) => {
155             println!("{}Box", ind);
156             print_expr(cx, e, indent + 1);
157         },
158         hir::ExprKind::Array(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, 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, _, 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(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::Path(hir::QPath::LangItem(lang_item, ..)) => {
270             println!("{}Lang Item Path, {:?}", ind, lang_item.name());
271         },
272         hir::ExprKind::AddrOf(kind, ref muta, ref e) => {
273             println!("{}AddrOf", ind);
274             println!("kind: {:?}", kind);
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 asm) => {
292             println!("{}InlineAsm", ind);
293             println!("{}template: {}", ind, InlineAsmTemplatePiece::to_string(asm.template));
294             println!("{}options: {:?}", ind, asm.options);
295             println!("{}operands:", ind);
296             for op in asm.operands {
297                 match op {
298                     hir::InlineAsmOperand::In { expr, .. }
299                     | hir::InlineAsmOperand::InOut { expr, .. }
300                     | hir::InlineAsmOperand::Const { expr }
301                     | hir::InlineAsmOperand::Sym { expr } => print_expr(cx, expr, indent + 1),
302                     hir::InlineAsmOperand::Out { expr, .. } => {
303                         if let Some(expr) = expr {
304                             print_expr(cx, expr, indent + 1);
305                         }
306                     },
307                     hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
308                         print_expr(cx, in_expr, indent + 1);
309                         if let Some(out_expr) = out_expr {
310                             print_expr(cx, out_expr, indent + 1);
311                         }
312                     },
313                 }
314             }
315         },
316         hir::ExprKind::LlvmInlineAsm(ref asm) => {
317             let inputs = &asm.inputs_exprs;
318             let outputs = &asm.outputs_exprs;
319             println!("{}LlvmInlineAsm", ind);
320             println!("{}inputs:", ind);
321             for e in inputs.iter() {
322                 print_expr(cx, e, indent + 1);
323             }
324             println!("{}outputs:", ind);
325             for e in outputs.iter() {
326                 print_expr(cx, e, indent + 1);
327             }
328         },
329         hir::ExprKind::Struct(ref path, fields, ref base) => {
330             println!("{}Struct", ind);
331             println!("{}path: {:?}", ind, path);
332             for field in fields {
333                 println!("{}field \"{}\":", ind, field.ident.name);
334                 print_expr(cx, &field.expr, indent + 1);
335             }
336             if let Some(ref base) = *base {
337                 println!("{}base:", ind);
338                 print_expr(cx, base, indent + 1);
339             }
340         },
341         hir::ExprKind::ConstBlock(ref anon_const) => {
342             println!("{}ConstBlock", ind);
343             println!("{}anon_const:", ind);
344             print_expr(cx, &cx.tcx.hir().body(anon_const.body).value, indent + 1);
345         },
346         hir::ExprKind::Repeat(ref val, ref anon_const) => {
347             println!("{}Repeat", ind);
348             println!("{}value:", ind);
349             print_expr(cx, val, indent + 1);
350             println!("{}repeat count:", ind);
351             print_expr(cx, &cx.tcx.hir().body(anon_const.body).value, indent + 1);
352         },
353         hir::ExprKind::Err => {
354             println!("{}Err", ind);
355         },
356         hir::ExprKind::DropTemps(ref e) => {
357             println!("{}DropTemps", ind);
358             print_expr(cx, e, indent + 1);
359         },
360     }
361 }
362
363 fn print_item(cx: &LateContext<'_>, item: &hir::Item<'_>) {
364     let did = cx.tcx.hir().local_def_id(item.hir_id);
365     println!("item `{}`", item.ident.name);
366     match item.vis.node {
367         hir::VisibilityKind::Public => println!("public"),
368         hir::VisibilityKind::Crate(_) => println!("visible crate wide"),
369         hir::VisibilityKind::Restricted { ref path, .. } => println!(
370             "visible in module `{}`",
371             rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_path(path, false))
372         ),
373         hir::VisibilityKind::Inherited => println!("visibility inherited from outer item"),
374     }
375     match item.kind {
376         hir::ItemKind::ExternCrate(ref _renamed_from) => {
377             let def_id = cx.tcx.hir().local_def_id(item.hir_id);
378             if let Some(crate_id) = cx.tcx.extern_mod_stmt_cnum(def_id) {
379                 let source = cx.tcx.used_crate_source(crate_id);
380                 if let Some(ref src) = source.dylib {
381                     println!("extern crate dylib source: {:?}", src.0);
382                 }
383                 if let Some(ref src) = source.rlib {
384                     println!("extern crate rlib source: {:?}", src.0);
385                 }
386             } else {
387                 println!("weird extern crate without a crate id");
388             }
389         },
390         hir::ItemKind::Use(ref path, ref kind) => println!("{:?}, {:?}", path, kind),
391         hir::ItemKind::Static(..) => println!("static item of type {:#?}", cx.tcx.type_of(did)),
392         hir::ItemKind::Const(..) => println!("const item of type {:#?}", cx.tcx.type_of(did)),
393         hir::ItemKind::Fn(..) => {
394             let item_ty = cx.tcx.type_of(did);
395             println!("function of type {:#?}", item_ty);
396         },
397         hir::ItemKind::Mod(..) => println!("module"),
398         hir::ItemKind::ForeignMod { abi, .. } => println!("foreign module with abi: {}", abi),
399         hir::ItemKind::GlobalAsm(ref asm) => println!("global asm: {:?}", asm),
400         hir::ItemKind::TyAlias(..) => {
401             println!("type alias for {:?}", cx.tcx.type_of(did));
402         },
403         hir::ItemKind::OpaqueTy(..) => {
404             println!("existential type with real type {:?}", cx.tcx.type_of(did));
405         },
406         hir::ItemKind::Enum(..) => {
407             println!("enum definition of type {:?}", cx.tcx.type_of(did));
408         },
409         hir::ItemKind::Struct(..) => {
410             println!("struct definition of type {:?}", cx.tcx.type_of(did));
411         },
412         hir::ItemKind::Union(..) => {
413             println!("union definition of type {:?}", cx.tcx.type_of(did));
414         },
415         hir::ItemKind::Trait(..) => {
416             println!("trait decl");
417             if cx.tcx.trait_is_auto(did.to_def_id()) {
418                 println!("trait is auto");
419             } else {
420                 println!("trait is not auto");
421             }
422         },
423         hir::ItemKind::TraitAlias(..) => {
424             println!("trait alias");
425         },
426         hir::ItemKind::Impl {
427             of_trait: Some(ref _trait_ref),
428             ..
429         } => {
430             println!("trait impl");
431         },
432         hir::ItemKind::Impl { of_trait: None, .. } => {
433             println!("impl");
434         },
435     }
436 }
437
438 #[allow(clippy::similar_names)]
439 #[allow(clippy::too_many_lines)]
440 fn print_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, indent: usize) {
441     let ind = "  ".repeat(indent);
442     println!("{}+", ind);
443     match pat.kind {
444         hir::PatKind::Wild => println!("{}Wild", ind),
445         hir::PatKind::Binding(ref mode, .., ident, ref inner) => {
446             println!("{}Binding", ind);
447             println!("{}mode: {:?}", ind, mode);
448             println!("{}name: {}", ind, ident.name);
449             if let Some(ref inner) = *inner {
450                 println!("{}inner:", ind);
451                 print_pat(cx, inner, indent + 1);
452             }
453         },
454         hir::PatKind::Or(fields) => {
455             println!("{}Or", ind);
456             for field in fields {
457                 print_pat(cx, field, indent + 1);
458             }
459         },
460         hir::PatKind::Struct(ref path, fields, ignore) => {
461             println!("{}Struct", ind);
462             println!(
463                 "{}name: {}",
464                 ind,
465                 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
466             );
467             println!("{}ignore leftover fields: {}", ind, ignore);
468             println!("{}fields:", ind);
469             for field in fields {
470                 println!("{}  field name: {}", ind, field.ident.name);
471                 if field.is_shorthand {
472                     println!("{}  in shorthand notation", ind);
473                 }
474                 print_pat(cx, &field.pat, indent + 1);
475             }
476         },
477         hir::PatKind::TupleStruct(ref path, fields, opt_dots_position) => {
478             println!("{}TupleStruct", ind);
479             println!(
480                 "{}path: {}",
481                 ind,
482                 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
483             );
484             if let Some(dot_position) = opt_dots_position {
485                 println!("{}dot position: {}", ind, dot_position);
486             }
487             for field in fields {
488                 print_pat(cx, field, indent + 1);
489             }
490         },
491         hir::PatKind::Path(hir::QPath::Resolved(ref ty, ref path)) => {
492             println!("{}Resolved Path, {:?}", ind, ty);
493             println!("{}path: {:?}", ind, path);
494         },
495         hir::PatKind::Path(hir::QPath::TypeRelative(ref ty, ref seg)) => {
496             println!("{}Relative Path, {:?}", ind, ty);
497             println!("{}seg: {:?}", ind, seg);
498         },
499         hir::PatKind::Path(hir::QPath::LangItem(lang_item, ..)) => {
500             println!("{}Lang Item Path, {:?}", ind, lang_item.name());
501         },
502         hir::PatKind::Tuple(pats, opt_dots_position) => {
503             println!("{}Tuple", ind);
504             if let Some(dot_position) = opt_dots_position {
505                 println!("{}dot position: {}", ind, dot_position);
506             }
507             for field in pats {
508                 print_pat(cx, field, indent + 1);
509             }
510         },
511         hir::PatKind::Box(ref inner) => {
512             println!("{}Box", ind);
513             print_pat(cx, inner, indent + 1);
514         },
515         hir::PatKind::Ref(ref inner, ref muta) => {
516             println!("{}Ref", ind);
517             println!("{}mutability: {:?}", ind, muta);
518             print_pat(cx, inner, indent + 1);
519         },
520         hir::PatKind::Lit(ref e) => {
521             println!("{}Lit", ind);
522             print_expr(cx, e, indent + 1);
523         },
524         hir::PatKind::Range(ref l, ref r, ref range_end) => {
525             println!("{}Range", ind);
526             if let Some(expr) = l {
527                 print_expr(cx, expr, indent + 1);
528             }
529             if let Some(expr) = r {
530                 print_expr(cx, expr, indent + 1);
531             }
532             match *range_end {
533                 hir::RangeEnd::Included => println!("{} end included", ind),
534                 hir::RangeEnd::Excluded => println!("{} end excluded", ind),
535             }
536         },
537         hir::PatKind::Slice(first_pats, ref range, last_pats) => {
538             println!("{}Slice [a, b, ..i, y, z]", ind);
539             println!("[a, b]:");
540             for pat in first_pats {
541                 print_pat(cx, pat, indent + 1);
542             }
543             println!("i:");
544             if let Some(ref pat) = *range {
545                 print_pat(cx, pat, indent + 1);
546             }
547             println!("[y, z]:");
548             for pat in last_pats {
549                 print_pat(cx, pat, indent + 1);
550             }
551         },
552     }
553 }
554
555 fn print_guard(cx: &LateContext<'_>, guard: &hir::Guard<'_>, indent: usize) {
556     let ind = "  ".repeat(indent);
557     println!("{}+", ind);
558     match guard {
559         hir::Guard::If(expr) => {
560             println!("{}If", ind);
561             print_expr(cx, expr, indent + 1);
562         },
563     }
564 }