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