]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/utils/author.rs
Rollup merge of #71591 - hermitcore:thread_create, r=hanna-kruppe
[rust.git] / src / tools / clippy / clippy_lints / src / utils / author.rs
1 //! A group of attributes that can be attached to Rust code in order
2 //! to generate a clippy lint detecting said code automatically.
3
4 use crate::utils::{get_attr, higher};
5 use rustc_ast::ast::{Attribute, LitFloatType, LitKind};
6 use rustc_ast::walk_list;
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_hir as hir;
9 use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
10 use rustc_hir::{BindingAnnotation, Block, Expr, ExprKind, Pat, PatKind, QPath, Stmt, StmtKind, TyKind};
11 use rustc_lint::{LateContext, LateLintPass, LintContext};
12 use rustc_middle::hir::map::Map;
13 use rustc_session::Session;
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
15
16 declare_clippy_lint! {
17     /// **What it does:** Generates clippy code that detects the offending pattern
18     ///
19     /// **Example:**
20     /// ```rust,ignore
21     /// // ./tests/ui/my_lint.rs
22     /// fn foo() {
23     ///     // detect the following pattern
24     ///     #[clippy::author]
25     ///     if x == 42 {
26     ///         // but ignore everything from here on
27     ///         #![clippy::author = "ignore"]
28     ///     }
29     ///     ()
30     /// }
31     /// ```
32     ///
33     /// Running `TESTNAME=ui/my_lint cargo uitest` will produce
34     /// a `./tests/ui/new_lint.stdout` file with the generated code:
35     ///
36     /// ```rust,ignore
37     /// // ./tests/ui/new_lint.stdout
38     /// if_chain! {
39     ///     if let ExprKind::If(ref cond, ref then, None) = item.kind,
40     ///     if let ExprKind::Binary(BinOp::Eq, ref left, ref right) = cond.kind,
41     ///     if let ExprKind::Path(ref path) = left.kind,
42     ///     if let ExprKind::Lit(ref lit) = right.kind,
43     ///     if let LitKind::Int(42, _) = lit.node,
44     ///     then {
45     ///         // report your lint here
46     ///     }
47     /// }
48     /// ```
49     pub LINT_AUTHOR,
50     internal_warn,
51     "helper for writing lints"
52 }
53
54 declare_lint_pass!(Author => [LINT_AUTHOR]);
55
56 fn prelude() {
57     println!("if_chain! {{");
58 }
59
60 fn done() {
61     println!("    then {{");
62     println!("        // report your lint here");
63     println!("    }}");
64     println!("}}");
65 }
66
67 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Author {
68     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
69         if !has_attr(cx.sess(), &item.attrs) {
70             return;
71         }
72         prelude();
73         PrintVisitor::new("item").visit_item(item);
74         done();
75     }
76
77     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem<'_>) {
78         if !has_attr(cx.sess(), &item.attrs) {
79             return;
80         }
81         prelude();
82         PrintVisitor::new("item").visit_impl_item(item);
83         done();
84     }
85
86     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem<'_>) {
87         if !has_attr(cx.sess(), &item.attrs) {
88             return;
89         }
90         prelude();
91         PrintVisitor::new("item").visit_trait_item(item);
92         done();
93     }
94
95     fn check_variant(&mut self, cx: &LateContext<'a, 'tcx>, var: &'tcx hir::Variant<'_>) {
96         if !has_attr(cx.sess(), &var.attrs) {
97             return;
98         }
99         prelude();
100         let parent_hir_id = cx.tcx.hir().get_parent_node(var.id);
101         PrintVisitor::new("var").visit_variant(var, &hir::Generics::empty(), parent_hir_id);
102         done();
103     }
104
105     fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField<'_>) {
106         if !has_attr(cx.sess(), &field.attrs) {
107             return;
108         }
109         prelude();
110         PrintVisitor::new("field").visit_struct_field(field);
111         done();
112     }
113
114     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>) {
115         if !has_attr(cx.sess(), &expr.attrs) {
116             return;
117         }
118         prelude();
119         PrintVisitor::new("expr").visit_expr(expr);
120         done();
121     }
122
123     fn check_arm(&mut self, cx: &LateContext<'a, 'tcx>, arm: &'tcx hir::Arm<'_>) {
124         if !has_attr(cx.sess(), &arm.attrs) {
125             return;
126         }
127         prelude();
128         PrintVisitor::new("arm").visit_arm(arm);
129         done();
130     }
131
132     fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx hir::Stmt<'_>) {
133         if !has_attr(cx.sess(), stmt.kind.attrs()) {
134             return;
135         }
136         prelude();
137         PrintVisitor::new("stmt").visit_stmt(stmt);
138         done();
139     }
140
141     fn check_foreign_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ForeignItem<'_>) {
142         if !has_attr(cx.sess(), &item.attrs) {
143             return;
144         }
145         prelude();
146         PrintVisitor::new("item").visit_foreign_item(item);
147         done();
148     }
149 }
150
151 impl PrintVisitor {
152     #[must_use]
153     fn new(s: &'static str) -> Self {
154         Self {
155             ids: FxHashMap::default(),
156             current: s.to_owned(),
157         }
158     }
159
160     fn next(&mut self, s: &'static str) -> String {
161         use std::collections::hash_map::Entry::{Occupied, Vacant};
162         match self.ids.entry(s) {
163             // already there: start numbering from `1`
164             Occupied(mut occ) => {
165                 let val = occ.get_mut();
166                 *val += 1;
167                 format!("{}{}", s, *val)
168             },
169             // not there: insert and return name as given
170             Vacant(vac) => {
171                 vac.insert(0);
172                 s.to_owned()
173             },
174         }
175     }
176
177     fn print_qpath(&mut self, path: &QPath<'_>) {
178         print!("    if match_qpath({}, &[", self.current);
179         print_path(path, &mut true);
180         println!("]);");
181     }
182 }
183
184 struct PrintVisitor {
185     /// Fields are the current index that needs to be appended to pattern
186     /// binding names
187     ids: FxHashMap<&'static str, usize>,
188     /// the name that needs to be destructured
189     current: String,
190 }
191
192 impl<'tcx> Visitor<'tcx> for PrintVisitor {
193     type Map = Map<'tcx>;
194
195     #[allow(clippy::too_many_lines)]
196     fn visit_expr(&mut self, expr: &Expr<'_>) {
197         // handle if desugarings
198         // TODO add more desugarings here
199         if let Some((cond, then, opt_else)) = higher::if_block(&expr) {
200             let cond_pat = self.next("cond");
201             let then_pat = self.next("then");
202             if let Some(else_) = opt_else {
203                 let else_pat = self.next("else_");
204                 println!(
205                     "    if let Some((ref {}, ref {}, Some({}))) = higher::if_block(&{});",
206                     cond_pat, then_pat, else_pat, self.current
207                 );
208                 self.current = else_pat;
209                 self.visit_expr(else_);
210             } else {
211                 println!(
212                     "    if let Some((ref {}, ref {}, None)) = higher::if_block(&{});",
213                     cond_pat, then_pat, self.current
214                 );
215             }
216             self.current = cond_pat;
217             self.visit_expr(cond);
218             self.current = then_pat;
219             self.visit_expr(then);
220             return;
221         }
222
223         print!("    if let ExprKind::");
224         let current = format!("{}.kind", self.current);
225         match expr.kind {
226             ExprKind::Box(ref inner) => {
227                 let inner_pat = self.next("inner");
228                 println!("Box(ref {}) = {};", inner_pat, current);
229                 self.current = inner_pat;
230                 self.visit_expr(inner);
231             },
232             ExprKind::Array(ref elements) => {
233                 let elements_pat = self.next("elements");
234                 println!("Array(ref {}) = {};", elements_pat, current);
235                 println!("    if {}.len() == {};", elements_pat, elements.len());
236                 for (i, element) in elements.iter().enumerate() {
237                     self.current = format!("{}[{}]", elements_pat, i);
238                     self.visit_expr(element);
239                 }
240             },
241             ExprKind::Call(ref func, ref args) => {
242                 let func_pat = self.next("func");
243                 let args_pat = self.next("args");
244                 println!("Call(ref {}, ref {}) = {};", func_pat, args_pat, current);
245                 self.current = func_pat;
246                 self.visit_expr(func);
247                 println!("    if {}.len() == {};", args_pat, args.len());
248                 for (i, arg) in args.iter().enumerate() {
249                     self.current = format!("{}[{}]", args_pat, i);
250                     self.visit_expr(arg);
251                 }
252             },
253             ExprKind::MethodCall(ref _method_name, ref _generics, ref _args) => {
254                 println!("MethodCall(ref method_name, ref generics, ref args) = {};", current);
255                 println!("    // unimplemented: `ExprKind::MethodCall` is not further destructured at the moment");
256             },
257             ExprKind::Tup(ref elements) => {
258                 let elements_pat = self.next("elements");
259                 println!("Tup(ref {}) = {};", elements_pat, current);
260                 println!("    if {}.len() == {};", elements_pat, elements.len());
261                 for (i, element) in elements.iter().enumerate() {
262                     self.current = format!("{}[{}]", elements_pat, i);
263                     self.visit_expr(element);
264                 }
265             },
266             ExprKind::Binary(ref op, ref left, ref right) => {
267                 let op_pat = self.next("op");
268                 let left_pat = self.next("left");
269                 let right_pat = self.next("right");
270                 println!(
271                     "Binary(ref {}, ref {}, ref {}) = {};",
272                     op_pat, left_pat, right_pat, current
273                 );
274                 println!("    if BinOpKind::{:?} == {}.node;", op.node, op_pat);
275                 self.current = left_pat;
276                 self.visit_expr(left);
277                 self.current = right_pat;
278                 self.visit_expr(right);
279             },
280             ExprKind::Unary(ref op, ref inner) => {
281                 let inner_pat = self.next("inner");
282                 println!("Unary(UnOp::{:?}, ref {}) = {};", op, inner_pat, current);
283                 self.current = inner_pat;
284                 self.visit_expr(inner);
285             },
286             ExprKind::Lit(ref lit) => {
287                 let lit_pat = self.next("lit");
288                 println!("Lit(ref {}) = {};", lit_pat, current);
289                 match lit.node {
290                     LitKind::Bool(val) => println!("    if let LitKind::Bool({:?}) = {}.node;", val, lit_pat),
291                     LitKind::Char(c) => println!("    if let LitKind::Char({:?}) = {}.node;", c, lit_pat),
292                     LitKind::Err(val) => println!("    if let LitKind::Err({}) = {}.node;", val, lit_pat),
293                     LitKind::Byte(b) => println!("    if let LitKind::Byte({}) = {}.node;", b, lit_pat),
294                     // FIXME: also check int type
295                     LitKind::Int(i, _) => println!("    if let LitKind::Int({}, _) = {}.node;", i, lit_pat),
296                     LitKind::Float(_, LitFloatType::Suffixed(_)) => println!(
297                         "    if let LitKind::Float(_, LitFloatType::Suffixed(_)) = {}.node;",
298                         lit_pat
299                     ),
300                     LitKind::Float(_, LitFloatType::Unsuffixed) => println!(
301                         "    if let LitKind::Float(_, LitFloatType::Unsuffixed) = {}.node;",
302                         lit_pat
303                     ),
304                     LitKind::ByteStr(ref vec) => {
305                         let vec_pat = self.next("vec");
306                         println!("    if let LitKind::ByteStr(ref {}) = {}.node;", vec_pat, lit_pat);
307                         println!("    if let [{:?}] = **{};", vec, vec_pat);
308                     },
309                     LitKind::Str(ref text, _) => {
310                         let str_pat = self.next("s");
311                         println!("    if let LitKind::Str(ref {}, _) = {}.node;", str_pat, lit_pat);
312                         println!("    if {}.as_str() == {:?}", str_pat, &*text.as_str())
313                     },
314                 }
315             },
316             ExprKind::Cast(ref expr, ref ty) => {
317                 let cast_pat = self.next("expr");
318                 let cast_ty = self.next("cast_ty");
319                 let qp_label = self.next("qp");
320
321                 println!("Cast(ref {}, ref {}) = {};", cast_pat, cast_ty, current);
322                 if let TyKind::Path(ref qp) = ty.kind {
323                     println!("    if let TyKind::Path(ref {}) = {}.kind;", qp_label, cast_ty);
324                     self.current = qp_label;
325                     self.print_qpath(qp);
326                 }
327                 self.current = cast_pat;
328                 self.visit_expr(expr);
329             },
330             ExprKind::Type(ref expr, ref _ty) => {
331                 let cast_pat = self.next("expr");
332                 println!("Type(ref {}, _) = {};", cast_pat, current);
333                 self.current = cast_pat;
334                 self.visit_expr(expr);
335             },
336             ExprKind::Loop(ref body, _, desugaring) => {
337                 let body_pat = self.next("body");
338                 let des = loop_desugaring_name(desugaring);
339                 let label_pat = self.next("label");
340                 println!("Loop(ref {}, ref {}, {}) = {};", body_pat, label_pat, des, current);
341                 self.current = body_pat;
342                 self.visit_block(body);
343             },
344             ExprKind::Match(ref expr, ref arms, desugaring) => {
345                 let des = desugaring_name(desugaring);
346                 let expr_pat = self.next("expr");
347                 let arms_pat = self.next("arms");
348                 println!("Match(ref {}, ref {}, {}) = {};", expr_pat, arms_pat, des, current);
349                 self.current = expr_pat;
350                 self.visit_expr(expr);
351                 println!("    if {}.len() == {};", arms_pat, arms.len());
352                 for (i, arm) in arms.iter().enumerate() {
353                     self.current = format!("{}[{}].body", arms_pat, i);
354                     self.visit_expr(&arm.body);
355                     if let Some(ref guard) = arm.guard {
356                         let guard_pat = self.next("guard");
357                         println!("    if let Some(ref {}) = {}[{}].guard;", guard_pat, arms_pat, i);
358                         match guard {
359                             hir::Guard::If(ref if_expr) => {
360                                 let if_expr_pat = self.next("expr");
361                                 println!("    if let Guard::If(ref {}) = {};", if_expr_pat, guard_pat);
362                                 self.current = if_expr_pat;
363                                 self.visit_expr(if_expr);
364                             },
365                         }
366                     }
367                     self.current = format!("{}[{}].pat", arms_pat, i);
368                     self.visit_pat(&arm.pat);
369                 }
370             },
371             ExprKind::Closure(ref _capture_clause, ref _func, _, _, _) => {
372                 println!("Closure(ref capture_clause, ref func, _, _, _) = {};", current);
373                 println!("    // unimplemented: `ExprKind::Closure` is not further destructured at the moment");
374             },
375             ExprKind::Yield(ref sub, _) => {
376                 let sub_pat = self.next("sub");
377                 println!("Yield(ref sub) = {};", current);
378                 self.current = sub_pat;
379                 self.visit_expr(sub);
380             },
381             ExprKind::Block(ref block, _) => {
382                 let block_pat = self.next("block");
383                 println!("Block(ref {}) = {};", block_pat, current);
384                 self.current = block_pat;
385                 self.visit_block(block);
386             },
387             ExprKind::Assign(ref target, ref value, _) => {
388                 let target_pat = self.next("target");
389                 let value_pat = self.next("value");
390                 println!(
391                     "Assign(ref {}, ref {}, ref _span) = {};",
392                     target_pat, value_pat, current
393                 );
394                 self.current = target_pat;
395                 self.visit_expr(target);
396                 self.current = value_pat;
397                 self.visit_expr(value);
398             },
399             ExprKind::AssignOp(ref op, ref target, ref value) => {
400                 let op_pat = self.next("op");
401                 let target_pat = self.next("target");
402                 let value_pat = self.next("value");
403                 println!(
404                     "AssignOp(ref {}, ref {}, ref {}) = {};",
405                     op_pat, target_pat, value_pat, current
406                 );
407                 println!("    if BinOpKind::{:?} == {}.node;", op.node, op_pat);
408                 self.current = target_pat;
409                 self.visit_expr(target);
410                 self.current = value_pat;
411                 self.visit_expr(value);
412             },
413             ExprKind::Field(ref object, ref field_ident) => {
414                 let obj_pat = self.next("object");
415                 let field_name_pat = self.next("field_name");
416                 println!("Field(ref {}, ref {}) = {};", obj_pat, field_name_pat, current);
417                 println!("    if {}.as_str() == {:?}", field_name_pat, field_ident.as_str());
418                 self.current = obj_pat;
419                 self.visit_expr(object);
420             },
421             ExprKind::Index(ref object, ref index) => {
422                 let object_pat = self.next("object");
423                 let index_pat = self.next("index");
424                 println!("Index(ref {}, ref {}) = {};", object_pat, index_pat, current);
425                 self.current = object_pat;
426                 self.visit_expr(object);
427                 self.current = index_pat;
428                 self.visit_expr(index);
429             },
430             ExprKind::Path(ref path) => {
431                 let path_pat = self.next("path");
432                 println!("Path(ref {}) = {};", path_pat, current);
433                 self.current = path_pat;
434                 self.print_qpath(path);
435             },
436             ExprKind::AddrOf(kind, mutability, ref inner) => {
437                 let inner_pat = self.next("inner");
438                 println!(
439                     "AddrOf(BorrowKind::{:?}, Mutability::{:?}, ref {}) = {};",
440                     kind, mutability, inner_pat, current
441                 );
442                 self.current = inner_pat;
443                 self.visit_expr(inner);
444             },
445             ExprKind::Break(ref _destination, ref opt_value) => {
446                 let destination_pat = self.next("destination");
447                 if let Some(ref value) = *opt_value {
448                     let value_pat = self.next("value");
449                     println!("Break(ref {}, Some(ref {})) = {};", destination_pat, value_pat, current);
450                     self.current = value_pat;
451                     self.visit_expr(value);
452                 } else {
453                     println!("Break(ref {}, None) = {};", destination_pat, current);
454                 }
455                 // FIXME: implement label printing
456             },
457             ExprKind::Continue(ref _destination) => {
458                 let destination_pat = self.next("destination");
459                 println!("Again(ref {}) = {};", destination_pat, current);
460                 // FIXME: implement label printing
461             },
462             ExprKind::Ret(ref opt_value) => {
463                 if let Some(ref value) = *opt_value {
464                     let value_pat = self.next("value");
465                     println!("Ret(Some(ref {})) = {};", value_pat, current);
466                     self.current = value_pat;
467                     self.visit_expr(value);
468                 } else {
469                     println!("Ret(None) = {};", current);
470                 }
471             },
472             ExprKind::LlvmInlineAsm(_) => {
473                 println!("LlvmInlineAsm(_) = {};", current);
474                 println!("    // unimplemented: `ExprKind::LlvmInlineAsm` is not further destructured at the moment");
475             },
476             ExprKind::Struct(ref path, ref fields, ref opt_base) => {
477                 let path_pat = self.next("path");
478                 let fields_pat = self.next("fields");
479                 if let Some(ref base) = *opt_base {
480                     let base_pat = self.next("base");
481                     println!(
482                         "Struct(ref {}, ref {}, Some(ref {})) = {};",
483                         path_pat, fields_pat, base_pat, current
484                     );
485                     self.current = base_pat;
486                     self.visit_expr(base);
487                 } else {
488                     println!("Struct(ref {}, ref {}, None) = {};", path_pat, fields_pat, current);
489                 }
490                 self.current = path_pat;
491                 self.print_qpath(path);
492                 println!("    if {}.len() == {};", fields_pat, fields.len());
493                 println!("    // unimplemented: field checks");
494             },
495             // FIXME: compute length (needs type info)
496             ExprKind::Repeat(ref value, _) => {
497                 let value_pat = self.next("value");
498                 println!("Repeat(ref {}, _) = {};", value_pat, current);
499                 println!("// unimplemented: repeat count check");
500                 self.current = value_pat;
501                 self.visit_expr(value);
502             },
503             ExprKind::Err => {
504                 println!("Err = {}", current);
505             },
506             ExprKind::DropTemps(ref expr) => {
507                 let expr_pat = self.next("expr");
508                 println!("DropTemps(ref {}) = {};", expr_pat, current);
509                 self.current = expr_pat;
510                 self.visit_expr(expr);
511             },
512         }
513     }
514
515     fn visit_block(&mut self, block: &Block<'_>) {
516         let trailing_pat = self.next("trailing_expr");
517         println!("    if let Some({}) = &{}.expr;", trailing_pat, self.current);
518         println!("    if {}.stmts.len() == {};", self.current, block.stmts.len());
519         let current = self.current.clone();
520         for (i, stmt) in block.stmts.iter().enumerate() {
521             self.current = format!("{}.stmts[{}]", current, i);
522             self.visit_stmt(stmt);
523         }
524     }
525
526     #[allow(clippy::too_many_lines)]
527     fn visit_pat(&mut self, pat: &Pat<'_>) {
528         print!("    if let PatKind::");
529         let current = format!("{}.kind", self.current);
530         match pat.kind {
531             PatKind::Wild => println!("Wild = {};", current),
532             PatKind::Binding(anno, .., ident, ref sub) => {
533                 let anno_pat = match anno {
534                     BindingAnnotation::Unannotated => "BindingAnnotation::Unannotated",
535                     BindingAnnotation::Mutable => "BindingAnnotation::Mutable",
536                     BindingAnnotation::Ref => "BindingAnnotation::Ref",
537                     BindingAnnotation::RefMut => "BindingAnnotation::RefMut",
538                 };
539                 let name_pat = self.next("name");
540                 if let Some(ref sub) = *sub {
541                     let sub_pat = self.next("sub");
542                     println!(
543                         "Binding({}, _, {}, Some(ref {})) = {};",
544                         anno_pat, name_pat, sub_pat, current
545                     );
546                     self.current = sub_pat;
547                     self.visit_pat(sub);
548                 } else {
549                     println!("Binding({}, _, {}, None) = {};", anno_pat, name_pat, current);
550                 }
551                 println!("    if {}.as_str() == \"{}\";", name_pat, ident.as_str());
552             },
553             PatKind::Struct(ref path, ref fields, ignore) => {
554                 let path_pat = self.next("path");
555                 let fields_pat = self.next("fields");
556                 println!(
557                     "Struct(ref {}, ref {}, {}) = {};",
558                     path_pat, fields_pat, ignore, current
559                 );
560                 self.current = path_pat;
561                 self.print_qpath(path);
562                 println!("    if {}.len() == {};", fields_pat, fields.len());
563                 println!("    // unimplemented: field checks");
564             },
565             PatKind::Or(ref fields) => {
566                 let fields_pat = self.next("fields");
567                 println!("Or(ref {}) = {};", fields_pat, current);
568                 println!("    if {}.len() == {};", fields_pat, fields.len());
569                 println!("    // unimplemented: field checks");
570             },
571             PatKind::TupleStruct(ref path, ref fields, skip_pos) => {
572                 let path_pat = self.next("path");
573                 let fields_pat = self.next("fields");
574                 println!(
575                     "TupleStruct(ref {}, ref {}, {:?}) = {};",
576                     path_pat, fields_pat, skip_pos, current
577                 );
578                 self.current = path_pat;
579                 self.print_qpath(path);
580                 println!("    if {}.len() == {};", fields_pat, fields.len());
581                 println!("    // unimplemented: field checks");
582             },
583             PatKind::Path(ref path) => {
584                 let path_pat = self.next("path");
585                 println!("Path(ref {}) = {};", path_pat, current);
586                 self.current = path_pat;
587                 self.print_qpath(path);
588             },
589             PatKind::Tuple(ref fields, skip_pos) => {
590                 let fields_pat = self.next("fields");
591                 println!("Tuple(ref {}, {:?}) = {};", fields_pat, skip_pos, current);
592                 println!("    if {}.len() == {};", fields_pat, fields.len());
593                 println!("    // unimplemented: field checks");
594             },
595             PatKind::Box(ref pat) => {
596                 let pat_pat = self.next("pat");
597                 println!("Box(ref {}) = {};", pat_pat, current);
598                 self.current = pat_pat;
599                 self.visit_pat(pat);
600             },
601             PatKind::Ref(ref pat, muta) => {
602                 let pat_pat = self.next("pat");
603                 println!("Ref(ref {}, Mutability::{:?}) = {};", pat_pat, muta, current);
604                 self.current = pat_pat;
605                 self.visit_pat(pat);
606             },
607             PatKind::Lit(ref lit_expr) => {
608                 let lit_expr_pat = self.next("lit_expr");
609                 println!("Lit(ref {}) = {}", lit_expr_pat, current);
610                 self.current = lit_expr_pat;
611                 self.visit_expr(lit_expr);
612             },
613             PatKind::Range(ref start, ref end, end_kind) => {
614                 let start_pat = self.next("start");
615                 let end_pat = self.next("end");
616                 println!(
617                     "Range(ref {}, ref {}, RangeEnd::{:?}) = {};",
618                     start_pat, end_pat, end_kind, current
619                 );
620                 self.current = start_pat;
621                 walk_list!(self, visit_expr, start);
622                 self.current = end_pat;
623                 walk_list!(self, visit_expr, end);
624             },
625             PatKind::Slice(ref start, ref middle, ref end) => {
626                 let start_pat = self.next("start");
627                 let end_pat = self.next("end");
628                 if let Some(ref middle) = middle {
629                     let middle_pat = self.next("middle");
630                     println!(
631                         "Slice(ref {}, Some(ref {}), ref {}) = {};",
632                         start_pat, middle_pat, end_pat, current
633                     );
634                     self.current = middle_pat;
635                     self.visit_pat(middle);
636                 } else {
637                     println!("Slice(ref {}, None, ref {}) = {};", start_pat, end_pat, current);
638                 }
639                 println!("    if {}.len() == {};", start_pat, start.len());
640                 for (i, pat) in start.iter().enumerate() {
641                     self.current = format!("{}[{}]", start_pat, i);
642                     self.visit_pat(pat);
643                 }
644                 println!("    if {}.len() == {};", end_pat, end.len());
645                 for (i, pat) in end.iter().enumerate() {
646                     self.current = format!("{}[{}]", end_pat, i);
647                     self.visit_pat(pat);
648                 }
649             },
650         }
651     }
652
653     fn visit_stmt(&mut self, s: &Stmt<'_>) {
654         print!("    if let StmtKind::");
655         let current = format!("{}.kind", self.current);
656         match s.kind {
657             // A local (let) binding:
658             StmtKind::Local(ref local) => {
659                 let local_pat = self.next("local");
660                 println!("Local(ref {}) = {};", local_pat, current);
661                 if let Some(ref init) = local.init {
662                     let init_pat = self.next("init");
663                     println!("    if let Some(ref {}) = {}.init;", init_pat, local_pat);
664                     self.current = init_pat;
665                     self.visit_expr(init);
666                 }
667                 self.current = format!("{}.pat", local_pat);
668                 self.visit_pat(&local.pat);
669             },
670             // An item binding:
671             StmtKind::Item(_) => {
672                 println!("Item(item_id) = {};", current);
673             },
674
675             // Expr without trailing semi-colon (must have unit type):
676             StmtKind::Expr(ref e) => {
677                 let e_pat = self.next("e");
678                 println!("Expr(ref {}, _) = {}", e_pat, current);
679                 self.current = e_pat;
680                 self.visit_expr(e);
681             },
682
683             // Expr with trailing semi-colon (may have any type):
684             StmtKind::Semi(ref e) => {
685                 let e_pat = self.next("e");
686                 println!("Semi(ref {}, _) = {}", e_pat, current);
687                 self.current = e_pat;
688                 self.visit_expr(e);
689             },
690         }
691     }
692
693     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
694         NestedVisitorMap::None
695     }
696 }
697
698 fn has_attr(sess: &Session, attrs: &[Attribute]) -> bool {
699     get_attr(sess, attrs, "author").count() > 0
700 }
701
702 #[must_use]
703 fn desugaring_name(des: hir::MatchSource) -> String {
704     match des {
705         hir::MatchSource::ForLoopDesugar => "MatchSource::ForLoopDesugar".to_string(),
706         hir::MatchSource::TryDesugar => "MatchSource::TryDesugar".to_string(),
707         hir::MatchSource::WhileDesugar => "MatchSource::WhileDesugar".to_string(),
708         hir::MatchSource::WhileLetDesugar => "MatchSource::WhileLetDesugar".to_string(),
709         hir::MatchSource::Normal => "MatchSource::Normal".to_string(),
710         hir::MatchSource::IfLetDesugar { contains_else_clause } => format!(
711             "MatchSource::IfLetDesugar {{ contains_else_clause: {} }}",
712             contains_else_clause
713         ),
714         hir::MatchSource::IfDesugar { contains_else_clause } => format!(
715             "MatchSource::IfDesugar {{ contains_else_clause: {} }}",
716             contains_else_clause
717         ),
718         hir::MatchSource::AwaitDesugar => "MatchSource::AwaitDesugar".to_string(),
719     }
720 }
721
722 #[must_use]
723 fn loop_desugaring_name(des: hir::LoopSource) -> &'static str {
724     match des {
725         hir::LoopSource::ForLoop => "LoopSource::ForLoop",
726         hir::LoopSource::Loop => "LoopSource::Loop",
727         hir::LoopSource::While => "LoopSource::While",
728         hir::LoopSource::WhileLet => "LoopSource::WhileLet",
729     }
730 }
731
732 fn print_path(path: &QPath<'_>, first: &mut bool) {
733     match *path {
734         QPath::Resolved(_, ref path) => {
735             for segment in path.segments {
736                 if *first {
737                     *first = false;
738                 } else {
739                     print!(", ");
740                 }
741                 print!("{:?}", segment.ident.as_str());
742             }
743         },
744         QPath::TypeRelative(ref ty, ref segment) => match ty.kind {
745             hir::TyKind::Path(ref inner_path) => {
746                 print_path(inner_path, first);
747                 if *first {
748                     *first = false;
749                 } else {
750                     print!(", ");
751                 }
752                 print!("{:?}", segment.ident.as_str());
753             },
754             ref other => print!("/* unimplemented: {:?}*/", other),
755         },
756     }
757 }