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