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