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