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