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