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