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 use crate::utils::get_attr;
6 use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
7 use rustc::hir::{BindingAnnotation, Expr, ExprKind, Pat, PatKind, QPath, Stmt, StmtKind, TyKind};
8 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
9 use rustc::{declare_tool_lint, lint_array};
10 use rustc_data_structures::fx::FxHashMap;
11 use syntax::ast::{Attribute, LitKind};
13 /// **What it does:** Generates clippy code that detects the offending pattern
17 /// // ./tests/ui/my_lint.rs
19 /// // detect the following pattern
22 /// // but ignore everything from here on
23 /// #![clippy::author = "ignore"]
28 /// Running `TESTNAME=ui/my_lint cargo uitest` will produce
29 /// a `./tests/ui/new_lint.stdout` file with the generated code:
32 /// // ./tests/ui/new_lint.stdout
34 /// if let ExprKind::If(ref cond, ref then, None) = item.node,
35 /// if let ExprKind::Binary(BinOp::Eq, ref left, ref right) = cond.node,
36 /// if let ExprKind::Path(ref path) = left.node,
37 /// if let ExprKind::Lit(ref lit) = right.node,
38 /// if let LitKind::Int(42, _) = lit.node,
40 /// // report your lint here
44 declare_clippy_lint! {
47 "helper for writing lints"
52 impl LintPass for Pass {
53 fn get_lints(&self) -> LintArray {
54 lint_array!(LINT_AUTHOR)
57 fn name(&self) -> &'static str {
63 println!("if_chain! {{");
68 println!(" // report your lint here");
73 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
74 fn check_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
75 if !has_attr(&item.attrs) {
79 PrintVisitor::new("item").visit_item(item);
83 fn check_impl_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem) {
84 if !has_attr(&item.attrs) {
88 PrintVisitor::new("item").visit_impl_item(item);
92 fn check_trait_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
93 if !has_attr(&item.attrs) {
97 PrintVisitor::new("item").visit_trait_item(item);
101 fn check_variant(&mut self, _cx: &LateContext<'a, 'tcx>, var: &'tcx hir::Variant, generics: &hir::Generics) {
102 if !has_attr(&var.node.attrs) {
106 PrintVisitor::new("var").visit_variant(var, generics, hir::DUMMY_HIR_ID);
110 fn check_struct_field(&mut self, _cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField) {
111 if !has_attr(&field.attrs) {
115 PrintVisitor::new("field").visit_struct_field(field);
119 fn check_expr(&mut self, _cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
120 if !has_attr(&expr.attrs) {
124 PrintVisitor::new("expr").visit_expr(expr);
128 fn check_arm(&mut self, _cx: &LateContext<'a, 'tcx>, arm: &'tcx hir::Arm) {
129 if !has_attr(&arm.attrs) {
133 PrintVisitor::new("arm").visit_arm(arm);
137 fn check_stmt(&mut self, _cx: &LateContext<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
138 if !has_attr(stmt.node.attrs()) {
142 PrintVisitor::new("stmt").visit_stmt(stmt);
146 fn check_foreign_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ForeignItem) {
147 if !has_attr(&item.attrs) {
151 PrintVisitor::new("item").visit_foreign_item(item);
157 fn new(s: &'static str) -> Self {
159 ids: FxHashMap::default(),
160 current: s.to_owned(),
164 fn next(&mut self, s: &'static str) -> String {
165 use std::collections::hash_map::Entry::*;
166 match self.ids.entry(s) {
167 // already there: start numbering from `1`
168 Occupied(mut occ) => {
169 let val = occ.get_mut();
171 format!("{}{}", s, *val)
173 // not there: insert and return name as given
181 fn print_qpath(&mut self, path: &QPath) {
182 print!(" if match_qpath({}, &[", self.current);
183 print_path(path, &mut true);
188 struct PrintVisitor {
189 /// Fields are the current index that needs to be appended to pattern
191 ids: FxHashMap<&'static str, usize>,
192 /// the name that needs to be destructured
196 impl<'tcx> Visitor<'tcx> for PrintVisitor {
197 #[allow(clippy::too_many_lines)]
198 fn visit_expr(&mut self, expr: &Expr) {
199 print!(" if let ExprKind::");
200 let current = format!("{}.node", self.current);
202 ExprKind::Box(ref inner) => {
203 let inner_pat = self.next("inner");
204 println!("Box(ref {}) = {};", inner_pat, current);
205 self.current = inner_pat;
206 self.visit_expr(inner);
208 ExprKind::Array(ref elements) => {
209 let elements_pat = self.next("elements");
210 println!("Array(ref {}) = {};", elements_pat, current);
211 println!(" if {}.len() == {};", elements_pat, elements.len());
212 for (i, element) in elements.iter().enumerate() {
213 self.current = format!("{}[{}]", elements_pat, i);
214 self.visit_expr(element);
217 ExprKind::Call(ref func, ref args) => {
218 let func_pat = self.next("func");
219 let args_pat = self.next("args");
220 println!("Call(ref {}, ref {}) = {};", func_pat, args_pat, current);
221 self.current = func_pat;
222 self.visit_expr(func);
223 println!(" if {}.len() == {};", args_pat, args.len());
224 for (i, arg) in args.iter().enumerate() {
225 self.current = format!("{}[{}]", args_pat, i);
226 self.visit_expr(arg);
229 ExprKind::MethodCall(ref _method_name, ref _generics, ref _args) => {
230 println!("MethodCall(ref method_name, ref generics, ref args) = {};", current);
231 println!(" // unimplemented: `ExprKind::MethodCall` is not further destructured at the moment");
233 ExprKind::Tup(ref elements) => {
234 let elements_pat = self.next("elements");
235 println!("Tup(ref {}) = {};", elements_pat, current);
236 println!(" if {}.len() == {};", elements_pat, elements.len());
237 for (i, element) in elements.iter().enumerate() {
238 self.current = format!("{}[{}]", elements_pat, i);
239 self.visit_expr(element);
242 ExprKind::Binary(ref op, ref left, ref right) => {
243 let op_pat = self.next("op");
244 let left_pat = self.next("left");
245 let right_pat = self.next("right");
247 "Binary(ref {}, ref {}, ref {}) = {};",
248 op_pat, left_pat, right_pat, current
250 println!(" if BinOpKind::{:?} == {}.node;", op.node, op_pat);
251 self.current = left_pat;
252 self.visit_expr(left);
253 self.current = right_pat;
254 self.visit_expr(right);
256 ExprKind::Unary(ref op, ref inner) => {
257 let inner_pat = self.next("inner");
258 println!("Unary(UnOp::{:?}, ref {}) = {};", op, inner_pat, current);
259 self.current = inner_pat;
260 self.visit_expr(inner);
262 ExprKind::Lit(ref lit) => {
263 let lit_pat = self.next("lit");
264 println!("Lit(ref {}) = {};", lit_pat, current);
266 LitKind::Bool(val) => println!(" if let LitKind::Bool({:?}) = {}.node;", val, lit_pat),
267 LitKind::Char(c) => println!(" if let LitKind::Char({:?}) = {}.node;", c, lit_pat),
268 LitKind::Err(val) => println!(" if let LitKind::Err({}) = {}.node;", val, lit_pat),
269 LitKind::Byte(b) => println!(" if let LitKind::Byte({}) = {}.node;", b, lit_pat),
270 // FIXME: also check int type
271 LitKind::Int(i, _) => println!(" if let LitKind::Int({}, _) = {}.node;", i, lit_pat),
272 LitKind::Float(..) => println!(" if let LitKind::Float(..) = {}.node;", lit_pat),
273 LitKind::FloatUnsuffixed(_) => {
274 println!(" if let LitKind::FloatUnsuffixed(_) = {}.node;", lit_pat)
276 LitKind::ByteStr(ref vec) => {
277 let vec_pat = self.next("vec");
278 println!(" if let LitKind::ByteStr(ref {}) = {}.node;", vec_pat, lit_pat);
279 println!(" if let [{:?}] = **{};", vec, vec_pat);
281 LitKind::Str(ref text, _) => {
282 let str_pat = self.next("s");
283 println!(" if let LitKind::Str(ref {}) = {}.node;", str_pat, lit_pat);
284 println!(" if {}.as_str() == {:?}", str_pat, &*text.as_str())
288 ExprKind::Cast(ref expr, ref ty) => {
289 let cast_pat = self.next("expr");
290 let cast_ty = self.next("cast_ty");
291 let qp_label = self.next("qp");
293 println!("Cast(ref {}, ref {}) = {};", cast_pat, cast_ty, current);
294 if let TyKind::Path(ref qp) = ty.node {
295 println!(" if let TyKind::Path(ref {}) = {}.node;", qp_label, cast_ty);
296 self.current = qp_label;
297 self.print_qpath(qp);
299 self.current = cast_pat;
300 self.visit_expr(expr);
302 ExprKind::Type(ref expr, ref _ty) => {
303 let cast_pat = self.next("expr");
304 println!("Type(ref {}, _) = {};", cast_pat, current);
305 self.current = cast_pat;
306 self.visit_expr(expr);
308 ExprKind::If(ref cond, ref then, ref opt_else) => {
309 let cond_pat = self.next("cond");
310 let then_pat = self.next("then");
311 if let Some(ref else_) = *opt_else {
312 let else_pat = self.next("else_");
314 "If(ref {}, ref {}, Some(ref {})) = {};",
315 cond_pat, then_pat, else_pat, current
317 self.current = else_pat;
318 self.visit_expr(else_);
320 println!("If(ref {}, ref {}, None) = {};", cond_pat, then_pat, current);
322 self.current = cond_pat;
323 self.visit_expr(cond);
324 self.current = then_pat;
325 self.visit_expr(then);
327 ExprKind::While(ref cond, ref body, _) => {
328 let cond_pat = self.next("cond");
329 let body_pat = self.next("body");
330 let label_pat = self.next("label");
332 "While(ref {}, ref {}, ref {}) = {};",
333 cond_pat, body_pat, label_pat, current
335 self.current = cond_pat;
336 self.visit_expr(cond);
337 self.current = body_pat;
338 self.visit_block(body);
340 ExprKind::Loop(ref body, _, desugaring) => {
341 let body_pat = self.next("body");
342 let des = loop_desugaring_name(desugaring);
343 let label_pat = self.next("label");
344 println!("Loop(ref {}, ref {}, {}) = {};", body_pat, label_pat, des, current);
345 self.current = body_pat;
346 self.visit_block(body);
348 ExprKind::Match(ref expr, ref arms, desugaring) => {
349 let des = desugaring_name(desugaring);
350 let expr_pat = self.next("expr");
351 let arms_pat = self.next("arms");
352 println!("Match(ref {}, ref {}, {}) = {};", expr_pat, arms_pat, des, current);
353 self.current = expr_pat;
354 self.visit_expr(expr);
355 println!(" if {}.len() == {};", arms_pat, arms.len());
356 for (i, arm) in arms.iter().enumerate() {
357 self.current = format!("{}[{}].body", arms_pat, i);
358 self.visit_expr(&arm.body);
359 if let Some(ref guard) = arm.guard {
360 let guard_pat = self.next("guard");
361 println!(" if let Some(ref {}) = {}[{}].guard;", guard_pat, arms_pat, i);
363 hir::Guard::If(ref if_expr) => {
364 let if_expr_pat = self.next("expr");
365 println!(" if let Guard::If(ref {}) = {};", if_expr_pat, guard_pat);
366 self.current = if_expr_pat;
367 self.visit_expr(if_expr);
371 println!(" if {}[{}].pats.len() == {};", arms_pat, i, arm.pats.len());
372 for (j, pat) in arm.pats.iter().enumerate() {
373 self.current = format!("{}[{}].pats[{}]", arms_pat, i, j);
378 ExprKind::Closure(ref _capture_clause, ref _func, _, _, _) => {
379 println!("Closure(ref capture_clause, ref func, _, _, _) = {};", current);
380 println!(" // unimplemented: `ExprKind::Closure` is not further destructured at the moment");
382 ExprKind::Yield(ref sub) => {
383 let sub_pat = self.next("sub");
384 println!("Yield(ref sub) = {};", current);
385 self.current = sub_pat;
386 self.visit_expr(sub);
388 ExprKind::Block(ref block, _) => {
389 let block_pat = self.next("block");
390 println!("Block(ref {}) = {};", block_pat, current);
391 self.current = block_pat;
392 self.visit_block(block);
394 ExprKind::Assign(ref target, ref value) => {
395 let target_pat = self.next("target");
396 let value_pat = self.next("value");
397 println!("Assign(ref {}, ref {}) = {};", target_pat, value_pat, current);
398 self.current = target_pat;
399 self.visit_expr(target);
400 self.current = value_pat;
401 self.visit_expr(value);
403 ExprKind::AssignOp(ref op, ref target, ref value) => {
404 let op_pat = self.next("op");
405 let target_pat = self.next("target");
406 let value_pat = self.next("value");
408 "AssignOp(ref {}, ref {}, ref {}) = {};",
409 op_pat, target_pat, value_pat, current
411 println!(" if BinOpKind::{:?} == {}.node;", op.node, op_pat);
412 self.current = target_pat;
413 self.visit_expr(target);
414 self.current = value_pat;
415 self.visit_expr(value);
417 ExprKind::Field(ref object, ref field_ident) => {
418 let obj_pat = self.next("object");
419 let field_name_pat = self.next("field_name");
420 println!("Field(ref {}, ref {}) = {};", obj_pat, field_name_pat, current);
421 println!(" if {}.node.as_str() == {:?}", field_name_pat, field_ident.as_str());
422 self.current = obj_pat;
423 self.visit_expr(object);
425 ExprKind::Index(ref object, ref index) => {
426 let object_pat = self.next("object");
427 let index_pat = self.next("index");
428 println!("Index(ref {}, ref {}) = {};", object_pat, index_pat, current);
429 self.current = object_pat;
430 self.visit_expr(object);
431 self.current = index_pat;
432 self.visit_expr(index);
434 ExprKind::Path(ref path) => {
435 let path_pat = self.next("path");
436 println!("Path(ref {}) = {};", path_pat, current);
437 self.current = path_pat;
438 self.print_qpath(path);
440 ExprKind::AddrOf(mutability, ref inner) => {
441 let inner_pat = self.next("inner");
442 println!("AddrOf({:?}, ref {}) = {};", mutability, inner_pat, current);
443 self.current = inner_pat;
444 self.visit_expr(inner);
446 ExprKind::Break(ref _destination, ref opt_value) => {
447 let destination_pat = self.next("destination");
448 if let Some(ref value) = *opt_value {
449 let value_pat = self.next("value");
450 println!("Break(ref {}, Some(ref {})) = {};", destination_pat, value_pat, current);
451 self.current = value_pat;
452 self.visit_expr(value);
454 println!("Break(ref {}, None) = {};", destination_pat, current);
456 // FIXME: implement label printing
458 ExprKind::Continue(ref _destination) => {
459 let destination_pat = self.next("destination");
460 println!("Again(ref {}) = {};", destination_pat, current);
461 // FIXME: implement label printing
463 ExprKind::Ret(ref opt_value) => {
464 if let Some(ref value) = *opt_value {
465 let value_pat = self.next("value");
466 println!("Ret(Some(ref {})) = {};", value_pat, current);
467 self.current = value_pat;
468 self.visit_expr(value);
470 println!("Ret(None) = {};", current);
473 ExprKind::InlineAsm(_, ref _input, ref _output) => {
474 println!("InlineAsm(_, ref input, ref output) = {};", current);
475 println!(" // unimplemented: `ExprKind::InlineAsm` is not further destructured at the moment");
477 ExprKind::Struct(ref path, ref fields, ref opt_base) => {
478 let path_pat = self.next("path");
479 let fields_pat = self.next("fields");
480 if let Some(ref base) = *opt_base {
481 let base_pat = self.next("base");
483 "Struct(ref {}, ref {}, Some(ref {})) = {};",
484 path_pat, fields_pat, base_pat, current
486 self.current = base_pat;
487 self.visit_expr(base);
489 println!("Struct(ref {}, ref {}, None) = {};", path_pat, fields_pat, current);
491 self.current = path_pat;
492 self.print_qpath(path);
493 println!(" if {}.len() == {};", fields_pat, fields.len());
494 println!(" // unimplemented: field checks");
496 // FIXME: compute length (needs type info)
497 ExprKind::Repeat(ref value, _) => {
498 let value_pat = self.next("value");
499 println!("Repeat(ref {}, _) = {};", value_pat, current);
500 println!("// unimplemented: repeat count check");
501 self.current = value_pat;
502 self.visit_expr(value);
505 println!("Err = {}", current);
510 #[allow(clippy::too_many_lines)]
511 fn visit_pat(&mut self, pat: &Pat) {
512 print!(" if let PatKind::");
513 let current = format!("{}.node", self.current);
515 PatKind::Wild => println!("Wild = {};", current),
516 PatKind::Binding(anno, .., ident, ref sub) => {
517 let anno_pat = match anno {
518 BindingAnnotation::Unannotated => "BindingAnnotation::Unannotated",
519 BindingAnnotation::Mutable => "BindingAnnotation::Mutable",
520 BindingAnnotation::Ref => "BindingAnnotation::Ref",
521 BindingAnnotation::RefMut => "BindingAnnotation::RefMut",
523 let name_pat = self.next("name");
524 if let Some(ref sub) = *sub {
525 let sub_pat = self.next("sub");
527 "Binding({}, _, {}, Some(ref {})) = {};",
528 anno_pat, name_pat, sub_pat, current
530 self.current = sub_pat;
533 println!("Binding({}, _, {}, None) = {};", anno_pat, name_pat, current);
535 println!(" if {}.node.as_str() == \"{}\";", name_pat, ident.as_str());
537 PatKind::Struct(ref path, ref fields, ignore) => {
538 let path_pat = self.next("path");
539 let fields_pat = self.next("fields");
541 "Struct(ref {}, ref {}, {}) = {};",
542 path_pat, fields_pat, ignore, current
544 self.current = path_pat;
545 self.print_qpath(path);
546 println!(" if {}.len() == {};", fields_pat, fields.len());
547 println!(" // unimplemented: field checks");
549 PatKind::TupleStruct(ref path, ref fields, skip_pos) => {
550 let path_pat = self.next("path");
551 let fields_pat = self.next("fields");
553 "TupleStruct(ref {}, ref {}, {:?}) = {};",
554 path_pat, fields_pat, skip_pos, current
556 self.current = path_pat;
557 self.print_qpath(path);
558 println!(" if {}.len() == {};", fields_pat, fields.len());
559 println!(" // unimplemented: field checks");
561 PatKind::Path(ref path) => {
562 let path_pat = self.next("path");
563 println!("Path(ref {}) = {};", path_pat, current);
564 self.current = path_pat;
565 self.print_qpath(path);
567 PatKind::Tuple(ref fields, skip_pos) => {
568 let fields_pat = self.next("fields");
569 println!("Tuple(ref {}, {:?}) = {};", fields_pat, skip_pos, current);
570 println!(" if {}.len() == {};", fields_pat, fields.len());
571 println!(" // unimplemented: field checks");
573 PatKind::Box(ref pat) => {
574 let pat_pat = self.next("pat");
575 println!("Box(ref {}) = {};", pat_pat, current);
576 self.current = pat_pat;
579 PatKind::Ref(ref pat, muta) => {
580 let pat_pat = self.next("pat");
581 println!("Ref(ref {}, Mutability::{:?}) = {};", pat_pat, muta, current);
582 self.current = pat_pat;
585 PatKind::Lit(ref lit_expr) => {
586 let lit_expr_pat = self.next("lit_expr");
587 println!("Lit(ref {}) = {}", lit_expr_pat, current);
588 self.current = lit_expr_pat;
589 self.visit_expr(lit_expr);
591 PatKind::Range(ref start, ref end, end_kind) => {
592 let start_pat = self.next("start");
593 let end_pat = self.next("end");
595 "Range(ref {}, ref {}, RangeEnd::{:?}) = {};",
596 start_pat, end_pat, end_kind, current
598 self.current = start_pat;
599 self.visit_expr(start);
600 self.current = end_pat;
601 self.visit_expr(end);
603 PatKind::Slice(ref start, ref middle, ref end) => {
604 let start_pat = self.next("start");
605 let end_pat = self.next("end");
606 if let Some(ref middle) = middle {
607 let middle_pat = self.next("middle");
609 "Slice(ref {}, Some(ref {}), ref {}) = {};",
610 start_pat, middle_pat, end_pat, current
612 self.current = middle_pat;
613 self.visit_pat(middle);
615 println!("Slice(ref {}, None, ref {}) = {};", start_pat, end_pat, current);
617 println!(" if {}.len() == {};", start_pat, start.len());
618 for (i, pat) in start.iter().enumerate() {
619 self.current = format!("{}[{}]", start_pat, i);
622 println!(" if {}.len() == {};", end_pat, end.len());
623 for (i, pat) in end.iter().enumerate() {
624 self.current = format!("{}[{}]", end_pat, i);
631 fn visit_stmt(&mut self, s: &Stmt) {
632 print!(" if let StmtKind::");
633 let current = format!("{}.node", self.current);
635 // A local (let) binding:
636 StmtKind::Local(ref local) => {
637 let local_pat = self.next("local");
638 println!("Local(ref {}) = {};", local_pat, current);
639 if let Some(ref init) = local.init {
640 let init_pat = self.next("init");
641 println!(" if let Some(ref {}) = {}.init", init_pat, local_pat);
642 self.current = init_pat;
643 self.visit_expr(init);
645 self.current = format!("{}.pat", local_pat);
646 self.visit_pat(&local.pat);
649 StmtKind::Item(_) => {
650 println!("Item(item_id) = {};", current);
653 // Expr without trailing semi-colon (must have unit type):
654 StmtKind::Expr(ref e) => {
655 let e_pat = self.next("e");
656 println!("Expr(ref {}, _) = {}", e_pat, current);
657 self.current = e_pat;
661 // Expr with trailing semi-colon (may have any type):
662 StmtKind::Semi(ref e) => {
663 let e_pat = self.next("e");
664 println!("Semi(ref {}, _) = {}", e_pat, current);
665 self.current = e_pat;
671 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
672 NestedVisitorMap::None
676 fn has_attr(attrs: &[Attribute]) -> bool {
677 get_attr(attrs, "author").count() > 0
680 fn desugaring_name(des: hir::MatchSource) -> String {
682 hir::MatchSource::ForLoopDesugar => "MatchSource::ForLoopDesugar".to_string(),
683 hir::MatchSource::TryDesugar => "MatchSource::TryDesugar".to_string(),
684 hir::MatchSource::WhileLetDesugar => "MatchSource::WhileLetDesugar".to_string(),
685 hir::MatchSource::Normal => "MatchSource::Normal".to_string(),
686 hir::MatchSource::IfLetDesugar { contains_else_clause } => format!(
687 "MatchSource::IfLetDesugar {{ contains_else_clause: {} }}",
693 fn loop_desugaring_name(des: hir::LoopSource) -> &'static str {
695 hir::LoopSource::ForLoop => "LoopSource::ForLoop",
696 hir::LoopSource::Loop => "LoopSource::Loop",
697 hir::LoopSource::WhileLet => "LoopSource::WhileLet",
701 fn print_path(path: &QPath, first: &mut bool) {
703 QPath::Resolved(_, ref path) => {
704 for segment in &path.segments {
710 print!("{:?}", segment.ident.as_str());
713 QPath::TypeRelative(ref ty, ref segment) => match ty.node {
714 hir::TyKind::Path(ref inner_path) => {
715 print_path(inner_path, first);
721 print!("{:?}", segment.ident.as_str());
723 ref other => print!("/* unimplemented: {:?}*/", other),