]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/author.rs
Auto merge of #8707 - OneSignal:await-invalid-types, r=llogiq
[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 clippy_utils::{get_attr, higher};
5 use rustc_ast::ast::{LitFloatType, LitKind};
6 use rustc_ast::LitIntType;
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_hir as hir;
9 use rustc_hir::{ArrayLen, ExprKind, FnRetTy, HirId, Lit, PatKind, QPath, StmtKind, TyKind};
10 use rustc_lint::{LateContext, LateLintPass, LintContext};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::symbol::{Ident, Symbol};
13 use std::fmt::{Display, Formatter, Write as _};
14
15 declare_clippy_lint! {
16     /// ### What it does
17     /// 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 /// Writes a line of output with indentation added
57 macro_rules! out {
58     ($($t:tt)*) => {
59         println!("    {}", format_args!($($t)*))
60     };
61 }
62
63 /// The variables passed in are replaced with `&Binding`s where the `value` field is set
64 /// to the original value of the variable. The `name` field is set to the name of the variable
65 /// (using `stringify!`) and is adjusted to avoid duplicate names.
66 /// Note that the `Binding` may be printed directly to output the `name`.
67 macro_rules! bind {
68     ($self:ident $(, $name:ident)+) => {
69         $(let $name = & $self.bind(stringify!($name), $name);)+
70     };
71 }
72
73 /// Transforms the given `Option<T>` variables into `OptionPat<Binding<T>>`.
74 /// This displays as `Some($name)` or `None` when printed. The name of the inner binding
75 /// is set to the name of the variable passed to the macro.
76 macro_rules! opt_bind {
77     ($self:ident $(, $name:ident)+) => {
78         $(let $name = OptionPat::new($name.map(|o| $self.bind(stringify!($name), o)));)+
79     };
80 }
81
82 /// Creates a `Binding` that accesses the field of an existing `Binding`
83 macro_rules! field {
84     ($binding:ident.$field:ident) => {
85         &Binding {
86             name: $binding.name.to_string() + stringify!(.$field),
87             value: $binding.value.$field,
88         }
89     };
90 }
91
92 fn prelude() {
93     println!("if_chain! {{");
94 }
95
96 fn done() {
97     println!("    then {{");
98     println!("        // report your lint here");
99     println!("    }}");
100     println!("}}");
101 }
102
103 impl<'tcx> LateLintPass<'tcx> for Author {
104     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
105         check_item(cx, item.hir_id());
106     }
107
108     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
109         check_item(cx, item.hir_id());
110     }
111
112     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
113         check_item(cx, item.hir_id());
114     }
115
116     fn check_arm(&mut self, cx: &LateContext<'tcx>, arm: &'tcx hir::Arm<'_>) {
117         check_node(cx, arm.hir_id, |v| {
118             v.arm(&v.bind("arm", arm));
119         });
120     }
121
122     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
123         check_node(cx, expr.hir_id, |v| {
124             v.expr(&v.bind("expr", expr));
125         });
126     }
127
128     fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx hir::Stmt<'_>) {
129         match stmt.kind {
130             StmtKind::Expr(e) | StmtKind::Semi(e) if has_attr(cx, e.hir_id) => return,
131             _ => {},
132         }
133         check_node(cx, stmt.hir_id, |v| {
134             v.stmt(&v.bind("stmt", stmt));
135         });
136     }
137 }
138
139 fn check_item(cx: &LateContext<'_>, hir_id: HirId) {
140     let hir = cx.tcx.hir();
141     if let Some(body_id) = hir.maybe_body_owned_by(hir_id) {
142         check_node(cx, hir_id, |v| {
143             v.expr(&v.bind("expr", &hir.body(body_id).value));
144         });
145     }
146 }
147
148 fn check_node(cx: &LateContext<'_>, hir_id: HirId, f: impl Fn(&PrintVisitor<'_, '_>)) {
149     if has_attr(cx, hir_id) {
150         prelude();
151         f(&PrintVisitor::new(cx));
152         done();
153     }
154 }
155
156 struct Binding<T> {
157     name: String,
158     value: T,
159 }
160
161 impl<T> Display for Binding<T> {
162     fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
163         f.write_str(&self.name)
164     }
165 }
166
167 struct OptionPat<T> {
168     pub opt: Option<T>,
169 }
170
171 impl<T> OptionPat<T> {
172     fn new(opt: Option<T>) -> Self {
173         Self { opt }
174     }
175
176     fn if_some(&self, f: impl Fn(&T)) {
177         if let Some(t) = &self.opt {
178             f(t);
179         }
180     }
181 }
182
183 impl<T: Display> Display for OptionPat<T> {
184     fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
185         match &self.opt {
186             None => f.write_str("None"),
187             Some(node) => write!(f, "Some({node})"),
188         }
189     }
190 }
191
192 struct PrintVisitor<'a, 'tcx> {
193     cx: &'a LateContext<'tcx>,
194     /// Fields are the current index that needs to be appended to pattern
195     /// binding names
196     ids: std::cell::Cell<FxHashMap<&'static str, u32>>,
197 }
198
199 #[allow(clippy::unused_self)]
200 impl<'a, 'tcx> PrintVisitor<'a, 'tcx> {
201     fn new(cx: &'a LateContext<'tcx>) -> Self {
202         Self {
203             cx,
204             ids: std::cell::Cell::default(),
205         }
206     }
207
208     fn next(&self, s: &'static str) -> String {
209         let mut ids = self.ids.take();
210         let out = match *ids.entry(s).and_modify(|n| *n += 1).or_default() {
211             // first usage of the name, use it as is
212             0 => s.to_string(),
213             // append a number starting with 1
214             n => format!("{s}{n}"),
215         };
216         self.ids.set(ids);
217         out
218     }
219
220     fn bind<T>(&self, name: &'static str, value: T) -> Binding<T> {
221         let name = self.next(name);
222         Binding { name, value }
223     }
224
225     fn option<T: Copy>(&self, option: &Binding<Option<T>>, name: &'static str, f: impl Fn(&Binding<T>)) {
226         match option.value {
227             None => out!("if {option}.is_none();"),
228             Some(value) => {
229                 let value = &self.bind(name, value);
230                 out!("if let Some({value}) = {option};");
231                 f(value);
232             },
233         }
234     }
235
236     fn slice<T>(&self, slice: &Binding<&[T]>, f: impl Fn(&Binding<&T>)) {
237         if slice.value.is_empty() {
238             out!("if {slice}.is_empty();");
239         } else {
240             out!("if {slice}.len() == {};", slice.value.len());
241             for (i, value) in slice.value.iter().enumerate() {
242                 let name = format!("{slice}[{i}]");
243                 f(&Binding { name, value });
244             }
245         }
246     }
247
248     fn destination(&self, destination: &Binding<hir::Destination>) {
249         self.option(field!(destination.label), "label", |label| {
250             self.ident(field!(label.ident));
251         });
252     }
253
254     fn ident(&self, ident: &Binding<Ident>) {
255         out!("if {ident}.as_str() == {:?};", ident.value.as_str());
256     }
257
258     fn symbol(&self, symbol: &Binding<Symbol>) {
259         out!("if {symbol}.as_str() == {:?};", symbol.value.as_str());
260     }
261
262     fn qpath(&self, qpath: &Binding<&QPath<'_>>) {
263         if let QPath::LangItem(lang_item, ..) = *qpath.value {
264             out!("if matches!({qpath}, QPath::LangItem(LangItem::{lang_item:?}, _));");
265         } else {
266             out!("if match_qpath({qpath}, &[{}]);", path_to_string(qpath.value));
267         }
268     }
269
270     fn lit(&self, lit: &Binding<&Lit>) {
271         let kind = |kind| out!("if let LitKind::{kind} = {lit}.node;");
272         macro_rules! kind {
273             ($($t:tt)*) => (kind(format_args!($($t)*)));
274         }
275
276         match lit.value.node {
277             LitKind::Bool(val) => kind!("Bool({val:?})"),
278             LitKind::Char(c) => kind!("Char({c:?})"),
279             LitKind::Err(val) => kind!("Err({val})"),
280             LitKind::Byte(b) => kind!("Byte({b})"),
281             LitKind::Int(i, suffix) => {
282                 let int_ty = match suffix {
283                     LitIntType::Signed(int_ty) => format!("LitIntType::Signed(IntTy::{int_ty:?})"),
284                     LitIntType::Unsigned(uint_ty) => format!("LitIntType::Unsigned(UintTy::{uint_ty:?})"),
285                     LitIntType::Unsuffixed => String::from("LitIntType::Unsuffixed"),
286                 };
287                 kind!("Int({i}, {int_ty})");
288             },
289             LitKind::Float(_, suffix) => {
290                 let float_ty = match suffix {
291                     LitFloatType::Suffixed(suffix_ty) => format!("LitFloatType::Suffixed(FloatTy::{suffix_ty:?})"),
292                     LitFloatType::Unsuffixed => String::from("LitFloatType::Unsuffixed"),
293                 };
294                 kind!("Float(_, {float_ty})");
295             },
296             LitKind::ByteStr(ref vec) => {
297                 bind!(self, vec);
298                 kind!("ByteStr(ref {vec})");
299                 out!("if let [{:?}] = **{vec};", vec.value);
300             },
301             LitKind::Str(s, _) => {
302                 bind!(self, s);
303                 kind!("Str({s}, _)");
304                 self.symbol(s);
305             },
306         }
307     }
308
309     fn arm(&self, arm: &Binding<&hir::Arm<'_>>) {
310         self.pat(field!(arm.pat));
311         match arm.value.guard {
312             None => out!("if {arm}.guard.is_none();"),
313             Some(hir::Guard::If(expr)) => {
314                 bind!(self, expr);
315                 out!("if let Some(Guard::If({expr})) = {arm}.guard;");
316                 self.expr(expr);
317             },
318             Some(hir::Guard::IfLet(pat, expr)) => {
319                 bind!(self, pat, expr);
320                 out!("if let Some(Guard::IfLet({pat}, {expr}) = {arm}.guard;");
321                 self.pat(pat);
322                 self.expr(expr);
323             },
324         }
325         self.expr(field!(arm.body));
326     }
327
328     #[allow(clippy::too_many_lines)]
329     fn expr(&self, expr: &Binding<&hir::Expr<'_>>) {
330         if let Some(higher::While { condition, body }) = higher::While::hir(expr.value) {
331             bind!(self, condition, body);
332             out!(
333                 "if let Some(higher::While {{ condition: {condition}, body: {body} }}) \
334                 = higher::While::hir({expr});"
335             );
336             self.expr(condition);
337             self.expr(body);
338             return;
339         }
340
341         if let Some(higher::WhileLet {
342             let_pat,
343             let_expr,
344             if_then,
345         }) = higher::WhileLet::hir(expr.value)
346         {
347             bind!(self, let_pat, let_expr, if_then);
348             out!(
349                 "if let Some(higher::WhileLet {{ let_pat: {let_pat}, let_expr: {let_expr}, if_then: {if_then} }}) \
350                 = higher::WhileLet::hir({expr});"
351             );
352             self.pat(let_pat);
353             self.expr(let_expr);
354             self.expr(if_then);
355             return;
356         }
357
358         if let Some(higher::ForLoop { pat, arg, body, .. }) = higher::ForLoop::hir(expr.value) {
359             bind!(self, pat, arg, body);
360             out!(
361                 "if let Some(higher::ForLoop {{ pat: {pat}, arg: {arg}, body: {body}, .. }}) \
362                 = higher::ForLoop::hir({expr});"
363             );
364             self.pat(pat);
365             self.expr(arg);
366             self.expr(body);
367             return;
368         }
369
370         let kind = |kind| out!("if let ExprKind::{kind} = {expr}.kind;");
371         macro_rules! kind {
372             ($($t:tt)*) => (kind(format_args!($($t)*)));
373         }
374
375         match expr.value.kind {
376             ExprKind::Let(let_expr) => {
377                 bind!(self, let_expr);
378                 kind!("Let({let_expr})");
379                 self.pat(field!(let_expr.pat));
380                 // Does what ExprKind::Cast does, only adds a clause for the type
381                 // if it's a path
382                 if let Some(TyKind::Path(ref qpath)) = let_expr.value.ty.as_ref().map(|ty| &ty.kind) {
383                     bind!(self, qpath);
384                     out!("if let TyKind::Path(ref {qpath}) = {let_expr}.ty.kind;");
385                     self.qpath(qpath);
386                 }
387                 self.expr(field!(let_expr.init));
388             },
389             ExprKind::Box(inner) => {
390                 bind!(self, inner);
391                 kind!("Box({inner})");
392                 self.expr(inner);
393             },
394             ExprKind::Array(elements) => {
395                 bind!(self, elements);
396                 kind!("Array({elements})");
397                 self.slice(elements, |e| self.expr(e));
398             },
399             ExprKind::Call(func, args) => {
400                 bind!(self, func, args);
401                 kind!("Call({func}, {args})");
402                 self.expr(func);
403                 self.slice(args, |e| self.expr(e));
404             },
405             ExprKind::MethodCall(method_name, args, _) => {
406                 bind!(self, method_name, args);
407                 kind!("MethodCall({method_name}, {args}, _)");
408                 self.ident(field!(method_name.ident));
409                 self.slice(args, |e| self.expr(e));
410             },
411             ExprKind::Tup(elements) => {
412                 bind!(self, elements);
413                 kind!("Tup({elements})");
414                 self.slice(elements, |e| self.expr(e));
415             },
416             ExprKind::Binary(op, left, right) => {
417                 bind!(self, op, left, right);
418                 kind!("Binary({op}, {left}, {right})");
419                 out!("if BinOpKind::{:?} == {op}.node;", op.value.node);
420                 self.expr(left);
421                 self.expr(right);
422             },
423             ExprKind::Unary(op, inner) => {
424                 bind!(self, inner);
425                 kind!("Unary(UnOp::{op:?}, {inner})");
426                 self.expr(inner);
427             },
428             ExprKind::Lit(ref lit) => {
429                 bind!(self, lit);
430                 kind!("Lit(ref {lit})");
431                 self.lit(lit);
432             },
433             ExprKind::Cast(expr, cast_ty) => {
434                 bind!(self, expr, cast_ty);
435                 kind!("Cast({expr}, {cast_ty})");
436                 if let TyKind::Path(ref qpath) = cast_ty.value.kind {
437                     bind!(self, qpath);
438                     out!("if let TyKind::Path(ref {qpath}) = {cast_ty}.kind;");
439                     self.qpath(qpath);
440                 }
441                 self.expr(expr);
442             },
443             ExprKind::Type(expr, _ty) => {
444                 bind!(self, expr);
445                 kind!("Type({expr}, _)");
446                 self.expr(expr);
447             },
448             ExprKind::Loop(body, label, des, _) => {
449                 bind!(self, body);
450                 opt_bind!(self, label);
451                 kind!("Loop({body}, {label}, LoopSource::{des:?}, _)");
452                 self.block(body);
453                 label.if_some(|l| self.ident(field!(l.ident)));
454             },
455             ExprKind::If(cond, then, else_expr) => {
456                 bind!(self, cond, then);
457                 opt_bind!(self, else_expr);
458                 kind!("If({cond}, {then}, {else_expr})");
459                 self.expr(cond);
460                 self.expr(then);
461                 else_expr.if_some(|e| self.expr(e));
462             },
463             ExprKind::Match(scrutinee, arms, des) => {
464                 bind!(self, scrutinee, arms);
465                 kind!("Match({scrutinee}, {arms}, MatchSource::{des:?})");
466                 self.expr(scrutinee);
467                 self.slice(arms, |arm| self.arm(arm));
468             },
469             ExprKind::Closure(capture_by, fn_decl, body_id, _, movability) => {
470                 let movability = OptionPat::new(movability.map(|m| format!("Movability::{m:?}")));
471
472                 let ret_ty = match fn_decl.output {
473                     FnRetTy::DefaultReturn(_) => "FnRetTy::DefaultReturn(_)",
474                     FnRetTy::Return(_) => "FnRetTy::Return(_ty)",
475                 };
476
477                 bind!(self, fn_decl, body_id);
478                 kind!("Closure(CaptureBy::{capture_by:?}, {fn_decl}, {body_id}, _, {movability})");
479                 out!("if let {ret_ty} = {fn_decl}.output;");
480                 self.body(body_id);
481             },
482             ExprKind::Yield(sub, source) => {
483                 bind!(self, sub);
484                 kind!("Yield(sub, YieldSource::{source:?})");
485                 self.expr(sub);
486             },
487             ExprKind::Block(block, label) => {
488                 bind!(self, block);
489                 opt_bind!(self, label);
490                 kind!("Block({block}, {label})");
491                 self.block(block);
492                 label.if_some(|l| self.ident(field!(l.ident)));
493             },
494             ExprKind::Assign(target, value, _) => {
495                 bind!(self, target, value);
496                 kind!("Assign({target}, {value}, _span)");
497                 self.expr(target);
498                 self.expr(value);
499             },
500             ExprKind::AssignOp(op, target, value) => {
501                 bind!(self, op, target, value);
502                 kind!("AssignOp({op}, {target}, {value})");
503                 out!("if BinOpKind::{:?} == {op}.node;", op.value.node);
504                 self.expr(target);
505                 self.expr(value);
506             },
507             ExprKind::Field(object, field_name) => {
508                 bind!(self, object, field_name);
509                 kind!("Field({object}, {field_name})");
510                 self.ident(field_name);
511                 self.expr(object);
512             },
513             ExprKind::Index(object, index) => {
514                 bind!(self, object, index);
515                 kind!("Index({object}, {index})");
516                 self.expr(object);
517                 self.expr(index);
518             },
519             ExprKind::Path(ref qpath) => {
520                 bind!(self, qpath);
521                 kind!("Path(ref {qpath})");
522                 self.qpath(qpath);
523             },
524             ExprKind::AddrOf(kind, mutability, inner) => {
525                 bind!(self, inner);
526                 kind!("AddrOf(BorrowKind::{kind:?}, Mutability::{mutability:?}, {inner})");
527                 self.expr(inner);
528             },
529             ExprKind::Break(destination, value) => {
530                 bind!(self, destination);
531                 opt_bind!(self, value);
532                 kind!("Break({destination}, {value})");
533                 self.destination(destination);
534                 value.if_some(|e| self.expr(e));
535             },
536             ExprKind::Continue(destination) => {
537                 bind!(self, destination);
538                 kind!("Continue({destination})");
539                 self.destination(destination);
540             },
541             ExprKind::Ret(value) => {
542                 opt_bind!(self, value);
543                 kind!("Ret({value})");
544                 value.if_some(|e| self.expr(e));
545             },
546             ExprKind::InlineAsm(_) => {
547                 kind!("InlineAsm(_)");
548                 out!("// unimplemented: `ExprKind::InlineAsm` is not further destructured at the moment");
549             },
550             ExprKind::Struct(qpath, fields, base) => {
551                 bind!(self, qpath, fields);
552                 opt_bind!(self, base);
553                 kind!("Struct({qpath}, {fields}, {base})");
554                 self.qpath(qpath);
555                 self.slice(fields, |field| {
556                     self.ident(field!(field.ident));
557                     self.expr(field!(field.expr));
558                 });
559                 base.if_some(|e| self.expr(e));
560             },
561             ExprKind::ConstBlock(_) => kind!("ConstBlock(_)"),
562             ExprKind::Repeat(value, length) => {
563                 bind!(self, value, length);
564                 kind!("Repeat({value}, {length})");
565                 self.expr(value);
566                 match length.value {
567                     ArrayLen::Infer(..) => out!("if let ArrayLen::Infer(..) = length;"),
568                     ArrayLen::Body(anon_const) => {
569                         bind!(self, anon_const);
570                         out!("if let ArrayLen::Body({anon_const}) = {length};");
571                         self.body(field!(anon_const.body));
572                     },
573                 }
574             },
575             ExprKind::Err => kind!("Err"),
576             ExprKind::DropTemps(expr) => {
577                 bind!(self, expr);
578                 kind!("DropTemps({expr})");
579                 self.expr(expr);
580             },
581         }
582     }
583
584     fn block(&self, block: &Binding<&hir::Block<'_>>) {
585         self.slice(field!(block.stmts), |stmt| self.stmt(stmt));
586         self.option(field!(block.expr), "trailing_expr", |expr| {
587             self.expr(expr);
588         });
589     }
590
591     fn body(&self, body_id: &Binding<hir::BodyId>) {
592         let expr = &self.cx.tcx.hir().body(body_id.value).value;
593         bind!(self, expr);
594         out!("let {expr} = &cx.tcx.hir().body({body_id}).value;");
595         self.expr(expr);
596     }
597
598     fn pat(&self, pat: &Binding<&hir::Pat<'_>>) {
599         let kind = |kind| out!("if let PatKind::{kind} = {pat}.kind;");
600         macro_rules! kind {
601             ($($t:tt)*) => (kind(format_args!($($t)*)));
602         }
603
604         match pat.value.kind {
605             PatKind::Wild => kind!("Wild"),
606             PatKind::Binding(anno, .., name, sub) => {
607                 bind!(self, name);
608                 opt_bind!(self, sub);
609                 kind!("Binding(BindingAnnotation::{anno:?}, _, {name}, {sub})");
610                 self.ident(name);
611                 sub.if_some(|p| self.pat(p));
612             },
613             PatKind::Struct(ref qpath, fields, ignore) => {
614                 bind!(self, qpath, fields);
615                 kind!("Struct(ref {qpath}, {fields}, {ignore})");
616                 self.qpath(qpath);
617                 self.slice(fields, |field| {
618                     self.ident(field!(field.ident));
619                     self.pat(field!(field.pat));
620                 });
621             },
622             PatKind::Or(fields) => {
623                 bind!(self, fields);
624                 kind!("Or({fields})");
625                 self.slice(fields, |pat| self.pat(pat));
626             },
627             PatKind::TupleStruct(ref qpath, fields, skip_pos) => {
628                 bind!(self, qpath, fields);
629                 kind!("TupleStruct(ref {qpath}, {fields}, {skip_pos:?})");
630                 self.qpath(qpath);
631                 self.slice(fields, |pat| self.pat(pat));
632             },
633             PatKind::Path(ref qpath) => {
634                 bind!(self, qpath);
635                 kind!("Path(ref {qpath})");
636                 self.qpath(qpath);
637             },
638             PatKind::Tuple(fields, skip_pos) => {
639                 bind!(self, fields);
640                 kind!("Tuple({fields}, {skip_pos:?})");
641                 self.slice(fields, |field| self.pat(field));
642             },
643             PatKind::Box(pat) => {
644                 bind!(self, pat);
645                 kind!("Box({pat})");
646                 self.pat(pat);
647             },
648             PatKind::Ref(pat, muta) => {
649                 bind!(self, pat);
650                 kind!("Ref({pat}, Mutability::{muta:?})");
651                 self.pat(pat);
652             },
653             PatKind::Lit(lit_expr) => {
654                 bind!(self, lit_expr);
655                 kind!("Lit({lit_expr})");
656                 self.expr(lit_expr);
657             },
658             PatKind::Range(start, end, end_kind) => {
659                 opt_bind!(self, start, end);
660                 kind!("Range({start}, {end}, RangeEnd::{end_kind:?})");
661                 start.if_some(|e| self.expr(e));
662                 end.if_some(|e| self.expr(e));
663             },
664             PatKind::Slice(start, middle, end) => {
665                 bind!(self, start, end);
666                 opt_bind!(self, middle);
667                 kind!("Slice({start}, {middle}, {end})");
668                 middle.if_some(|p| self.pat(p));
669                 self.slice(start, |pat| self.pat(pat));
670                 self.slice(end, |pat| self.pat(pat));
671             },
672         }
673     }
674
675     fn stmt(&self, stmt: &Binding<&hir::Stmt<'_>>) {
676         let kind = |kind| out!("if let StmtKind::{kind} = {stmt}.kind;");
677         macro_rules! kind {
678             ($($t:tt)*) => (kind(format_args!($($t)*)));
679         }
680
681         match stmt.value.kind {
682             StmtKind::Local(local) => {
683                 bind!(self, local);
684                 kind!("Local({local})");
685                 self.option(field!(local.init), "init", |init| {
686                     self.expr(init);
687                 });
688                 self.pat(field!(local.pat));
689             },
690             StmtKind::Item(_) => kind!("Item(item_id)"),
691             StmtKind::Expr(e) => {
692                 bind!(self, e);
693                 kind!("Expr({e})");
694                 self.expr(e);
695             },
696             StmtKind::Semi(e) => {
697                 bind!(self, e);
698                 kind!("Semi({e})");
699                 self.expr(e);
700             },
701         }
702     }
703 }
704
705 fn has_attr(cx: &LateContext<'_>, hir_id: hir::HirId) -> bool {
706     let attrs = cx.tcx.hir().attrs(hir_id);
707     get_attr(cx.sess(), attrs, "author").count() > 0
708 }
709
710 fn path_to_string(path: &QPath<'_>) -> String {
711     fn inner(s: &mut String, path: &QPath<'_>) {
712         match *path {
713             QPath::Resolved(_, path) => {
714                 for (i, segment) in path.segments.iter().enumerate() {
715                     if i > 0 {
716                         *s += ", ";
717                     }
718                     write!(s, "{:?}", segment.ident.as_str()).unwrap();
719                 }
720             },
721             QPath::TypeRelative(ty, segment) => match &ty.kind {
722                 hir::TyKind::Path(inner_path) => {
723                     inner(s, inner_path);
724                     *s += ", ";
725                     write!(s, "{:?}", segment.ident.as_str()).unwrap();
726                 },
727                 other => write!(s, "/* unimplemented: {:?}*/", other).unwrap(),
728             },
729             QPath::LangItem(..) => panic!("path_to_string: called for lang item qpath"),
730         }
731     }
732     let mut s = String::new();
733     inner(&mut s, path);
734     s
735 }