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