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