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::Byte(b) => println!(" if let LitKind::Byte({}) = {}.node;", b, lit_pat),
264 // FIXME: also check int type
265 LitKind::Int(i, _) => println!(" if let LitKind::Int({}, _) = {}.node;", i, lit_pat),
266 LitKind::Float(..) => println!(" if let LitKind::Float(..) = {}.node;", lit_pat),
267 LitKind::FloatUnsuffixed(_) => {
268 println!(" if let LitKind::FloatUnsuffixed(_) = {}.node;", lit_pat)
270 LitKind::ByteStr(ref vec) => {
271 let vec_pat = self.next("vec");
272 println!(" if let LitKind::ByteStr(ref {}) = {}.node;", vec_pat, lit_pat);
273 println!(" if let [{:?}] = **{};", vec, vec_pat);
275 LitKind::Str(ref text, _) => {
276 let str_pat = self.next("s");
277 println!(" if let LitKind::Str(ref {}) = {}.node;", str_pat, lit_pat);
278 println!(" if {}.as_str() == {:?}", str_pat, &*text.as_str())
282 ExprKind::Cast(ref expr, ref ty) => {
283 let cast_pat = self.next("expr");
284 let cast_ty = self.next("cast_ty");
285 let qp_label = self.next("qp");
287 println!("Cast(ref {}, ref {}) = {};", cast_pat, cast_ty, current);
288 if let TyKind::Path(ref qp) = ty.node {
289 println!(" if let TyKind::Path(ref {}) = {}.node;", qp_label, cast_ty);
290 self.current = qp_label;
291 self.print_qpath(qp);
293 self.current = cast_pat;
294 self.visit_expr(expr);
296 ExprKind::Type(ref expr, ref _ty) => {
297 let cast_pat = self.next("expr");
298 println!("Type(ref {}, _) = {};", cast_pat, current);
299 self.current = cast_pat;
300 self.visit_expr(expr);
302 ExprKind::If(ref cond, ref then, ref opt_else) => {
303 let cond_pat = self.next("cond");
304 let then_pat = self.next("then");
305 if let Some(ref else_) = *opt_else {
306 let else_pat = self.next("else_");
308 "If(ref {}, ref {}, Some(ref {})) = {};",
309 cond_pat, then_pat, else_pat, current
311 self.current = else_pat;
312 self.visit_expr(else_);
314 println!("If(ref {}, ref {}, None) = {};", cond_pat, then_pat, current);
316 self.current = cond_pat;
317 self.visit_expr(cond);
318 self.current = then_pat;
319 self.visit_expr(then);
321 ExprKind::While(ref cond, ref body, _) => {
322 let cond_pat = self.next("cond");
323 let body_pat = self.next("body");
324 let label_pat = self.next("label");
326 "While(ref {}, ref {}, ref {}) = {};",
327 cond_pat, body_pat, label_pat, current
329 self.current = cond_pat;
330 self.visit_expr(cond);
331 self.current = body_pat;
332 self.visit_block(body);
334 ExprKind::Loop(ref body, _, desugaring) => {
335 let body_pat = self.next("body");
336 let des = loop_desugaring_name(desugaring);
337 let label_pat = self.next("label");
338 println!("Loop(ref {}, ref {}, {}) = {};", body_pat, label_pat, des, current);
339 self.current = body_pat;
340 self.visit_block(body);
342 ExprKind::Match(ref expr, ref arms, desugaring) => {
343 let des = desugaring_name(desugaring);
344 let expr_pat = self.next("expr");
345 let arms_pat = self.next("arms");
346 println!("Match(ref {}, ref {}, {}) = {};", expr_pat, arms_pat, des, current);
347 self.current = expr_pat;
348 self.visit_expr(expr);
349 println!(" if {}.len() == {};", arms_pat, arms.len());
350 for (i, arm) in arms.iter().enumerate() {
351 self.current = format!("{}[{}].body", arms_pat, i);
352 self.visit_expr(&arm.body);
353 if let Some(ref guard) = arm.guard {
354 let guard_pat = self.next("guard");
355 println!(" if let Some(ref {}) = {}[{}].guard;", guard_pat, arms_pat, i);
357 hir::Guard::If(ref if_expr) => {
358 let if_expr_pat = self.next("expr");
359 println!(" if let Guard::If(ref {}) = {};", if_expr_pat, guard_pat);
360 self.current = if_expr_pat;
361 self.visit_expr(if_expr);
365 println!(" if {}[{}].pats.len() == {};", arms_pat, i, arm.pats.len());
366 for (j, pat) in arm.pats.iter().enumerate() {
367 self.current = format!("{}[{}].pats[{}]", arms_pat, i, j);
372 ExprKind::Closure(ref _capture_clause, ref _func, _, _, _) => {
373 println!("Closure(ref capture_clause, ref func, _, _, _) = {};", current);
374 println!(" // unimplemented: `ExprKind::Closure` is not further destructured at the moment");
376 ExprKind::Yield(ref sub) => {
377 let sub_pat = self.next("sub");
378 println!("Yield(ref sub) = {};", current);
379 self.current = sub_pat;
380 self.visit_expr(sub);
382 ExprKind::Block(ref block, _) => {
383 let block_pat = self.next("block");
384 println!("Block(ref {}) = {};", block_pat, current);
385 self.current = block_pat;
386 self.visit_block(block);
388 ExprKind::Assign(ref target, ref value) => {
389 let target_pat = self.next("target");
390 let value_pat = self.next("value");
391 println!("Assign(ref {}, ref {}) = {};", target_pat, value_pat, current);
392 self.current = target_pat;
393 self.visit_expr(target);
394 self.current = value_pat;
395 self.visit_expr(value);
397 ExprKind::AssignOp(ref op, ref target, ref value) => {
398 let op_pat = self.next("op");
399 let target_pat = self.next("target");
400 let value_pat = self.next("value");
402 "AssignOp(ref {}, ref {}, ref {}) = {};",
403 op_pat, target_pat, value_pat, current
405 println!(" if BinOpKind::{:?} == {}.node;", op.node, op_pat);
406 self.current = target_pat;
407 self.visit_expr(target);
408 self.current = value_pat;
409 self.visit_expr(value);
411 ExprKind::Field(ref object, ref field_ident) => {
412 let obj_pat = self.next("object");
413 let field_name_pat = self.next("field_name");
414 println!("Field(ref {}, ref {}) = {};", obj_pat, field_name_pat, current);
415 println!(" if {}.node.as_str() == {:?}", field_name_pat, field_ident.as_str());
416 self.current = obj_pat;
417 self.visit_expr(object);
419 ExprKind::Index(ref object, ref index) => {
420 let object_pat = self.next("object");
421 let index_pat = self.next("index");
422 println!("Index(ref {}, ref {}) = {};", object_pat, index_pat, current);
423 self.current = object_pat;
424 self.visit_expr(object);
425 self.current = index_pat;
426 self.visit_expr(index);
428 ExprKind::Path(ref path) => {
429 let path_pat = self.next("path");
430 println!("Path(ref {}) = {};", path_pat, current);
431 self.current = path_pat;
432 self.print_qpath(path);
434 ExprKind::AddrOf(mutability, ref inner) => {
435 let inner_pat = self.next("inner");
436 println!("AddrOf({:?}, ref {}) = {};", mutability, inner_pat, current);
437 self.current = inner_pat;
438 self.visit_expr(inner);
440 ExprKind::Break(ref _destination, ref opt_value) => {
441 let destination_pat = self.next("destination");
442 if let Some(ref value) = *opt_value {
443 let value_pat = self.next("value");
444 println!("Break(ref {}, Some(ref {})) = {};", destination_pat, value_pat, current);
445 self.current = value_pat;
446 self.visit_expr(value);
448 println!("Break(ref {}, None) = {};", destination_pat, current);
450 // FIXME: implement label printing
452 ExprKind::Continue(ref _destination) => {
453 let destination_pat = self.next("destination");
454 println!("Again(ref {}) = {};", destination_pat, current);
455 // FIXME: implement label printing
457 ExprKind::Ret(ref opt_value) => {
458 if let Some(ref value) = *opt_value {
459 let value_pat = self.next("value");
460 println!("Ret(Some(ref {})) = {};", value_pat, current);
461 self.current = value_pat;
462 self.visit_expr(value);
464 println!("Ret(None) = {};", current);
467 ExprKind::InlineAsm(_, ref _input, ref _output) => {
468 println!("InlineAsm(_, ref input, ref output) = {};", current);
469 println!(" // unimplemented: `ExprKind::InlineAsm` is not further destructured at the moment");
471 ExprKind::Struct(ref path, ref fields, ref opt_base) => {
472 let path_pat = self.next("path");
473 let fields_pat = self.next("fields");
474 if let Some(ref base) = *opt_base {
475 let base_pat = self.next("base");
477 "Struct(ref {}, ref {}, Some(ref {})) = {};",
478 path_pat, fields_pat, base_pat, current
480 self.current = base_pat;
481 self.visit_expr(base);
483 println!("Struct(ref {}, ref {}, None) = {};", path_pat, fields_pat, current);
485 self.current = path_pat;
486 self.print_qpath(path);
487 println!(" if {}.len() == {};", fields_pat, fields.len());
488 println!(" // unimplemented: field checks");
490 // FIXME: compute length (needs type info)
491 ExprKind::Repeat(ref value, _) => {
492 let value_pat = self.next("value");
493 println!("Repeat(ref {}, _) = {};", value_pat, current);
494 println!("// unimplemented: repeat count check");
495 self.current = value_pat;
496 self.visit_expr(value);
499 println!("Err = {}", current);
504 fn visit_pat(&mut self, pat: &Pat) {
505 print!(" if let PatKind::");
506 let current = format!("{}.node", self.current);
508 PatKind::Wild => println!("Wild = {};", current),
509 PatKind::Binding(anno, _, ident, ref sub) => {
510 let anno_pat = match anno {
511 BindingAnnotation::Unannotated => "BindingAnnotation::Unannotated",
512 BindingAnnotation::Mutable => "BindingAnnotation::Mutable",
513 BindingAnnotation::Ref => "BindingAnnotation::Ref",
514 BindingAnnotation::RefMut => "BindingAnnotation::RefMut",
516 let name_pat = self.next("name");
517 if let Some(ref sub) = *sub {
518 let sub_pat = self.next("sub");
520 "Binding({}, _, {}, Some(ref {})) = {};",
521 anno_pat, name_pat, sub_pat, current
523 self.current = sub_pat;
526 println!("Binding({}, _, {}, None) = {};", anno_pat, name_pat, current);
528 println!(" if {}.node.as_str() == \"{}\";", name_pat, ident.as_str());
530 PatKind::Struct(ref path, ref fields, ignore) => {
531 let path_pat = self.next("path");
532 let fields_pat = self.next("fields");
534 "Struct(ref {}, ref {}, {}) = {};",
535 path_pat, fields_pat, ignore, current
537 self.current = path_pat;
538 self.print_qpath(path);
539 println!(" if {}.len() == {};", fields_pat, fields.len());
540 println!(" // unimplemented: field checks");
542 PatKind::TupleStruct(ref path, ref fields, skip_pos) => {
543 let path_pat = self.next("path");
544 let fields_pat = self.next("fields");
546 "TupleStruct(ref {}, ref {}, {:?}) = {};",
547 path_pat, fields_pat, skip_pos, current
549 self.current = path_pat;
550 self.print_qpath(path);
551 println!(" if {}.len() == {};", fields_pat, fields.len());
552 println!(" // unimplemented: field checks");
554 PatKind::Path(ref path) => {
555 let path_pat = self.next("path");
556 println!("Path(ref {}) = {};", path_pat, current);
557 self.current = path_pat;
558 self.print_qpath(path);
560 PatKind::Tuple(ref fields, skip_pos) => {
561 let fields_pat = self.next("fields");
562 println!("Tuple(ref {}, {:?}) = {};", fields_pat, skip_pos, current);
563 println!(" if {}.len() == {};", fields_pat, fields.len());
564 println!(" // unimplemented: field checks");
566 PatKind::Box(ref pat) => {
567 let pat_pat = self.next("pat");
568 println!("Box(ref {}) = {};", pat_pat, current);
569 self.current = pat_pat;
572 PatKind::Ref(ref pat, muta) => {
573 let pat_pat = self.next("pat");
574 println!("Ref(ref {}, Mutability::{:?}) = {};", pat_pat, muta, current);
575 self.current = pat_pat;
578 PatKind::Lit(ref lit_expr) => {
579 let lit_expr_pat = self.next("lit_expr");
580 println!("Lit(ref {}) = {}", lit_expr_pat, current);
581 self.current = lit_expr_pat;
582 self.visit_expr(lit_expr);
584 PatKind::Range(ref start, ref end, end_kind) => {
585 let start_pat = self.next("start");
586 let end_pat = self.next("end");
588 "Range(ref {}, ref {}, RangeEnd::{:?}) = {};",
589 start_pat, end_pat, end_kind, current
591 self.current = start_pat;
592 self.visit_expr(start);
593 self.current = end_pat;
594 self.visit_expr(end);
596 PatKind::Slice(ref start, ref middle, ref end) => {
597 let start_pat = self.next("start");
598 let end_pat = self.next("end");
599 if let Some(ref middle) = middle {
600 let middle_pat = self.next("middle");
602 "Slice(ref {}, Some(ref {}), ref {}) = {};",
603 start_pat, middle_pat, end_pat, current
605 self.current = middle_pat;
606 self.visit_pat(middle);
608 println!("Slice(ref {}, None, ref {}) = {};", start_pat, end_pat, current);
610 println!(" if {}.len() == {};", start_pat, start.len());
611 for (i, pat) in start.iter().enumerate() {
612 self.current = format!("{}[{}]", start_pat, i);
615 println!(" if {}.len() == {};", end_pat, end.len());
616 for (i, pat) in end.iter().enumerate() {
617 self.current = format!("{}[{}]", end_pat, i);
624 fn visit_stmt(&mut self, s: &Stmt) {
625 print!(" if let StmtKind::");
626 let current = format!("{}.node", self.current);
628 // A local (let) binding:
629 StmtKind::Local(ref local) => {
630 let local_pat = self.next("local");
631 println!("Local(ref {}) = {};", local_pat, current);
632 if let Some(ref init) = local.init {
633 let init_pat = self.next("init");
634 println!(" if let Some(ref {}) = {}.init", init_pat, local_pat);
635 self.current = init_pat;
636 self.visit_expr(init);
638 self.current = format!("{}.pat", local_pat);
639 self.visit_pat(&local.pat);
642 StmtKind::Item(_) => {
643 println!("Item(item_id) = {};", current);
646 // Expr without trailing semi-colon (must have unit type):
647 StmtKind::Expr(ref e) => {
648 let e_pat = self.next("e");
649 println!("Expr(ref {}, _) = {}", e_pat, current);
650 self.current = e_pat;
654 // Expr with trailing semi-colon (may have any type):
655 StmtKind::Semi(ref e) => {
656 let e_pat = self.next("e");
657 println!("Semi(ref {}, _) = {}", e_pat, current);
658 self.current = e_pat;
664 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
665 NestedVisitorMap::None
669 fn has_attr(attrs: &[Attribute]) -> bool {
670 get_attr(attrs, "author").count() > 0
673 fn desugaring_name(des: hir::MatchSource) -> String {
675 hir::MatchSource::ForLoopDesugar => "MatchSource::ForLoopDesugar".to_string(),
676 hir::MatchSource::TryDesugar => "MatchSource::TryDesugar".to_string(),
677 hir::MatchSource::WhileLetDesugar => "MatchSource::WhileLetDesugar".to_string(),
678 hir::MatchSource::Normal => "MatchSource::Normal".to_string(),
679 hir::MatchSource::IfLetDesugar { contains_else_clause } => format!(
680 "MatchSource::IfLetDesugar {{ contains_else_clause: {} }}",
686 fn loop_desugaring_name(des: hir::LoopSource) -> &'static str {
688 hir::LoopSource::ForLoop => "LoopSource::ForLoop",
689 hir::LoopSource::Loop => "LoopSource::Loop",
690 hir::LoopSource::WhileLet => "LoopSource::WhileLet",
694 fn print_path(path: &QPath, first: &mut bool) {
696 QPath::Resolved(_, ref path) => {
697 for segment in &path.segments {
703 print!("{:?}", segment.ident.as_str());
706 QPath::TypeRelative(ref ty, ref segment) => match ty.node {
707 hir::TyKind::Path(ref inner_path) => {
708 print_path(inner_path, first);
714 print!("{:?}", segment.ident.as_str());
716 ref other => print!("/* unimplemented: {:?}*/", other),