]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/utils/inspector.rs
b3fe66ed4285eff8ba0a54f4e48275c70e0ee1ca
[rust.git] / src / tools / clippy / clippy_lints / src / utils / inspector.rs
1 //! checks for attributes
2
3 use clippy_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(), cx.tcx.hir().attrs(item.hir_id())) {
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(), cx.tcx.hir().attrs(item.hir_id())) {
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_field_def(&mut self, cx: &LateContext<'tcx>, field: &'tcx
84     // hir::FieldDef) {
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(), cx.tcx.hir().attrs(expr.hir_id)) {
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(), cx.tcx.hir().attrs(arm.hir_id)) {
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(), cx.tcx.hir().attrs(stmt.hir_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::If(ref cond, _, ref else_opt) => {
217             println!("{}If", ind);
218             println!("{}condition:", ind);
219             print_expr(cx, cond, indent + 1);
220             if let Some(ref els) = *else_opt {
221                 println!("{}else:", ind);
222                 print_expr(cx, els, indent + 1);
223             }
224         },
225         hir::ExprKind::Match(ref cond, _, ref source) => {
226             println!("{}Match", ind);
227             println!("{}condition:", ind);
228             print_expr(cx, cond, indent + 1);
229             println!("{}source: {:?}", ind, source);
230         },
231         hir::ExprKind::Closure(ref clause, _, _, _, _) => {
232             println!("{}Closure", ind);
233             println!("{}clause: {:?}", ind, clause);
234         },
235         hir::ExprKind::Yield(ref sub, _) => {
236             println!("{}Yield", ind);
237             print_expr(cx, sub, indent + 1);
238         },
239         hir::ExprKind::Block(_, _) => {
240             println!("{}Block", ind);
241         },
242         hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
243             println!("{}Assign", ind);
244             println!("{}lhs:", ind);
245             print_expr(cx, lhs, indent + 1);
246             println!("{}rhs:", ind);
247             print_expr(cx, rhs, indent + 1);
248         },
249         hir::ExprKind::AssignOp(ref binop, ref lhs, ref rhs) => {
250             println!("{}AssignOp", ind);
251             println!("{}op: {:?}", ind, binop.node);
252             println!("{}lhs:", ind);
253             print_expr(cx, lhs, indent + 1);
254             println!("{}rhs:", ind);
255             print_expr(cx, rhs, indent + 1);
256         },
257         hir::ExprKind::Field(ref e, ident) => {
258             println!("{}Field", ind);
259             println!("{}field name: {}", ind, ident.name);
260             println!("{}struct expr:", ind);
261             print_expr(cx, e, indent + 1);
262         },
263         hir::ExprKind::Index(ref arr, ref idx) => {
264             println!("{}Index", ind);
265             println!("{}array expr:", ind);
266             print_expr(cx, arr, indent + 1);
267             println!("{}index expr:", ind);
268             print_expr(cx, idx, indent + 1);
269         },
270         hir::ExprKind::Path(hir::QPath::Resolved(ref ty, ref path)) => {
271             println!("{}Resolved Path, {:?}", ind, ty);
272             println!("{}path: {:?}", ind, path);
273         },
274         hir::ExprKind::Path(hir::QPath::TypeRelative(ref ty, ref seg)) => {
275             println!("{}Relative Path, {:?}", ind, ty);
276             println!("{}seg: {:?}", ind, seg);
277         },
278         hir::ExprKind::Path(hir::QPath::LangItem(lang_item, ..)) => {
279             println!("{}Lang Item Path, {:?}", ind, lang_item.name());
280         },
281         hir::ExprKind::AddrOf(kind, ref muta, ref e) => {
282             println!("{}AddrOf", ind);
283             println!("kind: {:?}", kind);
284             println!("mutability: {:?}", muta);
285             print_expr(cx, e, indent + 1);
286         },
287         hir::ExprKind::Break(_, ref e) => {
288             println!("{}Break", ind);
289             if let Some(ref e) = *e {
290                 print_expr(cx, e, indent + 1);
291             }
292         },
293         hir::ExprKind::Continue(_) => println!("{}Again", ind),
294         hir::ExprKind::Ret(ref e) => {
295             println!("{}Ret", ind);
296             if let Some(ref e) = *e {
297                 print_expr(cx, e, indent + 1);
298             }
299         },
300         hir::ExprKind::InlineAsm(ref asm) => {
301             println!("{}InlineAsm", ind);
302             println!("{}template: {}", ind, InlineAsmTemplatePiece::to_string(asm.template));
303             println!("{}options: {:?}", ind, asm.options);
304             println!("{}operands:", ind);
305             for (op, _op_sp) in asm.operands {
306                 match op {
307                     hir::InlineAsmOperand::In { expr, .. }
308                     | hir::InlineAsmOperand::InOut { expr, .. }
309                     | hir::InlineAsmOperand::Sym { expr } => print_expr(cx, expr, indent + 1),
310                     hir::InlineAsmOperand::Out { expr, .. } => {
311                         if let Some(expr) = expr {
312                             print_expr(cx, expr, indent + 1);
313                         }
314                     },
315                     hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
316                         print_expr(cx, in_expr, indent + 1);
317                         if let Some(out_expr) = out_expr {
318                             print_expr(cx, out_expr, indent + 1);
319                         }
320                     },
321                     hir::InlineAsmOperand::Const { anon_const } => {
322                         println!("{}anon_const:", ind);
323                         print_expr(cx, &cx.tcx.hir().body(anon_const.body).value, indent + 1);
324                     }
325                 }
326             }
327         },
328         hir::ExprKind::LlvmInlineAsm(ref asm) => {
329             let inputs = &asm.inputs_exprs;
330             let outputs = &asm.outputs_exprs;
331             println!("{}LlvmInlineAsm", ind);
332             println!("{}inputs:", ind);
333             for e in inputs.iter() {
334                 print_expr(cx, e, indent + 1);
335             }
336             println!("{}outputs:", ind);
337             for e in outputs.iter() {
338                 print_expr(cx, e, indent + 1);
339             }
340         },
341         hir::ExprKind::Struct(ref path, fields, ref base) => {
342             println!("{}Struct", ind);
343             println!("{}path: {:?}", ind, path);
344             for field in fields {
345                 println!("{}field \"{}\":", ind, field.ident.name);
346                 print_expr(cx, &field.expr, indent + 1);
347             }
348             if let Some(ref base) = *base {
349                 println!("{}base:", ind);
350                 print_expr(cx, base, indent + 1);
351             }
352         },
353         hir::ExprKind::ConstBlock(ref anon_const) => {
354             println!("{}ConstBlock", ind);
355             println!("{}anon_const:", ind);
356             print_expr(cx, &cx.tcx.hir().body(anon_const.body).value, indent + 1);
357         },
358         hir::ExprKind::Repeat(ref val, ref anon_const) => {
359             println!("{}Repeat", ind);
360             println!("{}value:", ind);
361             print_expr(cx, val, indent + 1);
362             println!("{}repeat count:", ind);
363             print_expr(cx, &cx.tcx.hir().body(anon_const.body).value, indent + 1);
364         },
365         hir::ExprKind::Err => {
366             println!("{}Err", ind);
367         },
368         hir::ExprKind::DropTemps(ref e) => {
369             println!("{}DropTemps", ind);
370             print_expr(cx, e, indent + 1);
371         },
372     }
373 }
374
375 fn print_item(cx: &LateContext<'_>, item: &hir::Item<'_>) {
376     let did = item.def_id;
377     println!("item `{}`", item.ident.name);
378     match item.vis.node {
379         hir::VisibilityKind::Public => println!("public"),
380         hir::VisibilityKind::Crate(_) => println!("visible crate wide"),
381         hir::VisibilityKind::Restricted { ref path, .. } => println!(
382             "visible in module `{}`",
383             rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_path(path, false))
384         ),
385         hir::VisibilityKind::Inherited => println!("visibility inherited from outer item"),
386     }
387     match item.kind {
388         hir::ItemKind::ExternCrate(ref _renamed_from) => {
389             if let Some(crate_id) = cx.tcx.extern_mod_stmt_cnum(did) {
390                 let source = cx.tcx.used_crate_source(crate_id);
391                 if let Some(ref src) = source.dylib {
392                     println!("extern crate dylib source: {:?}", src.0);
393                 }
394                 if let Some(ref src) = source.rlib {
395                     println!("extern crate rlib source: {:?}", src.0);
396                 }
397             } else {
398                 println!("weird extern crate without a crate id");
399             }
400         },
401         hir::ItemKind::Use(ref path, ref kind) => println!("{:?}, {:?}", path, kind),
402         hir::ItemKind::Static(..) => println!("static item of type {:#?}", cx.tcx.type_of(did)),
403         hir::ItemKind::Const(..) => println!("const item of type {:#?}", cx.tcx.type_of(did)),
404         hir::ItemKind::Fn(..) => {
405             let item_ty = cx.tcx.type_of(did);
406             println!("function of type {:#?}", item_ty);
407         },
408         hir::ItemKind::Mod(..) => println!("module"),
409         hir::ItemKind::ForeignMod { abi, .. } => println!("foreign module with abi: {}", abi),
410         hir::ItemKind::GlobalAsm(ref asm) => println!("global asm: {:?}", asm),
411         hir::ItemKind::TyAlias(..) => {
412             println!("type alias for {:?}", cx.tcx.type_of(did));
413         },
414         hir::ItemKind::OpaqueTy(..) => {
415             println!("existential type with real type {:?}", cx.tcx.type_of(did));
416         },
417         hir::ItemKind::Enum(..) => {
418             println!("enum definition of type {:?}", cx.tcx.type_of(did));
419         },
420         hir::ItemKind::Struct(..) => {
421             println!("struct definition of type {:?}", cx.tcx.type_of(did));
422         },
423         hir::ItemKind::Union(..) => {
424             println!("union definition of type {:?}", cx.tcx.type_of(did));
425         },
426         hir::ItemKind::Trait(..) => {
427             println!("trait decl");
428             if cx.tcx.trait_is_auto(did.to_def_id()) {
429                 println!("trait is auto");
430             } else {
431                 println!("trait is not auto");
432             }
433         },
434         hir::ItemKind::TraitAlias(..) => {
435             println!("trait alias");
436         },
437         hir::ItemKind::Impl(hir::Impl {
438             of_trait: Some(ref _trait_ref),
439             ..
440         }) => {
441             println!("trait impl");
442         },
443         hir::ItemKind::Impl(hir::Impl { of_trait: None, .. }) => {
444             println!("impl");
445         },
446     }
447 }
448
449 #[allow(clippy::similar_names)]
450 #[allow(clippy::too_many_lines)]
451 fn print_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, indent: usize) {
452     let ind = "  ".repeat(indent);
453     println!("{}+", ind);
454     match pat.kind {
455         hir::PatKind::Wild => println!("{}Wild", ind),
456         hir::PatKind::Binding(ref mode, .., ident, ref inner) => {
457             println!("{}Binding", ind);
458             println!("{}mode: {:?}", ind, mode);
459             println!("{}name: {}", ind, ident.name);
460             if let Some(ref inner) = *inner {
461                 println!("{}inner:", ind);
462                 print_pat(cx, inner, indent + 1);
463             }
464         },
465         hir::PatKind::Or(fields) => {
466             println!("{}Or", ind);
467             for field in fields {
468                 print_pat(cx, field, indent + 1);
469             }
470         },
471         hir::PatKind::Struct(ref path, fields, ignore) => {
472             println!("{}Struct", ind);
473             println!(
474                 "{}name: {}",
475                 ind,
476                 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
477             );
478             println!("{}ignore leftover fields: {}", ind, ignore);
479             println!("{}fields:", ind);
480             for field in fields {
481                 println!("{}  field name: {}", ind, field.ident.name);
482                 if field.is_shorthand {
483                     println!("{}  in shorthand notation", ind);
484                 }
485                 print_pat(cx, &field.pat, indent + 1);
486             }
487         },
488         hir::PatKind::TupleStruct(ref path, fields, opt_dots_position) => {
489             println!("{}TupleStruct", ind);
490             println!(
491                 "{}path: {}",
492                 ind,
493                 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
494             );
495             if let Some(dot_position) = opt_dots_position {
496                 println!("{}dot position: {}", ind, dot_position);
497             }
498             for field in fields {
499                 print_pat(cx, field, indent + 1);
500             }
501         },
502         hir::PatKind::Path(hir::QPath::Resolved(ref ty, ref path)) => {
503             println!("{}Resolved Path, {:?}", ind, ty);
504             println!("{}path: {:?}", ind, path);
505         },
506         hir::PatKind::Path(hir::QPath::TypeRelative(ref ty, ref seg)) => {
507             println!("{}Relative Path, {:?}", ind, ty);
508             println!("{}seg: {:?}", ind, seg);
509         },
510         hir::PatKind::Path(hir::QPath::LangItem(lang_item, ..)) => {
511             println!("{}Lang Item Path, {:?}", ind, lang_item.name());
512         },
513         hir::PatKind::Tuple(pats, opt_dots_position) => {
514             println!("{}Tuple", ind);
515             if let Some(dot_position) = opt_dots_position {
516                 println!("{}dot position: {}", ind, dot_position);
517             }
518             for field in pats {
519                 print_pat(cx, field, indent + 1);
520             }
521         },
522         hir::PatKind::Box(ref inner) => {
523             println!("{}Box", ind);
524             print_pat(cx, inner, indent + 1);
525         },
526         hir::PatKind::Ref(ref inner, ref muta) => {
527             println!("{}Ref", ind);
528             println!("{}mutability: {:?}", ind, muta);
529             print_pat(cx, inner, indent + 1);
530         },
531         hir::PatKind::Lit(ref e) => {
532             println!("{}Lit", ind);
533             print_expr(cx, e, indent + 1);
534         },
535         hir::PatKind::Range(ref l, ref r, ref range_end) => {
536             println!("{}Range", ind);
537             if let Some(expr) = l {
538                 print_expr(cx, expr, indent + 1);
539             }
540             if let Some(expr) = r {
541                 print_expr(cx, expr, indent + 1);
542             }
543             match *range_end {
544                 hir::RangeEnd::Included => println!("{} end included", ind),
545                 hir::RangeEnd::Excluded => println!("{} end excluded", ind),
546             }
547         },
548         hir::PatKind::Slice(first_pats, ref range, last_pats) => {
549             println!("{}Slice [a, b, ..i, y, z]", ind);
550             println!("[a, b]:");
551             for pat in first_pats {
552                 print_pat(cx, pat, indent + 1);
553             }
554             println!("i:");
555             if let Some(ref pat) = *range {
556                 print_pat(cx, pat, indent + 1);
557             }
558             println!("[y, z]:");
559             for pat in last_pats {
560                 print_pat(cx, pat, indent + 1);
561             }
562         },
563     }
564 }
565
566 fn print_guard(cx: &LateContext<'_>, guard: &hir::Guard<'_>, indent: usize) {
567     let ind = "  ".repeat(indent);
568     println!("{}+", ind);
569     match guard {
570         hir::Guard::If(expr) => {
571             println!("{}If", ind);
572             print_expr(cx, expr, indent + 1);
573         },
574         hir::Guard::IfLet(pat, expr) => {
575             println!("{}IfLet", ind);
576             print_pat(cx, pat, indent + 1);
577             print_expr(cx, expr, indent + 1);
578         },
579     }
580 }