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