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