1 //! A group of attributes that can be attached to Rust code in order
2 //! to generate a clippy lint detecting said code automatically.
4 #![allow(print_stdout, use_debug)]
8 use rustc::hir::{Expr, ExprKind, QPath, TyKind, Pat, PatKind, BindingAnnotation, StmtKind, DeclKind, Stmt};
9 use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
10 use syntax::ast::{Attribute, LitKind, DUMMY_NODE_ID};
11 use std::collections::HashMap;
12 use crate::utils::get_attr;
14 /// **What it does:** Generates clippy code that detects the offending pattern
18 /// // ./tests/ui/my_lint.rs
20 /// // detect the following pattern
23 /// // but ignore everything from here on
24 /// #![clippy::author = "ignore"]
29 /// Running `TESTNAME=ui/my_lint cargo test --test compile-test` will produce
30 /// a `./tests/ui/new_lint.stdout` file with the generated code:
33 /// // ./tests/ui/new_lint.stdout
35 /// if let ExprKind::If(ref cond, ref then, None) = item.node,
36 /// if let ExprKind::Binary(BinOp::Eq, ref left, ref right) = cond.node,
37 /// if let ExprKind::Path(ref path) = left.node,
38 /// if let ExprKind::Lit(ref lit) = right.node,
39 /// if let LitKind::Int(42, _) = lit.node,
41 /// // report your lint here
45 declare_clippy_lint! {
48 "helper for writing lints"
53 impl LintPass for Pass {
54 fn get_lints(&self) -> LintArray {
55 lint_array!(LINT_AUTHOR)
60 println!("if_chain! {{");
65 println!(" // report your lint here");
70 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
71 fn check_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
72 if !has_attr(&item.attrs) {
76 PrintVisitor::new("item").visit_item(item);
80 fn check_impl_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem) {
81 if !has_attr(&item.attrs) {
85 PrintVisitor::new("item").visit_impl_item(item);
89 fn check_trait_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
90 if !has_attr(&item.attrs) {
94 PrintVisitor::new("item").visit_trait_item(item);
98 fn check_variant(&mut self, _cx: &LateContext<'a, 'tcx>, var: &'tcx hir::Variant, generics: &hir::Generics) {
99 if !has_attr(&var.node.attrs) {
103 PrintVisitor::new("var").visit_variant(var, generics, DUMMY_NODE_ID);
107 fn check_struct_field(&mut self, _cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField) {
108 if !has_attr(&field.attrs) {
112 PrintVisitor::new("field").visit_struct_field(field);
116 fn check_expr(&mut self, _cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
117 if !has_attr(&expr.attrs) {
121 PrintVisitor::new("expr").visit_expr(expr);
125 fn check_arm(&mut self, _cx: &LateContext<'a, 'tcx>, arm: &'tcx hir::Arm) {
126 if !has_attr(&arm.attrs) {
130 PrintVisitor::new("arm").visit_arm(arm);
134 fn check_stmt(&mut self, _cx: &LateContext<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
135 if !has_attr(stmt.node.attrs()) {
139 PrintVisitor::new("stmt").visit_stmt(stmt);
143 fn check_foreign_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ForeignItem) {
144 if !has_attr(&item.attrs) {
148 PrintVisitor::new("item").visit_foreign_item(item);
154 fn new(s: &'static str) -> Self {
157 current: s.to_owned(),
161 fn next(&mut self, s: &'static str) -> String {
162 use std::collections::hash_map::Entry::*;
163 match self.ids.entry(s) {
164 // already there: start numbering from `1`
165 Occupied(mut occ) => {
166 let val = occ.get_mut();
168 format!("{}{}", s, *val)
170 // not there: insert and return name as given
178 fn print_qpath(&mut self, path: &QPath) {
179 print!(" if match_qpath({}, &[", self.current);
180 print_path(path, &mut true);
185 struct PrintVisitor {
186 /// Fields are the current index that needs to be appended to pattern
188 ids: HashMap<&'static str, usize>,
189 /// the name that needs to be destructured
193 impl<'tcx> Visitor<'tcx> for PrintVisitor {
194 fn visit_expr(&mut self, expr: &Expr) {
195 print!(" if let ExprKind::");
196 let current = format!("{}.node", self.current);
198 ExprKind::Box(ref inner) => {
199 let inner_pat = self.next("inner");
200 println!("Box(ref {}) = {};", inner_pat, current);
201 self.current = inner_pat;
202 self.visit_expr(inner);
204 ExprKind::Array(ref elements) => {
205 let elements_pat = self.next("elements");
206 println!("Array(ref {}) = {};", elements_pat, current);
207 println!(" if {}.len() == {};", elements_pat, elements.len());
208 for (i, element) in elements.iter().enumerate() {
209 self.current = format!("{}[{}]", elements_pat, i);
210 self.visit_expr(element);
213 ExprKind::Call(ref func, ref args) => {
214 let func_pat = self.next("func");
215 let args_pat = self.next("args");
216 println!("Call(ref {}, ref {}) = {};", func_pat, args_pat, current);
217 self.current = func_pat;
218 self.visit_expr(func);
219 println!(" if {}.len() == {};", args_pat, args.len());
220 for (i, arg) in args.iter().enumerate() {
221 self.current = format!("{}[{}]", args_pat, i);
222 self.visit_expr(arg);
225 ExprKind::MethodCall(ref _method_name, ref _generics, ref _args) => {
226 println!("MethodCall(ref method_name, ref generics, ref args) = {};", current);
227 println!(" // unimplemented: `ExprKind::MethodCall` is not further destructured at the moment");
229 ExprKind::Tup(ref elements) => {
230 let elements_pat = self.next("elements");
231 println!("Tup(ref {}) = {};", elements_pat, current);
232 println!(" if {}.len() == {};", elements_pat, elements.len());
233 for (i, element) in elements.iter().enumerate() {
234 self.current = format!("{}[{}]", elements_pat, i);
235 self.visit_expr(element);
238 ExprKind::Binary(ref op, ref left, ref right) => {
239 let op_pat = self.next("op");
240 let left_pat = self.next("left");
241 let right_pat = self.next("right");
242 println!("Binary(ref {}, ref {}, ref {}) = {};", op_pat, left_pat, right_pat, current);
243 println!(" if BinOpKind::{:?} == {}.node;", op.node, op_pat);
244 self.current = left_pat;
245 self.visit_expr(left);
246 self.current = right_pat;
247 self.visit_expr(right);
249 ExprKind::Unary(ref op, ref inner) => {
250 let inner_pat = self.next("inner");
251 println!("Unary(UnOp::{:?}, ref {}) = {};", op, inner_pat, current);
252 self.current = inner_pat;
253 self.visit_expr(inner);
255 ExprKind::Lit(ref lit) => {
256 let lit_pat = self.next("lit");
257 println!("Lit(ref {}) = {};", lit_pat, current);
259 LitKind::Bool(val) => println!(" if let LitKind::Bool({:?}) = {}.node;", val, lit_pat),
260 LitKind::Char(c) => println!(" if let LitKind::Char({:?}) = {}.node;", c, lit_pat),
261 LitKind::Byte(b) => println!(" if let LitKind::Byte({}) = {}.node;", b, lit_pat),
262 // FIXME: also check int type
263 LitKind::Int(i, _) => println!(" if let LitKind::Int({}, _) = {}.node;", i, lit_pat),
264 LitKind::Float(..) => println!(" if let LitKind::Float(..) = {}.node;", lit_pat),
265 LitKind::FloatUnsuffixed(_) => {
266 println!(" if let LitKind::FloatUnsuffixed(_) = {}.node;", lit_pat)
268 LitKind::ByteStr(ref vec) => {
269 let vec_pat = self.next("vec");
270 println!(" if let LitKind::ByteStr(ref {}) = {}.node;", vec_pat, lit_pat);
271 println!(" if let [{:?}] = **{};", vec, vec_pat);
273 LitKind::Str(ref text, _) => {
274 let str_pat = self.next("s");
275 println!(" if let LitKind::Str(ref {}) = {}.node;", str_pat, lit_pat);
276 println!(" if {}.as_str() == {:?}", str_pat, &*text.as_str())
280 ExprKind::Cast(ref expr, ref ty) => {
281 let cast_pat = self.next("expr");
282 let cast_ty = self.next("cast_ty");
283 let qp_label = self.next("qp");
285 println!("Cast(ref {}, ref {}) = {};", cast_pat, cast_ty, current);
286 if let TyKind::Path(ref qp) = ty.node {
287 println!(" if let TyKind::Path(ref {}) = {}.node;", qp_label, cast_ty);
288 self.current = qp_label;
289 self.print_qpath(qp);
291 self.current = cast_pat;
292 self.visit_expr(expr);
294 ExprKind::Type(ref expr, ref _ty) => {
295 let cast_pat = self.next("expr");
296 println!("Type(ref {}, _) = {};", cast_pat, current);
297 self.current = cast_pat;
298 self.visit_expr(expr);
300 ExprKind::If(ref cond, ref then, ref opt_else) => {
301 let cond_pat = self.next("cond");
302 let then_pat = self.next("then");
303 if let Some(ref else_) = *opt_else {
304 let else_pat = self.next("else_");
305 println!("If(ref {}, ref {}, Some(ref {})) = {};", cond_pat, then_pat, else_pat, current);
306 self.current = else_pat;
307 self.visit_expr(else_);
309 println!("If(ref {}, ref {}, None) = {};", cond_pat, then_pat, current);
311 self.current = cond_pat;
312 self.visit_expr(cond);
313 self.current = then_pat;
314 self.visit_expr(then);
316 ExprKind::While(ref cond, ref body, _) => {
317 let cond_pat = self.next("cond");
318 let body_pat = self.next("body");
319 let label_pat = self.next("label");
320 println!("While(ref {}, ref {}, ref {}) = {};", cond_pat, body_pat, label_pat, current);
321 self.current = cond_pat;
322 self.visit_expr(cond);
323 self.current = body_pat;
324 self.visit_block(body);
326 ExprKind::Loop(ref body, _, desugaring) => {
327 let body_pat = self.next("body");
328 let des = loop_desugaring_name(desugaring);
329 let label_pat = self.next("label");
330 println!("Loop(ref {}, ref {}, {}) = {};", body_pat, label_pat, des, current);
331 self.current = body_pat;
332 self.visit_block(body);
334 ExprKind::Match(ref expr, ref arms, desugaring) => {
335 let des = desugaring_name(desugaring);
336 let expr_pat = self.next("expr");
337 let arms_pat = self.next("arms");
338 println!("Match(ref {}, ref {}, {}) = {};", expr_pat, arms_pat, des, current);
339 self.current = expr_pat;
340 self.visit_expr(expr);
341 println!(" if {}.len() == {};", arms_pat, arms.len());
342 for (i, arm) in arms.iter().enumerate() {
343 self.current = format!("{}[{}].body", arms_pat, i);
344 self.visit_expr(&arm.body);
345 if let Some(ref guard) = arm.guard {
346 let guard_pat = self.next("guard");
347 println!(" if let Some(ref {}) = {}[{}].guard", guard_pat, arms_pat, i);
348 self.current = guard_pat;
349 self.visit_expr(guard);
351 println!(" if {}[{}].pats.len() == {};", arms_pat, i, arm.pats.len());
352 for (j, pat) in arm.pats.iter().enumerate() {
353 self.current = format!("{}[{}].pats[{}]", arms_pat, i, j);
358 ExprKind::Closure(ref _capture_clause, ref _func, _, _, _) => {
359 println!("Closure(ref capture_clause, ref func, _, _, _) = {};", current);
360 println!(" // unimplemented: `ExprKind::Closure` is not further destructured at the moment");
362 ExprKind::Yield(ref sub) => {
363 let sub_pat = self.next("sub");
364 println!("Yield(ref sub) = {};", current);
365 self.current = sub_pat;
366 self.visit_expr(sub);
368 ExprKind::Block(ref block, _) => {
369 let block_pat = self.next("block");
370 println!("Block(ref {}) = {};", block_pat, current);
371 self.current = block_pat;
372 self.visit_block(block);
374 ExprKind::Assign(ref target, ref value) => {
375 let target_pat = self.next("target");
376 let value_pat = self.next("value");
377 println!("Assign(ref {}, ref {}) = {};", target_pat, value_pat, current);
378 self.current = target_pat;
379 self.visit_expr(target);
380 self.current = value_pat;
381 self.visit_expr(value);
383 ExprKind::AssignOp(ref op, ref target, ref value) => {
384 let op_pat = self.next("op");
385 let target_pat = self.next("target");
386 let value_pat = self.next("value");
387 println!("AssignOp(ref {}, ref {}, ref {}) = {};", op_pat, target_pat, value_pat, current);
388 println!(" if BinOpKind::{:?} == {}.node;", op.node, op_pat);
389 self.current = target_pat;
390 self.visit_expr(target);
391 self.current = value_pat;
392 self.visit_expr(value);
394 ExprKind::Field(ref object, ref field_ident) => {
395 let obj_pat = self.next("object");
396 let field_name_pat = self.next("field_name");
397 println!("Field(ref {}, ref {}) = {};", obj_pat, field_name_pat, current);
398 println!(" if {}.node.as_str() == {:?}", field_name_pat, field_ident.as_str());
399 self.current = obj_pat;
400 self.visit_expr(object);
402 ExprKind::Index(ref object, ref index) => {
403 let object_pat = self.next("object");
404 let index_pat = self.next("index");
405 println!("Index(ref {}, ref {}) = {};", object_pat, index_pat, current);
406 self.current = object_pat;
407 self.visit_expr(object);
408 self.current = index_pat;
409 self.visit_expr(index);
411 ExprKind::Path(ref path) => {
412 let path_pat = self.next("path");
413 println!("Path(ref {}) = {};", path_pat, current);
414 self.current = path_pat;
415 self.print_qpath(path);
417 ExprKind::AddrOf(mutability, ref inner) => {
418 let inner_pat = self.next("inner");
419 println!("AddrOf({:?}, ref {}) = {};", mutability, inner_pat, current);
420 self.current = inner_pat;
421 self.visit_expr(inner);
423 ExprKind::Break(ref _destination, ref opt_value) => {
424 let destination_pat = self.next("destination");
425 if let Some(ref value) = *opt_value {
426 let value_pat = self.next("value");
427 println!("Break(ref {}, Some(ref {})) = {};", destination_pat, value_pat, current);
428 self.current = value_pat;
429 self.visit_expr(value);
431 println!("Break(ref {}, None) = {};", destination_pat, current);
433 // FIXME: implement label printing
435 ExprKind::Continue(ref _destination) => {
436 let destination_pat = self.next("destination");
437 println!("Again(ref {}) = {};", destination_pat, current);
438 // FIXME: implement label printing
440 ExprKind::Ret(ref opt_value) => if let Some(ref value) = *opt_value {
441 let value_pat = self.next("value");
442 println!("Ret(Some(ref {})) = {};", value_pat, current);
443 self.current = value_pat;
444 self.visit_expr(value);
446 println!("Ret(None) = {};", current);
448 ExprKind::InlineAsm(_, ref _input, ref _output) => {
449 println!("InlineAsm(_, ref input, ref output) = {};", current);
450 println!(" // unimplemented: `ExprKind::InlineAsm` is not further destructured at the moment");
452 ExprKind::Struct(ref path, ref fields, ref opt_base) => {
453 let path_pat = self.next("path");
454 let fields_pat = self.next("fields");
455 if let Some(ref base) = *opt_base {
456 let base_pat = self.next("base");
458 "Struct(ref {}, ref {}, Some(ref {})) = {};",
464 self.current = base_pat;
465 self.visit_expr(base);
467 println!("Struct(ref {}, ref {}, None) = {};", path_pat, fields_pat, current);
469 self.current = path_pat;
470 self.print_qpath(path);
471 println!(" if {}.len() == {};", fields_pat, fields.len());
472 println!(" // unimplemented: field checks");
474 // FIXME: compute length (needs type info)
475 ExprKind::Repeat(ref value, _) => {
476 let value_pat = self.next("value");
477 println!("Repeat(ref {}, _) = {};", value_pat, current);
478 println!("// unimplemented: repeat count check");
479 self.current = value_pat;
480 self.visit_expr(value);
485 fn visit_pat(&mut self, pat: &Pat) {
486 print!(" if let PatKind::");
487 let current = format!("{}.node", self.current);
489 PatKind::Wild => println!("Wild = {};", current),
490 PatKind::Binding(anno, _, ident, ref sub) => {
491 let anno_pat = match anno {
492 BindingAnnotation::Unannotated => "BindingAnnotation::Unannotated",
493 BindingAnnotation::Mutable => "BindingAnnotation::Mutable",
494 BindingAnnotation::Ref => "BindingAnnotation::Ref",
495 BindingAnnotation::RefMut => "BindingAnnotation::RefMut",
497 let name_pat = self.next("name");
498 if let Some(ref sub) = *sub {
499 let sub_pat = self.next("sub");
500 println!("Binding({}, _, {}, Some(ref {})) = {};", anno_pat, name_pat, sub_pat, current);
501 self.current = sub_pat;
504 println!("Binding({}, _, {}, None) = {};", anno_pat, name_pat, current);
506 println!(" if {}.node.as_str() == \"{}\";", name_pat, ident.as_str());
508 PatKind::Struct(ref path, ref fields, ignore) => {
509 let path_pat = self.next("path");
510 let fields_pat = self.next("fields");
511 println!("Struct(ref {}, ref {}, {}) = {};", path_pat, fields_pat, ignore, current);
512 self.current = path_pat;
513 self.print_qpath(path);
514 println!(" if {}.len() == {};", fields_pat, fields.len());
515 println!(" // unimplemented: field checks");
517 PatKind::TupleStruct(ref path, ref fields, skip_pos) => {
518 let path_pat = self.next("path");
519 let fields_pat = self.next("fields");
520 println!("TupleStruct(ref {}, ref {}, {:?}) = {};", path_pat, fields_pat, skip_pos, current);
521 self.current = path_pat;
522 self.print_qpath(path);
523 println!(" if {}.len() == {};", fields_pat, fields.len());
524 println!(" // unimplemented: field checks");
526 PatKind::Path(ref path) => {
527 let path_pat = self.next("path");
528 println!("Path(ref {}) = {};", path_pat, current);
529 self.current = path_pat;
530 self.print_qpath(path);
532 PatKind::Tuple(ref fields, skip_pos) => {
533 let fields_pat = self.next("fields");
534 println!("Tuple(ref {}, {:?}) = {};", fields_pat, skip_pos, current);
535 println!(" if {}.len() == {};", fields_pat, fields.len());
536 println!(" // unimplemented: field checks");
538 PatKind::Box(ref pat) => {
539 let pat_pat = self.next("pat");
540 println!("Box(ref {}) = {};", pat_pat, current);
541 self.current = pat_pat;
544 PatKind::Ref(ref pat, muta) => {
545 let pat_pat = self.next("pat");
546 println!("Ref(ref {}, Mutability::{:?}) = {};", pat_pat, muta, current);
547 self.current = pat_pat;
550 PatKind::Lit(ref lit_expr) => {
551 let lit_expr_pat = self.next("lit_expr");
552 println!("Lit(ref {}) = {}", lit_expr_pat, current);
553 self.current = lit_expr_pat;
554 self.visit_expr(lit_expr);
556 PatKind::Range(ref start, ref end, end_kind) => {
557 let start_pat = self.next("start");
558 let end_pat = self.next("end");
559 println!("Range(ref {}, ref {}, RangeEnd::{:?}) = {};", start_pat, end_pat, end_kind, current);
560 self.current = start_pat;
561 self.visit_expr(start);
562 self.current = end_pat;
563 self.visit_expr(end);
565 PatKind::Slice(ref start, ref middle, ref end) => {
566 let start_pat = self.next("start");
567 let end_pat = self.next("end");
568 if let Some(ref middle) = middle {
569 let middle_pat = self.next("middle");
570 println!("Slice(ref {}, Some(ref {}), ref {}) = {};", start_pat, middle_pat, end_pat, current);
571 self.current = middle_pat;
572 self.visit_pat(middle);
574 println!("Slice(ref {}, None, ref {}) = {};", start_pat, end_pat, current);
576 println!(" if {}.len() == {};", start_pat, start.len());
577 for (i, pat) in start.iter().enumerate() {
578 self.current = format!("{}[{}]", start_pat, i);
581 println!(" if {}.len() == {};", end_pat, end.len());
582 for (i, pat) in end.iter().enumerate() {
583 self.current = format!("{}[{}]", end_pat, i);
590 fn visit_stmt(&mut self, s: &Stmt) {
591 print!(" if let StmtKind::");
592 let current = format!("{}.node", self.current);
594 // Could be an item or a local (let) binding:
595 StmtKind::Decl(ref decl, _) => {
596 let decl_pat = self.next("decl");
597 println!("Decl(ref {}, _) = {}", decl_pat, current);
598 print!(" if let DeclKind::");
599 let current = format!("{}.node", decl_pat);
601 // A local (let) binding:
602 DeclKind::Local(ref local) => {
603 let local_pat = self.next("local");
604 println!("Local(ref {}) = {};", local_pat, current);
605 if let Some(ref init) = local.init {
606 let init_pat = self.next("init");
607 println!(" if let Some(ref {}) = {}.init", init_pat, local_pat);
608 self.current = init_pat;
609 self.visit_expr(init);
611 self.current = format!("{}.pat", local_pat);
612 self.visit_pat(&local.pat);
615 DeclKind::Item(_) => {
616 println!("Item(item_id) = {};", current);
621 // Expr without trailing semi-colon (must have unit type):
622 StmtKind::Expr(ref e, _) => {
623 let e_pat = self.next("e");
624 println!("Expr(ref {}, _) = {}", e_pat, current);
625 self.current = e_pat;
629 // Expr with trailing semi-colon (may have any type):
630 StmtKind::Semi(ref e, _) => {
631 let e_pat = self.next("e");
632 println!("Semi(ref {}, _) = {}", e_pat, current);
633 self.current = e_pat;
639 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
640 NestedVisitorMap::None
644 fn has_attr(attrs: &[Attribute]) -> bool {
645 get_attr(attrs, "author").count() > 0
648 fn desugaring_name(des: hir::MatchSource) -> String {
650 hir::MatchSource::ForLoopDesugar => "MatchSource::ForLoopDesugar".to_string(),
651 hir::MatchSource::TryDesugar => "MatchSource::TryDesugar".to_string(),
652 hir::MatchSource::WhileLetDesugar => "MatchSource::WhileLetDesugar".to_string(),
653 hir::MatchSource::Normal => "MatchSource::Normal".to_string(),
654 hir::MatchSource::IfLetDesugar { contains_else_clause } => format!("MatchSource::IfLetDesugar {{ contains_else_clause: {} }}", contains_else_clause),
658 fn loop_desugaring_name(des: hir::LoopSource) -> &'static str {
660 hir::LoopSource::ForLoop => "LoopSource::ForLoop",
661 hir::LoopSource::Loop => "LoopSource::Loop",
662 hir::LoopSource::WhileLet => "LoopSource::WhileLet",
666 fn print_path(path: &QPath, first: &mut bool) {
668 QPath::Resolved(_, ref path) => for segment in &path.segments {
674 print!("{:?}", segment.ident.as_str());
676 QPath::TypeRelative(ref ty, ref segment) => match ty.node {
677 hir::TyKind::Path(ref inner_path) => {
678 print_path(inner_path, first);
684 print!("{:?}", segment.ident.as_str());
686 ref other => print!("/* unimplemented: {:?}*/", other),