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