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, DUMMY_NODE_ID};
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 test --test compile-test` 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)
59 println!("if_chain! {{");
64 println!(" // report your lint here");
69 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
70 fn check_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
71 if !has_attr(&item.attrs) {
75 PrintVisitor::new("item").visit_item(item);
79 fn check_impl_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem) {
80 if !has_attr(&item.attrs) {
84 PrintVisitor::new("item").visit_impl_item(item);
88 fn check_trait_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
89 if !has_attr(&item.attrs) {
93 PrintVisitor::new("item").visit_trait_item(item);
97 fn check_variant(&mut self, _cx: &LateContext<'a, 'tcx>, var: &'tcx hir::Variant, generics: &hir::Generics) {
98 if !has_attr(&var.node.attrs) {
102 PrintVisitor::new("var").visit_variant(var, generics, DUMMY_NODE_ID);
106 fn check_struct_field(&mut self, _cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField) {
107 if !has_attr(&field.attrs) {
111 PrintVisitor::new("field").visit_struct_field(field);
115 fn check_expr(&mut self, _cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
116 if !has_attr(&expr.attrs) {
120 PrintVisitor::new("expr").visit_expr(expr);
124 fn check_arm(&mut self, _cx: &LateContext<'a, 'tcx>, arm: &'tcx hir::Arm) {
125 if !has_attr(&arm.attrs) {
129 PrintVisitor::new("arm").visit_arm(arm);
133 fn check_stmt(&mut self, _cx: &LateContext<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
134 if !has_attr(stmt.node.attrs()) {
138 PrintVisitor::new("stmt").visit_stmt(stmt);
142 fn check_foreign_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ForeignItem) {
143 if !has_attr(&item.attrs) {
147 PrintVisitor::new("item").visit_foreign_item(item);
153 fn new(s: &'static str) -> Self {
155 ids: FxHashMap::default(),
156 current: s.to_owned(),
160 fn next(&mut self, s: &'static str) -> String {
161 use std::collections::hash_map::Entry::*;
162 match self.ids.entry(s) {
163 // already there: start numbering from `1`
164 Occupied(mut occ) => {
165 let val = occ.get_mut();
167 format!("{}{}", s, *val)
169 // not there: insert and return name as given
177 fn print_qpath(&mut self, path: &QPath) {
178 print!(" if match_qpath({}, &[", self.current);
179 print_path(path, &mut true);
184 struct PrintVisitor {
185 /// Fields are the current index that needs to be appended to pattern
187 ids: FxHashMap<&'static str, usize>,
188 /// the name that needs to be destructured
192 impl<'tcx> Visitor<'tcx> for PrintVisitor {
193 fn visit_expr(&mut self, expr: &Expr) {
194 print!(" if let ExprKind::");
195 let current = format!("{}.node", self.current);
197 ExprKind::Box(ref inner) => {
198 let inner_pat = self.next("inner");
199 println!("Box(ref {}) = {};", inner_pat, current);
200 self.current = inner_pat;
201 self.visit_expr(inner);
203 ExprKind::Array(ref elements) => {
204 let elements_pat = self.next("elements");
205 println!("Array(ref {}) = {};", elements_pat, current);
206 println!(" if {}.len() == {};", elements_pat, elements.len());
207 for (i, element) in elements.iter().enumerate() {
208 self.current = format!("{}[{}]", elements_pat, i);
209 self.visit_expr(element);
212 ExprKind::Call(ref func, ref args) => {
213 let func_pat = self.next("func");
214 let args_pat = self.next("args");
215 println!("Call(ref {}, ref {}) = {};", func_pat, args_pat, current);
216 self.current = func_pat;
217 self.visit_expr(func);
218 println!(" if {}.len() == {};", args_pat, args.len());
219 for (i, arg) in args.iter().enumerate() {
220 self.current = format!("{}[{}]", args_pat, i);
221 self.visit_expr(arg);
224 ExprKind::MethodCall(ref _method_name, ref _generics, ref _args) => {
225 println!("MethodCall(ref method_name, ref generics, ref args) = {};", current);
226 println!(" // unimplemented: `ExprKind::MethodCall` is not further destructured at the moment");
228 ExprKind::Tup(ref elements) => {
229 let elements_pat = self.next("elements");
230 println!("Tup(ref {}) = {};", elements_pat, current);
231 println!(" if {}.len() == {};", elements_pat, elements.len());
232 for (i, element) in elements.iter().enumerate() {
233 self.current = format!("{}[{}]", elements_pat, i);
234 self.visit_expr(element);
237 ExprKind::Binary(ref op, ref left, ref right) => {
238 let op_pat = self.next("op");
239 let left_pat = self.next("left");
240 let right_pat = self.next("right");
242 "Binary(ref {}, ref {}, ref {}) = {};",
243 op_pat, left_pat, right_pat, current
245 println!(" if BinOpKind::{:?} == {}.node;", op.node, op_pat);
246 self.current = left_pat;
247 self.visit_expr(left);
248 self.current = right_pat;
249 self.visit_expr(right);
251 ExprKind::Unary(ref op, ref inner) => {
252 let inner_pat = self.next("inner");
253 println!("Unary(UnOp::{:?}, ref {}) = {};", op, inner_pat, current);
254 self.current = inner_pat;
255 self.visit_expr(inner);
257 ExprKind::Lit(ref lit) => {
258 let lit_pat = self.next("lit");
259 println!("Lit(ref {}) = {};", lit_pat, current);
261 LitKind::Bool(val) => println!(" if let LitKind::Bool({:?}) = {}.node;", val, lit_pat),
262 LitKind::Char(c) => println!(" if let LitKind::Char({:?}) = {}.node;", c, lit_pat),
263 LitKind::Err(val) => println!(" if let LitKind::Err({}) = {}.node;", val, lit_pat),
264 LitKind::Byte(b) => println!(" if let LitKind::Byte({}) = {}.node;", b, lit_pat),
265 // FIXME: also check int type
266 LitKind::Int(i, _) => println!(" if let LitKind::Int({}, _) = {}.node;", i, lit_pat),
267 LitKind::Float(..) => println!(" if let LitKind::Float(..) = {}.node;", lit_pat),
268 LitKind::FloatUnsuffixed(_) => {
269 println!(" if let LitKind::FloatUnsuffixed(_) = {}.node;", lit_pat)
271 LitKind::ByteStr(ref vec) => {
272 let vec_pat = self.next("vec");
273 println!(" if let LitKind::ByteStr(ref {}) = {}.node;", vec_pat, lit_pat);
274 println!(" if let [{:?}] = **{};", vec, vec_pat);
276 LitKind::Str(ref text, _) => {
277 let str_pat = self.next("s");
278 println!(" if let LitKind::Str(ref {}) = {}.node;", str_pat, lit_pat);
279 println!(" if {}.as_str() == {:?}", str_pat, &*text.as_str())
283 ExprKind::Cast(ref expr, ref ty) => {
284 let cast_pat = self.next("expr");
285 let cast_ty = self.next("cast_ty");
286 let qp_label = self.next("qp");
288 println!("Cast(ref {}, ref {}) = {};", cast_pat, cast_ty, current);
289 if let TyKind::Path(ref qp) = ty.node {
290 println!(" if let TyKind::Path(ref {}) = {}.node;", qp_label, cast_ty);
291 self.current = qp_label;
292 self.print_qpath(qp);
294 self.current = cast_pat;
295 self.visit_expr(expr);
297 ExprKind::Type(ref expr, ref _ty) => {
298 let cast_pat = self.next("expr");
299 println!("Type(ref {}, _) = {};", cast_pat, current);
300 self.current = cast_pat;
301 self.visit_expr(expr);
303 ExprKind::If(ref cond, ref then, ref opt_else) => {
304 let cond_pat = self.next("cond");
305 let then_pat = self.next("then");
306 if let Some(ref else_) = *opt_else {
307 let else_pat = self.next("else_");
309 "If(ref {}, ref {}, Some(ref {})) = {};",
310 cond_pat, then_pat, else_pat, current
312 self.current = else_pat;
313 self.visit_expr(else_);
315 println!("If(ref {}, ref {}, None) = {};", cond_pat, then_pat, current);
317 self.current = cond_pat;
318 self.visit_expr(cond);
319 self.current = then_pat;
320 self.visit_expr(then);
322 ExprKind::While(ref cond, ref body, _) => {
323 let cond_pat = self.next("cond");
324 let body_pat = self.next("body");
325 let label_pat = self.next("label");
327 "While(ref {}, ref {}, ref {}) = {};",
328 cond_pat, body_pat, label_pat, current
330 self.current = cond_pat;
331 self.visit_expr(cond);
332 self.current = body_pat;
333 self.visit_block(body);
335 ExprKind::Loop(ref body, _, desugaring) => {
336 let body_pat = self.next("body");
337 let des = loop_desugaring_name(desugaring);
338 let label_pat = self.next("label");
339 println!("Loop(ref {}, ref {}, {}) = {};", body_pat, label_pat, des, current);
340 self.current = body_pat;
341 self.visit_block(body);
343 ExprKind::Match(ref expr, ref arms, desugaring) => {
344 let des = desugaring_name(desugaring);
345 let expr_pat = self.next("expr");
346 let arms_pat = self.next("arms");
347 println!("Match(ref {}, ref {}, {}) = {};", expr_pat, arms_pat, des, current);
348 self.current = expr_pat;
349 self.visit_expr(expr);
350 println!(" if {}.len() == {};", arms_pat, arms.len());
351 for (i, arm) in arms.iter().enumerate() {
352 self.current = format!("{}[{}].body", arms_pat, i);
353 self.visit_expr(&arm.body);
354 if let Some(ref guard) = arm.guard {
355 let guard_pat = self.next("guard");
356 println!(" if let Some(ref {}) = {}[{}].guard;", guard_pat, arms_pat, i);
358 hir::Guard::If(ref if_expr) => {
359 let if_expr_pat = self.next("expr");
360 println!(" if let Guard::If(ref {}) = {};", if_expr_pat, guard_pat);
361 self.current = if_expr_pat;
362 self.visit_expr(if_expr);
366 println!(" if {}[{}].pats.len() == {};", arms_pat, i, arm.pats.len());
367 for (j, pat) in arm.pats.iter().enumerate() {
368 self.current = format!("{}[{}].pats[{}]", arms_pat, i, j);
373 ExprKind::Closure(ref _capture_clause, ref _func, _, _, _) => {
374 println!("Closure(ref capture_clause, ref func, _, _, _) = {};", current);
375 println!(" // unimplemented: `ExprKind::Closure` is not further destructured at the moment");
377 ExprKind::Yield(ref sub) => {
378 let sub_pat = self.next("sub");
379 println!("Yield(ref sub) = {};", current);
380 self.current = sub_pat;
381 self.visit_expr(sub);
383 ExprKind::Block(ref block, _) => {
384 let block_pat = self.next("block");
385 println!("Block(ref {}) = {};", block_pat, current);
386 self.current = block_pat;
387 self.visit_block(block);
389 ExprKind::Assign(ref target, ref value) => {
390 let target_pat = self.next("target");
391 let value_pat = self.next("value");
392 println!("Assign(ref {}, ref {}) = {};", target_pat, value_pat, current);
393 self.current = target_pat;
394 self.visit_expr(target);
395 self.current = value_pat;
396 self.visit_expr(value);
398 ExprKind::AssignOp(ref op, ref target, ref value) => {
399 let op_pat = self.next("op");
400 let target_pat = self.next("target");
401 let value_pat = self.next("value");
403 "AssignOp(ref {}, ref {}, ref {}) = {};",
404 op_pat, target_pat, value_pat, current
406 println!(" if BinOpKind::{:?} == {}.node;", op.node, op_pat);
407 self.current = target_pat;
408 self.visit_expr(target);
409 self.current = value_pat;
410 self.visit_expr(value);
412 ExprKind::Field(ref object, ref field_ident) => {
413 let obj_pat = self.next("object");
414 let field_name_pat = self.next("field_name");
415 println!("Field(ref {}, ref {}) = {};", obj_pat, field_name_pat, current);
416 println!(" if {}.node.as_str() == {:?}", field_name_pat, field_ident.as_str());
417 self.current = obj_pat;
418 self.visit_expr(object);
420 ExprKind::Index(ref object, ref index) => {
421 let object_pat = self.next("object");
422 let index_pat = self.next("index");
423 println!("Index(ref {}, ref {}) = {};", object_pat, index_pat, current);
424 self.current = object_pat;
425 self.visit_expr(object);
426 self.current = index_pat;
427 self.visit_expr(index);
429 ExprKind::Path(ref path) => {
430 let path_pat = self.next("path");
431 println!("Path(ref {}) = {};", path_pat, current);
432 self.current = path_pat;
433 self.print_qpath(path);
435 ExprKind::AddrOf(mutability, ref inner) => {
436 let inner_pat = self.next("inner");
437 println!("AddrOf({:?}, ref {}) = {};", mutability, inner_pat, current);
438 self.current = inner_pat;
439 self.visit_expr(inner);
441 ExprKind::Break(ref _destination, ref opt_value) => {
442 let destination_pat = self.next("destination");
443 if let Some(ref value) = *opt_value {
444 let value_pat = self.next("value");
445 println!("Break(ref {}, Some(ref {})) = {};", destination_pat, value_pat, current);
446 self.current = value_pat;
447 self.visit_expr(value);
449 println!("Break(ref {}, None) = {};", destination_pat, current);
451 // FIXME: implement label printing
453 ExprKind::Continue(ref _destination) => {
454 let destination_pat = self.next("destination");
455 println!("Again(ref {}) = {};", destination_pat, current);
456 // FIXME: implement label printing
458 ExprKind::Ret(ref opt_value) => {
459 if let Some(ref value) = *opt_value {
460 let value_pat = self.next("value");
461 println!("Ret(Some(ref {})) = {};", value_pat, current);
462 self.current = value_pat;
463 self.visit_expr(value);
465 println!("Ret(None) = {};", current);
468 ExprKind::InlineAsm(_, ref _input, ref _output) => {
469 println!("InlineAsm(_, ref input, ref output) = {};", current);
470 println!(" // unimplemented: `ExprKind::InlineAsm` is not further destructured at the moment");
472 ExprKind::Struct(ref path, ref fields, ref opt_base) => {
473 let path_pat = self.next("path");
474 let fields_pat = self.next("fields");
475 if let Some(ref base) = *opt_base {
476 let base_pat = self.next("base");
478 "Struct(ref {}, ref {}, Some(ref {})) = {};",
479 path_pat, fields_pat, base_pat, current
481 self.current = base_pat;
482 self.visit_expr(base);
484 println!("Struct(ref {}, ref {}, None) = {};", path_pat, fields_pat, current);
486 self.current = path_pat;
487 self.print_qpath(path);
488 println!(" if {}.len() == {};", fields_pat, fields.len());
489 println!(" // unimplemented: field checks");
491 // FIXME: compute length (needs type info)
492 ExprKind::Repeat(ref value, _) => {
493 let value_pat = self.next("value");
494 println!("Repeat(ref {}, _) = {};", value_pat, current);
495 println!("// unimplemented: repeat count check");
496 self.current = value_pat;
497 self.visit_expr(value);
500 println!("Err = {}", current);
505 fn visit_pat(&mut self, pat: &Pat) {
506 print!(" if let PatKind::");
507 let current = format!("{}.node", self.current);
509 PatKind::Wild => println!("Wild = {};", current),
510 PatKind::Binding(anno, _, ident, ref sub) => {
511 let anno_pat = match anno {
512 BindingAnnotation::Unannotated => "BindingAnnotation::Unannotated",
513 BindingAnnotation::Mutable => "BindingAnnotation::Mutable",
514 BindingAnnotation::Ref => "BindingAnnotation::Ref",
515 BindingAnnotation::RefMut => "BindingAnnotation::RefMut",
517 let name_pat = self.next("name");
518 if let Some(ref sub) = *sub {
519 let sub_pat = self.next("sub");
521 "Binding({}, _, {}, Some(ref {})) = {};",
522 anno_pat, name_pat, sub_pat, current
524 self.current = sub_pat;
527 println!("Binding({}, _, {}, None) = {};", anno_pat, name_pat, current);
529 println!(" if {}.node.as_str() == \"{}\";", name_pat, ident.as_str());
531 PatKind::Struct(ref path, ref fields, ignore) => {
532 let path_pat = self.next("path");
533 let fields_pat = self.next("fields");
535 "Struct(ref {}, ref {}, {}) = {};",
536 path_pat, fields_pat, ignore, current
538 self.current = path_pat;
539 self.print_qpath(path);
540 println!(" if {}.len() == {};", fields_pat, fields.len());
541 println!(" // unimplemented: field checks");
543 PatKind::TupleStruct(ref path, ref fields, skip_pos) => {
544 let path_pat = self.next("path");
545 let fields_pat = self.next("fields");
547 "TupleStruct(ref {}, ref {}, {:?}) = {};",
548 path_pat, fields_pat, skip_pos, current
550 self.current = path_pat;
551 self.print_qpath(path);
552 println!(" if {}.len() == {};", fields_pat, fields.len());
553 println!(" // unimplemented: field checks");
555 PatKind::Path(ref path) => {
556 let path_pat = self.next("path");
557 println!("Path(ref {}) = {};", path_pat, current);
558 self.current = path_pat;
559 self.print_qpath(path);
561 PatKind::Tuple(ref fields, skip_pos) => {
562 let fields_pat = self.next("fields");
563 println!("Tuple(ref {}, {:?}) = {};", fields_pat, skip_pos, current);
564 println!(" if {}.len() == {};", fields_pat, fields.len());
565 println!(" // unimplemented: field checks");
567 PatKind::Box(ref pat) => {
568 let pat_pat = self.next("pat");
569 println!("Box(ref {}) = {};", pat_pat, current);
570 self.current = pat_pat;
573 PatKind::Ref(ref pat, muta) => {
574 let pat_pat = self.next("pat");
575 println!("Ref(ref {}, Mutability::{:?}) = {};", pat_pat, muta, current);
576 self.current = pat_pat;
579 PatKind::Lit(ref lit_expr) => {
580 let lit_expr_pat = self.next("lit_expr");
581 println!("Lit(ref {}) = {}", lit_expr_pat, current);
582 self.current = lit_expr_pat;
583 self.visit_expr(lit_expr);
585 PatKind::Range(ref start, ref end, end_kind) => {
586 let start_pat = self.next("start");
587 let end_pat = self.next("end");
589 "Range(ref {}, ref {}, RangeEnd::{:?}) = {};",
590 start_pat, end_pat, end_kind, current
592 self.current = start_pat;
593 self.visit_expr(start);
594 self.current = end_pat;
595 self.visit_expr(end);
597 PatKind::Slice(ref start, ref middle, ref end) => {
598 let start_pat = self.next("start");
599 let end_pat = self.next("end");
600 if let Some(ref middle) = middle {
601 let middle_pat = self.next("middle");
603 "Slice(ref {}, Some(ref {}), ref {}) = {};",
604 start_pat, middle_pat, end_pat, current
606 self.current = middle_pat;
607 self.visit_pat(middle);
609 println!("Slice(ref {}, None, ref {}) = {};", start_pat, end_pat, current);
611 println!(" if {}.len() == {};", start_pat, start.len());
612 for (i, pat) in start.iter().enumerate() {
613 self.current = format!("{}[{}]", start_pat, i);
616 println!(" if {}.len() == {};", end_pat, end.len());
617 for (i, pat) in end.iter().enumerate() {
618 self.current = format!("{}[{}]", end_pat, i);
625 fn visit_stmt(&mut self, s: &Stmt) {
626 print!(" if let StmtKind::");
627 let current = format!("{}.node", self.current);
629 // A local (let) binding:
630 StmtKind::Local(ref local) => {
631 let local_pat = self.next("local");
632 println!("Local(ref {}) = {};", local_pat, current);
633 if let Some(ref init) = local.init {
634 let init_pat = self.next("init");
635 println!(" if let Some(ref {}) = {}.init", init_pat, local_pat);
636 self.current = init_pat;
637 self.visit_expr(init);
639 self.current = format!("{}.pat", local_pat);
640 self.visit_pat(&local.pat);
643 StmtKind::Item(_) => {
644 println!("Item(item_id) = {};", current);
647 // Expr without trailing semi-colon (must have unit type):
648 StmtKind::Expr(ref e) => {
649 let e_pat = self.next("e");
650 println!("Expr(ref {}, _) = {}", e_pat, current);
651 self.current = e_pat;
655 // Expr with trailing semi-colon (may have any type):
656 StmtKind::Semi(ref e) => {
657 let e_pat = self.next("e");
658 println!("Semi(ref {}, _) = {}", e_pat, current);
659 self.current = e_pat;
665 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
666 NestedVisitorMap::None
670 fn has_attr(attrs: &[Attribute]) -> bool {
671 get_attr(attrs, "author").count() > 0
674 fn desugaring_name(des: hir::MatchSource) -> String {
676 hir::MatchSource::ForLoopDesugar => "MatchSource::ForLoopDesugar".to_string(),
677 hir::MatchSource::TryDesugar => "MatchSource::TryDesugar".to_string(),
678 hir::MatchSource::WhileLetDesugar => "MatchSource::WhileLetDesugar".to_string(),
679 hir::MatchSource::Normal => "MatchSource::Normal".to_string(),
680 hir::MatchSource::IfLetDesugar { contains_else_clause } => format!(
681 "MatchSource::IfLetDesugar {{ contains_else_clause: {} }}",
687 fn loop_desugaring_name(des: hir::LoopSource) -> &'static str {
689 hir::LoopSource::ForLoop => "LoopSource::ForLoop",
690 hir::LoopSource::Loop => "LoopSource::Loop",
691 hir::LoopSource::WhileLet => "LoopSource::WhileLet",
695 fn print_path(path: &QPath, first: &mut bool) {
697 QPath::Resolved(_, ref path) => {
698 for segment in &path.segments {
704 print!("{:?}", segment.ident.as_str());
707 QPath::TypeRelative(ref ty, ref segment) => match ty.node {
708 hir::TyKind::Path(ref inner_path) => {
709 print_path(inner_path, first);
715 print!("{:?}", segment.ident.as_str());
717 ref other => print!("/* unimplemented: {:?}*/", other),