]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/author.rs
9623c6cbdaddf94b6783d0d03e949b72fd28643b
[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::Err(val) => println!("    if let LitKind::Err({}) = {}.node;", val, lit_pat),
264                     LitKind::Byte(b) => println!("    if let LitKind::Byte({}) = {}.node;", b, lit_pat),
265                     // FIXME: also check int type
266                     LitKind::Int(i, _) => println!("    if let LitKind::Int({}, _) = {}.node;", i, lit_pat),
267                     LitKind::Float(..) => println!("    if let LitKind::Float(..) = {}.node;", lit_pat),
268                     LitKind::FloatUnsuffixed(_) => {
269                         println!("    if let LitKind::FloatUnsuffixed(_) = {}.node;", lit_pat)
270                     },
271                     LitKind::ByteStr(ref vec) => {
272                         let vec_pat = self.next("vec");
273                         println!("    if let LitKind::ByteStr(ref {}) = {}.node;", vec_pat, lit_pat);
274                         println!("    if let [{:?}] = **{};", vec, vec_pat);
275                     },
276                     LitKind::Str(ref text, _) => {
277                         let str_pat = self.next("s");
278                         println!("    if let LitKind::Str(ref {}) = {}.node;", str_pat, lit_pat);
279                         println!("    if {}.as_str() == {:?}", str_pat, &*text.as_str())
280                     },
281                 }
282             },
283             ExprKind::Cast(ref expr, ref ty) => {
284                 let cast_pat = self.next("expr");
285                 let cast_ty = self.next("cast_ty");
286                 let qp_label = self.next("qp");
287
288                 println!("Cast(ref {}, ref {}) = {};", cast_pat, cast_ty, current);
289                 if let TyKind::Path(ref qp) = ty.node {
290                     println!("    if let TyKind::Path(ref {}) = {}.node;", qp_label, cast_ty);
291                     self.current = qp_label;
292                     self.print_qpath(qp);
293                 }
294                 self.current = cast_pat;
295                 self.visit_expr(expr);
296             },
297             ExprKind::Type(ref expr, ref _ty) => {
298                 let cast_pat = self.next("expr");
299                 println!("Type(ref {}, _) = {};", cast_pat, current);
300                 self.current = cast_pat;
301                 self.visit_expr(expr);
302             },
303             ExprKind::If(ref cond, ref then, ref opt_else) => {
304                 let cond_pat = self.next("cond");
305                 let then_pat = self.next("then");
306                 if let Some(ref else_) = *opt_else {
307                     let else_pat = self.next("else_");
308                     println!(
309                         "If(ref {}, ref {}, Some(ref {})) = {};",
310                         cond_pat, then_pat, else_pat, current
311                     );
312                     self.current = else_pat;
313                     self.visit_expr(else_);
314                 } else {
315                     println!("If(ref {}, ref {}, None) = {};", cond_pat, then_pat, current);
316                 }
317                 self.current = cond_pat;
318                 self.visit_expr(cond);
319                 self.current = then_pat;
320                 self.visit_expr(then);
321             },
322             ExprKind::While(ref cond, ref body, _) => {
323                 let cond_pat = self.next("cond");
324                 let body_pat = self.next("body");
325                 let label_pat = self.next("label");
326                 println!(
327                     "While(ref {}, ref {}, ref {}) = {};",
328                     cond_pat, body_pat, label_pat, current
329                 );
330                 self.current = cond_pat;
331                 self.visit_expr(cond);
332                 self.current = body_pat;
333                 self.visit_block(body);
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                     println!("    if {}[{}].pats.len() == {};", arms_pat, i, arm.pats.len());
367                     for (j, pat) in arm.pats.iter().enumerate() {
368                         self.current = format!("{}[{}].pats[{}]", arms_pat, i, j);
369                         self.visit_pat(pat);
370                     }
371                 }
372             },
373             ExprKind::Closure(ref _capture_clause, ref _func, _, _, _) => {
374                 println!("Closure(ref capture_clause, ref func, _, _, _) = {};", current);
375                 println!("    // unimplemented: `ExprKind::Closure` is not further destructured at the moment");
376             },
377             ExprKind::Yield(ref sub) => {
378                 let sub_pat = self.next("sub");
379                 println!("Yield(ref sub) = {};", current);
380                 self.current = sub_pat;
381                 self.visit_expr(sub);
382             },
383             ExprKind::Block(ref block, _) => {
384                 let block_pat = self.next("block");
385                 println!("Block(ref {}) = {};", block_pat, current);
386                 self.current = block_pat;
387                 self.visit_block(block);
388             },
389             ExprKind::Assign(ref target, ref value) => {
390                 let target_pat = self.next("target");
391                 let value_pat = self.next("value");
392                 println!("Assign(ref {}, ref {}) = {};", target_pat, value_pat, current);
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 {}.node.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(mutability, ref inner) => {
436                 let inner_pat = self.next("inner");
437                 println!("AddrOf({:?}, ref {}) = {};", mutability, inner_pat, current);
438                 self.current = inner_pat;
439                 self.visit_expr(inner);
440             },
441             ExprKind::Break(ref _destination, ref opt_value) => {
442                 let destination_pat = self.next("destination");
443                 if let Some(ref value) = *opt_value {
444                     let value_pat = self.next("value");
445                     println!("Break(ref {}, Some(ref {})) = {};", destination_pat, value_pat, current);
446                     self.current = value_pat;
447                     self.visit_expr(value);
448                 } else {
449                     println!("Break(ref {}, None) = {};", destination_pat, current);
450                 }
451                 // FIXME: implement label printing
452             },
453             ExprKind::Continue(ref _destination) => {
454                 let destination_pat = self.next("destination");
455                 println!("Again(ref {}) = {};", destination_pat, current);
456                 // FIXME: implement label printing
457             },
458             ExprKind::Ret(ref opt_value) => {
459                 if let Some(ref value) = *opt_value {
460                     let value_pat = self.next("value");
461                     println!("Ret(Some(ref {})) = {};", value_pat, current);
462                     self.current = value_pat;
463                     self.visit_expr(value);
464                 } else {
465                     println!("Ret(None) = {};", current);
466                 }
467             },
468             ExprKind::InlineAsm(_, ref _input, ref _output) => {
469                 println!("InlineAsm(_, ref input, ref output) = {};", current);
470                 println!("    // unimplemented: `ExprKind::InlineAsm` is not further destructured at the moment");
471             },
472             ExprKind::Struct(ref path, ref fields, ref opt_base) => {
473                 let path_pat = self.next("path");
474                 let fields_pat = self.next("fields");
475                 if let Some(ref base) = *opt_base {
476                     let base_pat = self.next("base");
477                     println!(
478                         "Struct(ref {}, ref {}, Some(ref {})) = {};",
479                         path_pat, fields_pat, base_pat, current
480                     );
481                     self.current = base_pat;
482                     self.visit_expr(base);
483                 } else {
484                     println!("Struct(ref {}, ref {}, None) = {};", path_pat, fields_pat, current);
485                 }
486                 self.current = path_pat;
487                 self.print_qpath(path);
488                 println!("    if {}.len() == {};", fields_pat, fields.len());
489                 println!("    // unimplemented: field checks");
490             },
491             // FIXME: compute length (needs type info)
492             ExprKind::Repeat(ref value, _) => {
493                 let value_pat = self.next("value");
494                 println!("Repeat(ref {}, _) = {};", value_pat, current);
495                 println!("// unimplemented: repeat count check");
496                 self.current = value_pat;
497                 self.visit_expr(value);
498             },
499             ExprKind::Err => {
500                 println!("Err = {}", current);
501             },
502         }
503     }
504
505     fn visit_pat(&mut self, pat: &Pat) {
506         print!("    if let PatKind::");
507         let current = format!("{}.node", self.current);
508         match pat.node {
509             PatKind::Wild => println!("Wild = {};", current),
510             PatKind::Binding(anno, _, ident, ref sub) => {
511                 let anno_pat = match anno {
512                     BindingAnnotation::Unannotated => "BindingAnnotation::Unannotated",
513                     BindingAnnotation::Mutable => "BindingAnnotation::Mutable",
514                     BindingAnnotation::Ref => "BindingAnnotation::Ref",
515                     BindingAnnotation::RefMut => "BindingAnnotation::RefMut",
516                 };
517                 let name_pat = self.next("name");
518                 if let Some(ref sub) = *sub {
519                     let sub_pat = self.next("sub");
520                     println!(
521                         "Binding({}, _, {}, Some(ref {})) = {};",
522                         anno_pat, name_pat, sub_pat, current
523                     );
524                     self.current = sub_pat;
525                     self.visit_pat(sub);
526                 } else {
527                     println!("Binding({}, _, {}, None) = {};", anno_pat, name_pat, current);
528                 }
529                 println!("    if {}.node.as_str() == \"{}\";", name_pat, ident.as_str());
530             },
531             PatKind::Struct(ref path, ref fields, ignore) => {
532                 let path_pat = self.next("path");
533                 let fields_pat = self.next("fields");
534                 println!(
535                     "Struct(ref {}, ref {}, {}) = {};",
536                     path_pat, fields_pat, ignore, current
537                 );
538                 self.current = path_pat;
539                 self.print_qpath(path);
540                 println!("    if {}.len() == {};", fields_pat, fields.len());
541                 println!("    // unimplemented: field checks");
542             },
543             PatKind::TupleStruct(ref path, ref fields, skip_pos) => {
544                 let path_pat = self.next("path");
545                 let fields_pat = self.next("fields");
546                 println!(
547                     "TupleStruct(ref {}, ref {}, {:?}) = {};",
548                     path_pat, fields_pat, skip_pos, current
549                 );
550                 self.current = path_pat;
551                 self.print_qpath(path);
552                 println!("    if {}.len() == {};", fields_pat, fields.len());
553                 println!("    // unimplemented: field checks");
554             },
555             PatKind::Path(ref path) => {
556                 let path_pat = self.next("path");
557                 println!("Path(ref {}) = {};", path_pat, current);
558                 self.current = path_pat;
559                 self.print_qpath(path);
560             },
561             PatKind::Tuple(ref fields, skip_pos) => {
562                 let fields_pat = self.next("fields");
563                 println!("Tuple(ref {}, {:?}) = {};", fields_pat, skip_pos, current);
564                 println!("    if {}.len() == {};", fields_pat, fields.len());
565                 println!("    // unimplemented: field checks");
566             },
567             PatKind::Box(ref pat) => {
568                 let pat_pat = self.next("pat");
569                 println!("Box(ref {}) = {};", pat_pat, current);
570                 self.current = pat_pat;
571                 self.visit_pat(pat);
572             },
573             PatKind::Ref(ref pat, muta) => {
574                 let pat_pat = self.next("pat");
575                 println!("Ref(ref {}, Mutability::{:?}) = {};", pat_pat, muta, current);
576                 self.current = pat_pat;
577                 self.visit_pat(pat);
578             },
579             PatKind::Lit(ref lit_expr) => {
580                 let lit_expr_pat = self.next("lit_expr");
581                 println!("Lit(ref {}) = {}", lit_expr_pat, current);
582                 self.current = lit_expr_pat;
583                 self.visit_expr(lit_expr);
584             },
585             PatKind::Range(ref start, ref end, end_kind) => {
586                 let start_pat = self.next("start");
587                 let end_pat = self.next("end");
588                 println!(
589                     "Range(ref {}, ref {}, RangeEnd::{:?}) = {};",
590                     start_pat, end_pat, end_kind, current
591                 );
592                 self.current = start_pat;
593                 self.visit_expr(start);
594                 self.current = end_pat;
595                 self.visit_expr(end);
596             },
597             PatKind::Slice(ref start, ref middle, ref end) => {
598                 let start_pat = self.next("start");
599                 let end_pat = self.next("end");
600                 if let Some(ref middle) = middle {
601                     let middle_pat = self.next("middle");
602                     println!(
603                         "Slice(ref {}, Some(ref {}), ref {}) = {};",
604                         start_pat, middle_pat, end_pat, current
605                     );
606                     self.current = middle_pat;
607                     self.visit_pat(middle);
608                 } else {
609                     println!("Slice(ref {}, None, ref {}) = {};", start_pat, end_pat, current);
610                 }
611                 println!("    if {}.len() == {};", start_pat, start.len());
612                 for (i, pat) in start.iter().enumerate() {
613                     self.current = format!("{}[{}]", start_pat, i);
614                     self.visit_pat(pat);
615                 }
616                 println!("    if {}.len() == {};", end_pat, end.len());
617                 for (i, pat) in end.iter().enumerate() {
618                     self.current = format!("{}[{}]", end_pat, i);
619                     self.visit_pat(pat);
620                 }
621             },
622         }
623     }
624
625     fn visit_stmt(&mut self, s: &Stmt) {
626         print!("    if let StmtKind::");
627         let current = format!("{}.node", self.current);
628         match s.node {
629             // A local (let) binding:
630             StmtKind::Local(ref local) => {
631                 let local_pat = self.next("local");
632                 println!("Local(ref {}) = {};", local_pat, current);
633                 if let Some(ref init) = local.init {
634                     let init_pat = self.next("init");
635                     println!("    if let Some(ref {}) = {}.init", init_pat, local_pat);
636                     self.current = init_pat;
637                     self.visit_expr(init);
638                 }
639                 self.current = format!("{}.pat", local_pat);
640                 self.visit_pat(&local.pat);
641             },
642             // An item binding:
643             StmtKind::Item(_) => {
644                 println!("Item(item_id) = {};", current);
645             },
646
647             // Expr without trailing semi-colon (must have unit type):
648             StmtKind::Expr(ref e) => {
649                 let e_pat = self.next("e");
650                 println!("Expr(ref {}, _) = {}", e_pat, current);
651                 self.current = e_pat;
652                 self.visit_expr(e);
653             },
654
655             // Expr with trailing semi-colon (may have any type):
656             StmtKind::Semi(ref e) => {
657                 let e_pat = self.next("e");
658                 println!("Semi(ref {}, _) = {}", e_pat, current);
659                 self.current = e_pat;
660                 self.visit_expr(e);
661             },
662         }
663     }
664
665     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
666         NestedVisitorMap::None
667     }
668 }
669
670 fn has_attr(attrs: &[Attribute]) -> bool {
671     get_attr(attrs, "author").count() > 0
672 }
673
674 fn desugaring_name(des: hir::MatchSource) -> String {
675     match des {
676         hir::MatchSource::ForLoopDesugar => "MatchSource::ForLoopDesugar".to_string(),
677         hir::MatchSource::TryDesugar => "MatchSource::TryDesugar".to_string(),
678         hir::MatchSource::WhileLetDesugar => "MatchSource::WhileLetDesugar".to_string(),
679         hir::MatchSource::Normal => "MatchSource::Normal".to_string(),
680         hir::MatchSource::IfLetDesugar { contains_else_clause } => format!(
681             "MatchSource::IfLetDesugar {{ contains_else_clause: {} }}",
682             contains_else_clause
683         ),
684     }
685 }
686
687 fn loop_desugaring_name(des: hir::LoopSource) -> &'static str {
688     match des {
689         hir::LoopSource::ForLoop => "LoopSource::ForLoop",
690         hir::LoopSource::Loop => "LoopSource::Loop",
691         hir::LoopSource::WhileLet => "LoopSource::WhileLet",
692     }
693 }
694
695 fn print_path(path: &QPath, first: &mut bool) {
696     match *path {
697         QPath::Resolved(_, ref path) => {
698             for segment in &path.segments {
699                 if *first {
700                     *first = false;
701                 } else {
702                     print!(", ");
703                 }
704                 print!("{:?}", segment.ident.as_str());
705             }
706         },
707         QPath::TypeRelative(ref ty, ref segment) => match ty.node {
708             hir::TyKind::Path(ref inner_path) => {
709                 print_path(inner_path, first);
710                 if *first {
711                     *first = false;
712                 } else {
713                     print!(", ");
714                 }
715                 print!("{:?}", segment.ident.as_str());
716             },
717             ref other => print!("/* unimplemented: {:?}*/", other),
718         },
719     }
720 }