]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/utils/inspector.rs
Rollup merge of #81588 - xfix:delete-doc-alias, r=Mark-Simulacrum
[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::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::Const { expr }
310                     | hir::InlineAsmOperand::Sym { expr } => print_expr(cx, expr, indent + 1),
311                     hir::InlineAsmOperand::Out { expr, .. } => {
312                         if let Some(expr) = expr {
313                             print_expr(cx, expr, indent + 1);
314                         }
315                     },
316                     hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
317                         print_expr(cx, in_expr, indent + 1);
318                         if let Some(out_expr) = out_expr {
319                             print_expr(cx, out_expr, indent + 1);
320                         }
321                     },
322                 }
323             }
324         },
325         hir::ExprKind::LlvmInlineAsm(ref asm) => {
326             let inputs = &asm.inputs_exprs;
327             let outputs = &asm.outputs_exprs;
328             println!("{}LlvmInlineAsm", ind);
329             println!("{}inputs:", ind);
330             for e in inputs.iter() {
331                 print_expr(cx, e, indent + 1);
332             }
333             println!("{}outputs:", ind);
334             for e in outputs.iter() {
335                 print_expr(cx, e, indent + 1);
336             }
337         },
338         hir::ExprKind::Struct(ref path, fields, ref base) => {
339             println!("{}Struct", ind);
340             println!("{}path: {:?}", ind, path);
341             for field in fields {
342                 println!("{}field \"{}\":", ind, field.ident.name);
343                 print_expr(cx, &field.expr, indent + 1);
344             }
345             if let Some(ref base) = *base {
346                 println!("{}base:", ind);
347                 print_expr(cx, base, indent + 1);
348             }
349         },
350         hir::ExprKind::ConstBlock(ref anon_const) => {
351             println!("{}ConstBlock", ind);
352             println!("{}anon_const:", ind);
353             print_expr(cx, &cx.tcx.hir().body(anon_const.body).value, indent + 1);
354         },
355         hir::ExprKind::Repeat(ref val, ref anon_const) => {
356             println!("{}Repeat", ind);
357             println!("{}value:", ind);
358             print_expr(cx, val, indent + 1);
359             println!("{}repeat count:", ind);
360             print_expr(cx, &cx.tcx.hir().body(anon_const.body).value, indent + 1);
361         },
362         hir::ExprKind::Err => {
363             println!("{}Err", ind);
364         },
365         hir::ExprKind::DropTemps(ref e) => {
366             println!("{}DropTemps", ind);
367             print_expr(cx, e, indent + 1);
368         },
369     }
370 }
371
372 fn print_item(cx: &LateContext<'_>, item: &hir::Item<'_>) {
373     let did = cx.tcx.hir().local_def_id(item.hir_id);
374     println!("item `{}`", item.ident.name);
375     match item.vis.node {
376         hir::VisibilityKind::Public => println!("public"),
377         hir::VisibilityKind::Crate(_) => println!("visible crate wide"),
378         hir::VisibilityKind::Restricted { ref path, .. } => println!(
379             "visible in module `{}`",
380             rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_path(path, false))
381         ),
382         hir::VisibilityKind::Inherited => println!("visibility inherited from outer item"),
383     }
384     match item.kind {
385         hir::ItemKind::ExternCrate(ref _renamed_from) => {
386             let def_id = cx.tcx.hir().local_def_id(item.hir_id);
387             if let Some(crate_id) = cx.tcx.extern_mod_stmt_cnum(def_id) {
388                 let source = cx.tcx.used_crate_source(crate_id);
389                 if let Some(ref src) = source.dylib {
390                     println!("extern crate dylib source: {:?}", src.0);
391                 }
392                 if let Some(ref src) = source.rlib {
393                     println!("extern crate rlib source: {:?}", src.0);
394                 }
395             } else {
396                 println!("weird extern crate without a crate id");
397             }
398         },
399         hir::ItemKind::Use(ref path, ref kind) => println!("{:?}, {:?}", path, kind),
400         hir::ItemKind::Static(..) => println!("static item of type {:#?}", cx.tcx.type_of(did)),
401         hir::ItemKind::Const(..) => println!("const item of type {:#?}", cx.tcx.type_of(did)),
402         hir::ItemKind::Fn(..) => {
403             let item_ty = cx.tcx.type_of(did);
404             println!("function of type {:#?}", item_ty);
405         },
406         hir::ItemKind::Mod(..) => println!("module"),
407         hir::ItemKind::ForeignMod { abi, .. } => println!("foreign module with abi: {}", abi),
408         hir::ItemKind::GlobalAsm(ref asm) => println!("global asm: {:?}", asm),
409         hir::ItemKind::TyAlias(..) => {
410             println!("type alias for {:?}", cx.tcx.type_of(did));
411         },
412         hir::ItemKind::OpaqueTy(..) => {
413             println!("existential type with real type {:?}", cx.tcx.type_of(did));
414         },
415         hir::ItemKind::Enum(..) => {
416             println!("enum definition of type {:?}", cx.tcx.type_of(did));
417         },
418         hir::ItemKind::Struct(..) => {
419             println!("struct definition of type {:?}", cx.tcx.type_of(did));
420         },
421         hir::ItemKind::Union(..) => {
422             println!("union definition of type {:?}", cx.tcx.type_of(did));
423         },
424         hir::ItemKind::Trait(..) => {
425             println!("trait decl");
426             if cx.tcx.trait_is_auto(did.to_def_id()) {
427                 println!("trait is auto");
428             } else {
429                 println!("trait is not auto");
430             }
431         },
432         hir::ItemKind::TraitAlias(..) => {
433             println!("trait alias");
434         },
435         hir::ItemKind::Impl(hir::Impl {
436             of_trait: Some(ref _trait_ref),
437             ..
438         }) => {
439             println!("trait impl");
440         },
441         hir::ItemKind::Impl(hir::Impl { of_trait: None, .. }) => {
442             println!("impl");
443         },
444     }
445 }
446
447 #[allow(clippy::similar_names)]
448 #[allow(clippy::too_many_lines)]
449 fn print_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, indent: usize) {
450     let ind = "  ".repeat(indent);
451     println!("{}+", ind);
452     match pat.kind {
453         hir::PatKind::Wild => println!("{}Wild", ind),
454         hir::PatKind::Binding(ref mode, .., ident, ref inner) => {
455             println!("{}Binding", ind);
456             println!("{}mode: {:?}", ind, mode);
457             println!("{}name: {}", ind, ident.name);
458             if let Some(ref inner) = *inner {
459                 println!("{}inner:", ind);
460                 print_pat(cx, inner, indent + 1);
461             }
462         },
463         hir::PatKind::Or(fields) => {
464             println!("{}Or", ind);
465             for field in fields {
466                 print_pat(cx, field, indent + 1);
467             }
468         },
469         hir::PatKind::Struct(ref path, fields, ignore) => {
470             println!("{}Struct", ind);
471             println!(
472                 "{}name: {}",
473                 ind,
474                 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
475             );
476             println!("{}ignore leftover fields: {}", ind, ignore);
477             println!("{}fields:", ind);
478             for field in fields {
479                 println!("{}  field name: {}", ind, field.ident.name);
480                 if field.is_shorthand {
481                     println!("{}  in shorthand notation", ind);
482                 }
483                 print_pat(cx, &field.pat, indent + 1);
484             }
485         },
486         hir::PatKind::TupleStruct(ref path, fields, opt_dots_position) => {
487             println!("{}TupleStruct", ind);
488             println!(
489                 "{}path: {}",
490                 ind,
491                 rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false))
492             );
493             if let Some(dot_position) = opt_dots_position {
494                 println!("{}dot position: {}", ind, dot_position);
495             }
496             for field in fields {
497                 print_pat(cx, field, indent + 1);
498             }
499         },
500         hir::PatKind::Path(hir::QPath::Resolved(ref ty, ref path)) => {
501             println!("{}Resolved Path, {:?}", ind, ty);
502             println!("{}path: {:?}", ind, path);
503         },
504         hir::PatKind::Path(hir::QPath::TypeRelative(ref ty, ref seg)) => {
505             println!("{}Relative Path, {:?}", ind, ty);
506             println!("{}seg: {:?}", ind, seg);
507         },
508         hir::PatKind::Path(hir::QPath::LangItem(lang_item, ..)) => {
509             println!("{}Lang Item Path, {:?}", ind, lang_item.name());
510         },
511         hir::PatKind::Tuple(pats, opt_dots_position) => {
512             println!("{}Tuple", ind);
513             if let Some(dot_position) = opt_dots_position {
514                 println!("{}dot position: {}", ind, dot_position);
515             }
516             for field in pats {
517                 print_pat(cx, field, indent + 1);
518             }
519         },
520         hir::PatKind::Box(ref inner) => {
521             println!("{}Box", ind);
522             print_pat(cx, inner, indent + 1);
523         },
524         hir::PatKind::Ref(ref inner, ref muta) => {
525             println!("{}Ref", ind);
526             println!("{}mutability: {:?}", ind, muta);
527             print_pat(cx, inner, indent + 1);
528         },
529         hir::PatKind::Lit(ref e) => {
530             println!("{}Lit", ind);
531             print_expr(cx, e, indent + 1);
532         },
533         hir::PatKind::Range(ref l, ref r, ref range_end) => {
534             println!("{}Range", ind);
535             if let Some(expr) = l {
536                 print_expr(cx, expr, indent + 1);
537             }
538             if let Some(expr) = r {
539                 print_expr(cx, expr, indent + 1);
540             }
541             match *range_end {
542                 hir::RangeEnd::Included => println!("{} end included", ind),
543                 hir::RangeEnd::Excluded => println!("{} end excluded", ind),
544             }
545         },
546         hir::PatKind::Slice(first_pats, ref range, last_pats) => {
547             println!("{}Slice [a, b, ..i, y, z]", ind);
548             println!("[a, b]:");
549             for pat in first_pats {
550                 print_pat(cx, pat, indent + 1);
551             }
552             println!("i:");
553             if let Some(ref pat) = *range {
554                 print_pat(cx, pat, indent + 1);
555             }
556             println!("[y, z]:");
557             for pat in last_pats {
558                 print_pat(cx, pat, indent + 1);
559             }
560         },
561     }
562 }
563
564 fn print_guard(cx: &LateContext<'_>, guard: &hir::Guard<'_>, indent: usize) {
565     let ind = "  ".repeat(indent);
566     println!("{}+", ind);
567     match guard {
568         hir::Guard::If(expr) => {
569             println!("{}If", ind);
570             print_expr(cx, expr, indent + 1);
571         },
572         hir::Guard::IfLet(pat, expr) => {
573             println!("{}IfLet", ind);
574             print_pat(cx, pat, indent + 1);
575             print_expr(cx, expr, indent + 1);
576         },
577     }
578 }