]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/author.rs
Auto merge of #4218 - lzutao:rustup, 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, higher};
5 use rustc::hir;
6 use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
7 use rustc::hir::{BindingAnnotation, Block, 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         // handle if desugarings
191         // TODO add more desugarings here
192         if let Some((cond, then, opt_else)) = higher::if_block(&expr) {
193             let cond_pat = self.next("cond");
194             let then_pat = self.next("then");
195             if let Some(else_) = opt_else {
196                 let else_pat = self.next("else_");
197                 println!(
198                     "    if let Some((ref {}, ref {}, Some({}))) = higher::if_block(&{});",
199                     cond_pat, then_pat, else_pat, self.current
200                 );
201                 self.current = else_pat;
202                 self.visit_expr(else_);
203             } else {
204                 println!(
205                     "    if let Some((ref {}, ref {}, None)) = higher::if_block(&{});",
206                     cond_pat, then_pat, self.current
207                 );
208             }
209             self.current = cond_pat;
210             self.visit_expr(cond);
211             self.current = then_pat;
212             self.visit_expr(then);
213             return;
214         }
215
216         print!("    if let ExprKind::");
217         let current = format!("{}.node", self.current);
218         match expr.node {
219             ExprKind::Box(ref inner) => {
220                 let inner_pat = self.next("inner");
221                 println!("Box(ref {}) = {};", inner_pat, current);
222                 self.current = inner_pat;
223                 self.visit_expr(inner);
224             },
225             ExprKind::Array(ref elements) => {
226                 let elements_pat = self.next("elements");
227                 println!("Array(ref {}) = {};", elements_pat, current);
228                 println!("    if {}.len() == {};", elements_pat, elements.len());
229                 for (i, element) in elements.iter().enumerate() {
230                     self.current = format!("{}[{}]", elements_pat, i);
231                     self.visit_expr(element);
232                 }
233             },
234             ExprKind::Call(ref func, ref args) => {
235                 let func_pat = self.next("func");
236                 let args_pat = self.next("args");
237                 println!("Call(ref {}, ref {}) = {};", func_pat, args_pat, current);
238                 self.current = func_pat;
239                 self.visit_expr(func);
240                 println!("    if {}.len() == {};", args_pat, args.len());
241                 for (i, arg) in args.iter().enumerate() {
242                     self.current = format!("{}[{}]", args_pat, i);
243                     self.visit_expr(arg);
244                 }
245             },
246             ExprKind::MethodCall(ref _method_name, ref _generics, ref _args) => {
247                 println!("MethodCall(ref method_name, ref generics, ref args) = {};", current);
248                 println!("    // unimplemented: `ExprKind::MethodCall` is not further destructured at the moment");
249             },
250             ExprKind::Tup(ref elements) => {
251                 let elements_pat = self.next("elements");
252                 println!("Tup(ref {}) = {};", elements_pat, current);
253                 println!("    if {}.len() == {};", elements_pat, elements.len());
254                 for (i, element) in elements.iter().enumerate() {
255                     self.current = format!("{}[{}]", elements_pat, i);
256                     self.visit_expr(element);
257                 }
258             },
259             ExprKind::Binary(ref op, ref left, ref right) => {
260                 let op_pat = self.next("op");
261                 let left_pat = self.next("left");
262                 let right_pat = self.next("right");
263                 println!(
264                     "Binary(ref {}, ref {}, ref {}) = {};",
265                     op_pat, left_pat, right_pat, current
266                 );
267                 println!("    if BinOpKind::{:?} == {}.node;", op.node, op_pat);
268                 self.current = left_pat;
269                 self.visit_expr(left);
270                 self.current = right_pat;
271                 self.visit_expr(right);
272             },
273             ExprKind::Unary(ref op, ref inner) => {
274                 let inner_pat = self.next("inner");
275                 println!("Unary(UnOp::{:?}, ref {}) = {};", op, inner_pat, current);
276                 self.current = inner_pat;
277                 self.visit_expr(inner);
278             },
279             ExprKind::Lit(ref lit) => {
280                 let lit_pat = self.next("lit");
281                 println!("Lit(ref {}) = {};", lit_pat, current);
282                 match lit.node {
283                     LitKind::Bool(val) => println!("    if let LitKind::Bool({:?}) = {}.node;", val, lit_pat),
284                     LitKind::Char(c) => println!("    if let LitKind::Char({:?}) = {}.node;", c, lit_pat),
285                     LitKind::Err(val) => println!("    if let LitKind::Err({}) = {}.node;", val, lit_pat),
286                     LitKind::Byte(b) => println!("    if let LitKind::Byte({}) = {}.node;", b, lit_pat),
287                     // FIXME: also check int type
288                     LitKind::Int(i, _) => println!("    if let LitKind::Int({}, _) = {}.node;", i, lit_pat),
289                     LitKind::Float(..) => println!("    if let LitKind::Float(..) = {}.node;", lit_pat),
290                     LitKind::FloatUnsuffixed(_) => {
291                         println!("    if let LitKind::FloatUnsuffixed(_) = {}.node;", lit_pat)
292                     },
293                     LitKind::ByteStr(ref vec) => {
294                         let vec_pat = self.next("vec");
295                         println!("    if let LitKind::ByteStr(ref {}) = {}.node;", vec_pat, lit_pat);
296                         println!("    if let [{:?}] = **{};", vec, vec_pat);
297                     },
298                     LitKind::Str(ref text, _) => {
299                         let str_pat = self.next("s");
300                         println!("    if let LitKind::Str(ref {}) = {}.node;", str_pat, lit_pat);
301                         println!("    if {}.as_str() == {:?}", str_pat, &*text.as_str())
302                     },
303                 }
304             },
305             ExprKind::Cast(ref expr, ref ty) => {
306                 let cast_pat = self.next("expr");
307                 let cast_ty = self.next("cast_ty");
308                 let qp_label = self.next("qp");
309
310                 println!("Cast(ref {}, ref {}) = {};", cast_pat, cast_ty, current);
311                 if let TyKind::Path(ref qp) = ty.node {
312                     println!("    if let TyKind::Path(ref {}) = {}.node;", qp_label, cast_ty);
313                     self.current = qp_label;
314                     self.print_qpath(qp);
315                 }
316                 self.current = cast_pat;
317                 self.visit_expr(expr);
318             },
319             ExprKind::Type(ref expr, ref _ty) => {
320                 let cast_pat = self.next("expr");
321                 println!("Type(ref {}, _) = {};", cast_pat, current);
322                 self.current = cast_pat;
323                 self.visit_expr(expr);
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!(
330                     "While(ref {}, ref {}, ref {}) = {};",
331                     cond_pat, body_pat, label_pat, current
332                 );
333                 self.current = cond_pat;
334                 self.visit_expr(cond);
335                 self.current = body_pat;
336                 self.visit_block(body);
337             },
338             ExprKind::Loop(ref body, _, desugaring) => {
339                 let body_pat = self.next("body");
340                 let des = loop_desugaring_name(desugaring);
341                 let label_pat = self.next("label");
342                 println!("Loop(ref {}, ref {}, {}) = {};", body_pat, label_pat, des, current);
343                 self.current = body_pat;
344                 self.visit_block(body);
345             },
346             ExprKind::Match(ref expr, ref arms, desugaring) => {
347                 let des = desugaring_name(desugaring);
348                 let expr_pat = self.next("expr");
349                 let arms_pat = self.next("arms");
350                 println!("Match(ref {}, ref {}, {}) = {};", expr_pat, arms_pat, des, current);
351                 self.current = expr_pat;
352                 self.visit_expr(expr);
353                 println!("    if {}.len() == {};", arms_pat, arms.len());
354                 for (i, arm) in arms.iter().enumerate() {
355                     self.current = format!("{}[{}].body", arms_pat, i);
356                     self.visit_expr(&arm.body);
357                     if let Some(ref guard) = arm.guard {
358                         let guard_pat = self.next("guard");
359                         println!("    if let Some(ref {}) = {}[{}].guard;", guard_pat, arms_pat, i);
360                         match guard {
361                             hir::Guard::If(ref if_expr) => {
362                                 let if_expr_pat = self.next("expr");
363                                 println!("    if let Guard::If(ref {}) = {};", if_expr_pat, guard_pat);
364                                 self.current = if_expr_pat;
365                                 self.visit_expr(if_expr);
366                             },
367                         }
368                     }
369                     println!("    if {}[{}].pats.len() == {};", arms_pat, i, arm.pats.len());
370                     for (j, pat) in arm.pats.iter().enumerate() {
371                         self.current = format!("{}[{}].pats[{}]", arms_pat, i, j);
372                         self.visit_pat(pat);
373                     }
374                 }
375             },
376             ExprKind::Closure(ref _capture_clause, ref _func, _, _, _) => {
377                 println!("Closure(ref capture_clause, ref func, _, _, _) = {};", current);
378                 println!("    // unimplemented: `ExprKind::Closure` is not further destructured at the moment");
379             },
380             ExprKind::Yield(ref sub, _) => {
381                 let sub_pat = self.next("sub");
382                 println!("Yield(ref sub) = {};", current);
383                 self.current = sub_pat;
384                 self.visit_expr(sub);
385             },
386             ExprKind::Block(ref block, _) => {
387                 let block_pat = self.next("block");
388                 println!("Block(ref {}) = {};", block_pat, current);
389                 self.current = block_pat;
390                 self.visit_block(block);
391             },
392             ExprKind::Assign(ref target, ref value) => {
393                 let target_pat = self.next("target");
394                 let value_pat = self.next("value");
395                 println!("Assign(ref {}, ref {}) = {};", target_pat, value_pat, current);
396                 self.current = target_pat;
397                 self.visit_expr(target);
398                 self.current = value_pat;
399                 self.visit_expr(value);
400             },
401             ExprKind::AssignOp(ref op, ref target, ref value) => {
402                 let op_pat = self.next("op");
403                 let target_pat = self.next("target");
404                 let value_pat = self.next("value");
405                 println!(
406                     "AssignOp(ref {}, ref {}, ref {}) = {};",
407                     op_pat, target_pat, value_pat, current
408                 );
409                 println!("    if BinOpKind::{:?} == {}.node;", op.node, op_pat);
410                 self.current = target_pat;
411                 self.visit_expr(target);
412                 self.current = value_pat;
413                 self.visit_expr(value);
414             },
415             ExprKind::Field(ref object, ref field_ident) => {
416                 let obj_pat = self.next("object");
417                 let field_name_pat = self.next("field_name");
418                 println!("Field(ref {}, ref {}) = {};", obj_pat, field_name_pat, current);
419                 println!("    if {}.node.as_str() == {:?}", field_name_pat, field_ident.as_str());
420                 self.current = obj_pat;
421                 self.visit_expr(object);
422             },
423             ExprKind::Index(ref object, ref index) => {
424                 let object_pat = self.next("object");
425                 let index_pat = self.next("index");
426                 println!("Index(ref {}, ref {}) = {};", object_pat, index_pat, current);
427                 self.current = object_pat;
428                 self.visit_expr(object);
429                 self.current = index_pat;
430                 self.visit_expr(index);
431             },
432             ExprKind::Path(ref path) => {
433                 let path_pat = self.next("path");
434                 println!("Path(ref {}) = {};", path_pat, current);
435                 self.current = path_pat;
436                 self.print_qpath(path);
437             },
438             ExprKind::AddrOf(mutability, ref inner) => {
439                 let inner_pat = self.next("inner");
440                 println!("AddrOf({:?}, ref {}) = {};", mutability, inner_pat, current);
441                 self.current = inner_pat;
442                 self.visit_expr(inner);
443             },
444             ExprKind::Break(ref _destination, ref opt_value) => {
445                 let destination_pat = self.next("destination");
446                 if let Some(ref value) = *opt_value {
447                     let value_pat = self.next("value");
448                     println!("Break(ref {}, Some(ref {})) = {};", destination_pat, value_pat, current);
449                     self.current = value_pat;
450                     self.visit_expr(value);
451                 } else {
452                     println!("Break(ref {}, None) = {};", destination_pat, current);
453                 }
454                 // FIXME: implement label printing
455             },
456             ExprKind::Continue(ref _destination) => {
457                 let destination_pat = self.next("destination");
458                 println!("Again(ref {}) = {};", destination_pat, current);
459                 // FIXME: implement label printing
460             },
461             ExprKind::Ret(ref opt_value) => {
462                 if let Some(ref value) = *opt_value {
463                     let value_pat = self.next("value");
464                     println!("Ret(Some(ref {})) = {};", value_pat, current);
465                     self.current = value_pat;
466                     self.visit_expr(value);
467                 } else {
468                     println!("Ret(None) = {};", current);
469                 }
470             },
471             ExprKind::InlineAsm(_, ref _input, ref _output) => {
472                 println!("InlineAsm(_, ref input, ref output) = {};", current);
473                 println!("    // unimplemented: `ExprKind::InlineAsm` is not further destructured at the moment");
474             },
475             ExprKind::Struct(ref path, ref fields, ref opt_base) => {
476                 let path_pat = self.next("path");
477                 let fields_pat = self.next("fields");
478                 if let Some(ref base) = *opt_base {
479                     let base_pat = self.next("base");
480                     println!(
481                         "Struct(ref {}, ref {}, Some(ref {})) = {};",
482                         path_pat, fields_pat, base_pat, current
483                     );
484                     self.current = base_pat;
485                     self.visit_expr(base);
486                 } else {
487                     println!("Struct(ref {}, ref {}, None) = {};", path_pat, fields_pat, current);
488                 }
489                 self.current = path_pat;
490                 self.print_qpath(path);
491                 println!("    if {}.len() == {};", fields_pat, fields.len());
492                 println!("    // unimplemented: field checks");
493             },
494             // FIXME: compute length (needs type info)
495             ExprKind::Repeat(ref value, _) => {
496                 let value_pat = self.next("value");
497                 println!("Repeat(ref {}, _) = {};", value_pat, current);
498                 println!("// unimplemented: repeat count check");
499                 self.current = value_pat;
500                 self.visit_expr(value);
501             },
502             ExprKind::Err => {
503                 println!("Err = {}", current);
504             },
505             ExprKind::DropTemps(ref expr) => {
506                 let expr_pat = self.next("expr");
507                 println!("DropTemps(ref {}) = {};", expr_pat, current);
508                 self.current = expr_pat;
509                 self.visit_expr(expr);
510             },
511         }
512     }
513
514     fn visit_block(&mut self, block: &Block) {
515         let trailing_pat = self.next("trailing_expr");
516         println!("    if let Some({}) = &{}.expr;", trailing_pat, self.current);
517         println!("    if {}.stmts.len() == {};", self.current, block.stmts.len());
518         let current = self.current.clone();
519         for (i, stmt) in block.stmts.iter().enumerate() {
520             self.current = format!("{}.stmts[{}]", current, i);
521             self.visit_stmt(stmt);
522         }
523     }
524
525     #[allow(clippy::too_many_lines)]
526     fn visit_pat(&mut self, pat: &Pat) {
527         print!("    if let PatKind::");
528         let current = format!("{}.node", self.current);
529         match pat.node {
530             PatKind::Wild => println!("Wild = {};", current),
531             PatKind::Binding(anno, .., ident, ref sub) => {
532                 let anno_pat = match anno {
533                     BindingAnnotation::Unannotated => "BindingAnnotation::Unannotated",
534                     BindingAnnotation::Mutable => "BindingAnnotation::Mutable",
535                     BindingAnnotation::Ref => "BindingAnnotation::Ref",
536                     BindingAnnotation::RefMut => "BindingAnnotation::RefMut",
537                 };
538                 let name_pat = self.next("name");
539                 if let Some(ref sub) = *sub {
540                     let sub_pat = self.next("sub");
541                     println!(
542                         "Binding({}, _, {}, Some(ref {})) = {};",
543                         anno_pat, name_pat, sub_pat, current
544                     );
545                     self.current = sub_pat;
546                     self.visit_pat(sub);
547                 } else {
548                     println!("Binding({}, _, {}, None) = {};", anno_pat, name_pat, current);
549                 }
550                 println!("    if {}.node.as_str() == \"{}\";", name_pat, ident.as_str());
551             },
552             PatKind::Struct(ref path, ref fields, ignore) => {
553                 let path_pat = self.next("path");
554                 let fields_pat = self.next("fields");
555                 println!(
556                     "Struct(ref {}, ref {}, {}) = {};",
557                     path_pat, fields_pat, ignore, current
558                 );
559                 self.current = path_pat;
560                 self.print_qpath(path);
561                 println!("    if {}.len() == {};", fields_pat, fields.len());
562                 println!("    // unimplemented: field checks");
563             },
564             PatKind::TupleStruct(ref path, ref fields, skip_pos) => {
565                 let path_pat = self.next("path");
566                 let fields_pat = self.next("fields");
567                 println!(
568                     "TupleStruct(ref {}, ref {}, {:?}) = {};",
569                     path_pat, fields_pat, skip_pos, current
570                 );
571                 self.current = path_pat;
572                 self.print_qpath(path);
573                 println!("    if {}.len() == {};", fields_pat, fields.len());
574                 println!("    // unimplemented: field checks");
575             },
576             PatKind::Path(ref path) => {
577                 let path_pat = self.next("path");
578                 println!("Path(ref {}) = {};", path_pat, current);
579                 self.current = path_pat;
580                 self.print_qpath(path);
581             },
582             PatKind::Tuple(ref fields, skip_pos) => {
583                 let fields_pat = self.next("fields");
584                 println!("Tuple(ref {}, {:?}) = {};", fields_pat, skip_pos, current);
585                 println!("    if {}.len() == {};", fields_pat, fields.len());
586                 println!("    // unimplemented: field checks");
587             },
588             PatKind::Box(ref pat) => {
589                 let pat_pat = self.next("pat");
590                 println!("Box(ref {}) = {};", pat_pat, current);
591                 self.current = pat_pat;
592                 self.visit_pat(pat);
593             },
594             PatKind::Ref(ref pat, muta) => {
595                 let pat_pat = self.next("pat");
596                 println!("Ref(ref {}, Mutability::{:?}) = {};", pat_pat, muta, current);
597                 self.current = pat_pat;
598                 self.visit_pat(pat);
599             },
600             PatKind::Lit(ref lit_expr) => {
601                 let lit_expr_pat = self.next("lit_expr");
602                 println!("Lit(ref {}) = {}", lit_expr_pat, current);
603                 self.current = lit_expr_pat;
604                 self.visit_expr(lit_expr);
605             },
606             PatKind::Range(ref start, ref end, end_kind) => {
607                 let start_pat = self.next("start");
608                 let end_pat = self.next("end");
609                 println!(
610                     "Range(ref {}, ref {}, RangeEnd::{:?}) = {};",
611                     start_pat, end_pat, end_kind, current
612                 );
613                 self.current = start_pat;
614                 self.visit_expr(start);
615                 self.current = end_pat;
616                 self.visit_expr(end);
617             },
618             PatKind::Slice(ref start, ref middle, ref end) => {
619                 let start_pat = self.next("start");
620                 let end_pat = self.next("end");
621                 if let Some(ref middle) = middle {
622                     let middle_pat = self.next("middle");
623                     println!(
624                         "Slice(ref {}, Some(ref {}), ref {}) = {};",
625                         start_pat, middle_pat, end_pat, current
626                     );
627                     self.current = middle_pat;
628                     self.visit_pat(middle);
629                 } else {
630                     println!("Slice(ref {}, None, ref {}) = {};", start_pat, end_pat, current);
631                 }
632                 println!("    if {}.len() == {};", start_pat, start.len());
633                 for (i, pat) in start.iter().enumerate() {
634                     self.current = format!("{}[{}]", start_pat, i);
635                     self.visit_pat(pat);
636                 }
637                 println!("    if {}.len() == {};", end_pat, end.len());
638                 for (i, pat) in end.iter().enumerate() {
639                     self.current = format!("{}[{}]", end_pat, i);
640                     self.visit_pat(pat);
641                 }
642             },
643         }
644     }
645
646     fn visit_stmt(&mut self, s: &Stmt) {
647         print!("    if let StmtKind::");
648         let current = format!("{}.node", self.current);
649         match s.node {
650             // A local (let) binding:
651             StmtKind::Local(ref local) => {
652                 let local_pat = self.next("local");
653                 println!("Local(ref {}) = {};", local_pat, current);
654                 if let Some(ref init) = local.init {
655                     let init_pat = self.next("init");
656                     println!("    if let Some(ref {}) = {}.init;", init_pat, local_pat);
657                     self.current = init_pat;
658                     self.visit_expr(init);
659                 }
660                 self.current = format!("{}.pat", local_pat);
661                 self.visit_pat(&local.pat);
662             },
663             // An item binding:
664             StmtKind::Item(_) => {
665                 println!("Item(item_id) = {};", current);
666             },
667
668             // Expr without trailing semi-colon (must have unit type):
669             StmtKind::Expr(ref e) => {
670                 let e_pat = self.next("e");
671                 println!("Expr(ref {}, _) = {}", e_pat, current);
672                 self.current = e_pat;
673                 self.visit_expr(e);
674             },
675
676             // Expr with trailing semi-colon (may have any type):
677             StmtKind::Semi(ref e) => {
678                 let e_pat = self.next("e");
679                 println!("Semi(ref {}, _) = {}", e_pat, current);
680                 self.current = e_pat;
681                 self.visit_expr(e);
682             },
683         }
684     }
685
686     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
687         NestedVisitorMap::None
688     }
689 }
690
691 fn has_attr(sess: &Session, attrs: &[Attribute]) -> bool {
692     get_attr(sess, attrs, "author").count() > 0
693 }
694
695 fn desugaring_name(des: hir::MatchSource) -> String {
696     match des {
697         hir::MatchSource::ForLoopDesugar => "MatchSource::ForLoopDesugar".to_string(),
698         hir::MatchSource::TryDesugar => "MatchSource::TryDesugar".to_string(),
699         hir::MatchSource::WhileLetDesugar => "MatchSource::WhileLetDesugar".to_string(),
700         hir::MatchSource::Normal => "MatchSource::Normal".to_string(),
701         hir::MatchSource::IfLetDesugar { contains_else_clause } => format!(
702             "MatchSource::IfLetDesugar {{ contains_else_clause: {} }}",
703             contains_else_clause
704         ),
705         hir::MatchSource::IfDesugar { contains_else_clause } => format!(
706             "MatchSource::IfDesugar {{ contains_else_clause: {} }}",
707             contains_else_clause
708         ),
709         hir::MatchSource::AwaitDesugar => "MatchSource::AwaitDesugar".to_string(),
710     }
711 }
712
713 fn loop_desugaring_name(des: hir::LoopSource) -> &'static str {
714     match des {
715         hir::LoopSource::ForLoop => "LoopSource::ForLoop",
716         hir::LoopSource::Loop => "LoopSource::Loop",
717         hir::LoopSource::WhileLet => "LoopSource::WhileLet",
718     }
719 }
720
721 fn print_path(path: &QPath, first: &mut bool) {
722     match *path {
723         QPath::Resolved(_, ref path) => {
724             for segment in &path.segments {
725                 if *first {
726                     *first = false;
727                 } else {
728                     print!(", ");
729                 }
730                 print!("{:?}", segment.ident.as_str());
731             }
732         },
733         QPath::TypeRelative(ref ty, ref segment) => match ty.node {
734             hir::TyKind::Path(ref inner_path) => {
735                 print_path(inner_path, first);
736                 if *first {
737                     *first = false;
738                 } else {
739                     print!(", ");
740                 }
741                 print!("{:?}", segment.ident.as_str());
742             },
743             ref other => print!("/* unimplemented: {:?}*/", other),
744         },
745     }
746 }