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