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