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