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, LintContext, LintPass};
9 use rustc::session::Session;
10 use rustc::{declare_tool_lint, lint_array};
11 use rustc_data_structures::fx::FxHashMap;
12 use syntax::ast::{Attribute, LitKind};
14 declare_clippy_lint! {
15 /// **What it does:** Generates clippy code that detects the offending pattern
19 /// // ./tests/ui/my_lint.rs
21 /// // detect the following pattern
24 /// // but ignore everything from here on
25 /// #![clippy::author = "ignore"]
30 /// Running `TESTNAME=ui/my_lint cargo uitest` will produce
31 /// a `./tests/ui/new_lint.stdout` file with the generated code:
34 /// // ./tests/ui/new_lint.stdout
36 /// if let ExprKind::If(ref cond, ref then, None) = item.node,
37 /// if let ExprKind::Binary(BinOp::Eq, ref left, ref right) = cond.node,
38 /// if let ExprKind::Path(ref path) = left.node,
39 /// if let ExprKind::Lit(ref lit) = right.node,
40 /// if let LitKind::Int(42, _) = lit.node,
42 /// // report your lint here
48 "helper for writing lints"
53 impl LintPass for Pass {
54 fn get_lints(&self) -> LintArray {
55 lint_array!(LINT_AUTHOR)
58 fn name(&self) -> &'static str {
64 println!("if_chain! {{");
69 println!(" // report your lint here");
74 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
75 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
76 if !has_attr(cx.sess(), &item.attrs) {
80 PrintVisitor::new("item").visit_item(item);
84 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem) {
85 if !has_attr(cx.sess(), &item.attrs) {
89 PrintVisitor::new("item").visit_impl_item(item);
93 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
94 if !has_attr(cx.sess(), &item.attrs) {
98 PrintVisitor::new("item").visit_trait_item(item);
102 fn check_variant(&mut self, cx: &LateContext<'a, 'tcx>, var: &'tcx hir::Variant, generics: &hir::Generics) {
103 if !has_attr(cx.sess(), &var.node.attrs) {
107 PrintVisitor::new("var").visit_variant(var, generics, hir::DUMMY_HIR_ID);
111 fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField) {
112 if !has_attr(cx.sess(), &field.attrs) {
116 PrintVisitor::new("field").visit_struct_field(field);
120 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
121 if !has_attr(cx.sess(), &expr.attrs) {
125 PrintVisitor::new("expr").visit_expr(expr);
129 fn check_arm(&mut self, cx: &LateContext<'a, 'tcx>, arm: &'tcx hir::Arm) {
130 if !has_attr(cx.sess(), &arm.attrs) {
134 PrintVisitor::new("arm").visit_arm(arm);
138 fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
139 if !has_attr(cx.sess(), stmt.node.attrs()) {
143 PrintVisitor::new("stmt").visit_stmt(stmt);
147 fn check_foreign_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ForeignItem) {
148 if !has_attr(cx.sess(), &item.attrs) {
152 PrintVisitor::new("item").visit_foreign_item(item);
158 fn new(s: &'static str) -> Self {
160 ids: FxHashMap::default(),
161 current: s.to_owned(),
165 fn next(&mut self, s: &'static str) -> String {
166 use std::collections::hash_map::Entry::*;
167 match self.ids.entry(s) {
168 // already there: start numbering from `1`
169 Occupied(mut occ) => {
170 let val = occ.get_mut();
172 format!("{}{}", s, *val)
174 // not there: insert and return name as given
182 fn print_qpath(&mut self, path: &QPath) {
183 print!(" if match_qpath({}, &[", self.current);
184 print_path(path, &mut true);
189 struct PrintVisitor {
190 /// Fields are the current index that needs to be appended to pattern
192 ids: FxHashMap<&'static str, usize>,
193 /// the name that needs to be destructured
197 impl<'tcx> Visitor<'tcx> for PrintVisitor {
198 #[allow(clippy::too_many_lines)]
199 fn visit_expr(&mut self, expr: &Expr) {
200 print!(" if let ExprKind::");
201 let current = format!("{}.node", self.current);
203 ExprKind::Box(ref inner) => {
204 let inner_pat = self.next("inner");
205 println!("Box(ref {}) = {};", inner_pat, current);
206 self.current = inner_pat;
207 self.visit_expr(inner);
209 ExprKind::Array(ref elements) => {
210 let elements_pat = self.next("elements");
211 println!("Array(ref {}) = {};", elements_pat, current);
212 println!(" if {}.len() == {};", elements_pat, elements.len());
213 for (i, element) in elements.iter().enumerate() {
214 self.current = format!("{}[{}]", elements_pat, i);
215 self.visit_expr(element);
218 ExprKind::Call(ref func, ref args) => {
219 let func_pat = self.next("func");
220 let args_pat = self.next("args");
221 println!("Call(ref {}, ref {}) = {};", func_pat, args_pat, current);
222 self.current = func_pat;
223 self.visit_expr(func);
224 println!(" if {}.len() == {};", args_pat, args.len());
225 for (i, arg) in args.iter().enumerate() {
226 self.current = format!("{}[{}]", args_pat, i);
227 self.visit_expr(arg);
230 ExprKind::MethodCall(ref _method_name, ref _generics, ref _args) => {
231 println!("MethodCall(ref method_name, ref generics, ref args) = {};", current);
232 println!(" // unimplemented: `ExprKind::MethodCall` is not further destructured at the moment");
234 ExprKind::Tup(ref elements) => {
235 let elements_pat = self.next("elements");
236 println!("Tup(ref {}) = {};", elements_pat, current);
237 println!(" if {}.len() == {};", elements_pat, elements.len());
238 for (i, element) in elements.iter().enumerate() {
239 self.current = format!("{}[{}]", elements_pat, i);
240 self.visit_expr(element);
243 ExprKind::Binary(ref op, ref left, ref right) => {
244 let op_pat = self.next("op");
245 let left_pat = self.next("left");
246 let right_pat = self.next("right");
248 "Binary(ref {}, ref {}, ref {}) = {};",
249 op_pat, left_pat, right_pat, current
251 println!(" if BinOpKind::{:?} == {}.node;", op.node, op_pat);
252 self.current = left_pat;
253 self.visit_expr(left);
254 self.current = right_pat;
255 self.visit_expr(right);
257 ExprKind::Unary(ref op, ref inner) => {
258 let inner_pat = self.next("inner");
259 println!("Unary(UnOp::{:?}, ref {}) = {};", op, inner_pat, current);
260 self.current = inner_pat;
261 self.visit_expr(inner);
263 ExprKind::Lit(ref lit) => {
264 let lit_pat = self.next("lit");
265 println!("Lit(ref {}) = {};", lit_pat, current);
267 LitKind::Bool(val) => println!(" if let LitKind::Bool({:?}) = {}.node;", val, lit_pat),
268 LitKind::Char(c) => println!(" if let LitKind::Char({:?}) = {}.node;", c, lit_pat),
269 LitKind::Err(val) => println!(" if let LitKind::Err({}) = {}.node;", val, lit_pat),
270 LitKind::Byte(b) => println!(" if let LitKind::Byte({}) = {}.node;", b, lit_pat),
271 // FIXME: also check int type
272 LitKind::Int(i, _) => println!(" if let LitKind::Int({}, _) = {}.node;", i, lit_pat),
273 LitKind::Float(..) => println!(" if let LitKind::Float(..) = {}.node;", lit_pat),
274 LitKind::FloatUnsuffixed(_) => {
275 println!(" if let LitKind::FloatUnsuffixed(_) = {}.node;", lit_pat)
277 LitKind::ByteStr(ref vec) => {
278 let vec_pat = self.next("vec");
279 println!(" if let LitKind::ByteStr(ref {}) = {}.node;", vec_pat, lit_pat);
280 println!(" if let [{:?}] = **{};", vec, vec_pat);
282 LitKind::Str(ref text, _) => {
283 let str_pat = self.next("s");
284 println!(" if let LitKind::Str(ref {}) = {}.node;", str_pat, lit_pat);
285 println!(" if {}.as_str() == {:?}", str_pat, &*text.as_str())
289 ExprKind::Cast(ref expr, ref ty) => {
290 let cast_pat = self.next("expr");
291 let cast_ty = self.next("cast_ty");
292 let qp_label = self.next("qp");
294 println!("Cast(ref {}, ref {}) = {};", cast_pat, cast_ty, current);
295 if let TyKind::Path(ref qp) = ty.node {
296 println!(" if let TyKind::Path(ref {}) = {}.node;", qp_label, cast_ty);
297 self.current = qp_label;
298 self.print_qpath(qp);
300 self.current = cast_pat;
301 self.visit_expr(expr);
303 ExprKind::Type(ref expr, ref _ty) => {
304 let cast_pat = self.next("expr");
305 println!("Type(ref {}, _) = {};", cast_pat, current);
306 self.current = cast_pat;
307 self.visit_expr(expr);
309 ExprKind::If(ref cond, ref then, ref opt_else) => {
310 let cond_pat = self.next("cond");
311 let then_pat = self.next("then");
312 if let Some(ref else_) = *opt_else {
313 let else_pat = self.next("else_");
315 "If(ref {}, ref {}, Some(ref {})) = {};",
316 cond_pat, then_pat, else_pat, current
318 self.current = else_pat;
319 self.visit_expr(else_);
321 println!("If(ref {}, ref {}, None) = {};", cond_pat, then_pat, current);
323 self.current = cond_pat;
324 self.visit_expr(cond);
325 self.current = then_pat;
326 self.visit_expr(then);
328 ExprKind::While(ref cond, ref body, _) => {
329 let cond_pat = self.next("cond");
330 let body_pat = self.next("body");
331 let label_pat = self.next("label");
333 "While(ref {}, ref {}, ref {}) = {};",
334 cond_pat, body_pat, label_pat, current
336 self.current = cond_pat;
337 self.visit_expr(cond);
338 self.current = body_pat;
339 self.visit_block(body);
341 ExprKind::Loop(ref body, _, desugaring) => {
342 let body_pat = self.next("body");
343 let des = loop_desugaring_name(desugaring);
344 let label_pat = self.next("label");
345 println!("Loop(ref {}, ref {}, {}) = {};", body_pat, label_pat, des, current);
346 self.current = body_pat;
347 self.visit_block(body);
349 ExprKind::Match(ref expr, ref arms, desugaring) => {
350 let des = desugaring_name(desugaring);
351 let expr_pat = self.next("expr");
352 let arms_pat = self.next("arms");
353 println!("Match(ref {}, ref {}, {}) = {};", expr_pat, arms_pat, des, current);
354 self.current = expr_pat;
355 self.visit_expr(expr);
356 println!(" if {}.len() == {};", arms_pat, arms.len());
357 for (i, arm) in arms.iter().enumerate() {
358 self.current = format!("{}[{}].body", arms_pat, i);
359 self.visit_expr(&arm.body);
360 if let Some(ref guard) = arm.guard {
361 let guard_pat = self.next("guard");
362 println!(" if let Some(ref {}) = {}[{}].guard;", guard_pat, arms_pat, i);
364 hir::Guard::If(ref if_expr) => {
365 let if_expr_pat = self.next("expr");
366 println!(" if let Guard::If(ref {}) = {};", if_expr_pat, guard_pat);
367 self.current = if_expr_pat;
368 self.visit_expr(if_expr);
372 println!(" if {}[{}].pats.len() == {};", arms_pat, i, arm.pats.len());
373 for (j, pat) in arm.pats.iter().enumerate() {
374 self.current = format!("{}[{}].pats[{}]", arms_pat, i, j);
379 ExprKind::Closure(ref _capture_clause, ref _func, _, _, _) => {
380 println!("Closure(ref capture_clause, ref func, _, _, _) = {};", current);
381 println!(" // unimplemented: `ExprKind::Closure` is not further destructured at the moment");
383 ExprKind::Yield(ref sub) => {
384 let sub_pat = self.next("sub");
385 println!("Yield(ref sub) = {};", current);
386 self.current = sub_pat;
387 self.visit_expr(sub);
389 ExprKind::Block(ref block, _) => {
390 let block_pat = self.next("block");
391 println!("Block(ref {}) = {};", block_pat, current);
392 self.current = block_pat;
393 self.visit_block(block);
395 ExprKind::Assign(ref target, ref value) => {
396 let target_pat = self.next("target");
397 let value_pat = self.next("value");
398 println!("Assign(ref {}, ref {}) = {};", target_pat, value_pat, current);
399 self.current = target_pat;
400 self.visit_expr(target);
401 self.current = value_pat;
402 self.visit_expr(value);
404 ExprKind::AssignOp(ref op, ref target, ref value) => {
405 let op_pat = self.next("op");
406 let target_pat = self.next("target");
407 let value_pat = self.next("value");
409 "AssignOp(ref {}, ref {}, ref {}) = {};",
410 op_pat, target_pat, value_pat, current
412 println!(" if BinOpKind::{:?} == {}.node;", op.node, op_pat);
413 self.current = target_pat;
414 self.visit_expr(target);
415 self.current = value_pat;
416 self.visit_expr(value);
418 ExprKind::Field(ref object, ref field_ident) => {
419 let obj_pat = self.next("object");
420 let field_name_pat = self.next("field_name");
421 println!("Field(ref {}, ref {}) = {};", obj_pat, field_name_pat, current);
422 println!(" if {}.node.as_str() == {:?}", field_name_pat, field_ident.as_str());
423 self.current = obj_pat;
424 self.visit_expr(object);
426 ExprKind::Index(ref object, ref index) => {
427 let object_pat = self.next("object");
428 let index_pat = self.next("index");
429 println!("Index(ref {}, ref {}) = {};", object_pat, index_pat, current);
430 self.current = object_pat;
431 self.visit_expr(object);
432 self.current = index_pat;
433 self.visit_expr(index);
435 ExprKind::Path(ref path) => {
436 let path_pat = self.next("path");
437 println!("Path(ref {}) = {};", path_pat, current);
438 self.current = path_pat;
439 self.print_qpath(path);
441 ExprKind::AddrOf(mutability, ref inner) => {
442 let inner_pat = self.next("inner");
443 println!("AddrOf({:?}, ref {}) = {};", mutability, inner_pat, current);
444 self.current = inner_pat;
445 self.visit_expr(inner);
447 ExprKind::Break(ref _destination, ref opt_value) => {
448 let destination_pat = self.next("destination");
449 if let Some(ref value) = *opt_value {
450 let value_pat = self.next("value");
451 println!("Break(ref {}, Some(ref {})) = {};", destination_pat, value_pat, current);
452 self.current = value_pat;
453 self.visit_expr(value);
455 println!("Break(ref {}, None) = {};", destination_pat, current);
457 // FIXME: implement label printing
459 ExprKind::Continue(ref _destination) => {
460 let destination_pat = self.next("destination");
461 println!("Again(ref {}) = {};", destination_pat, current);
462 // FIXME: implement label printing
464 ExprKind::Ret(ref opt_value) => {
465 if let Some(ref value) = *opt_value {
466 let value_pat = self.next("value");
467 println!("Ret(Some(ref {})) = {};", value_pat, current);
468 self.current = value_pat;
469 self.visit_expr(value);
471 println!("Ret(None) = {};", current);
474 ExprKind::InlineAsm(_, ref _input, ref _output) => {
475 println!("InlineAsm(_, ref input, ref output) = {};", current);
476 println!(" // unimplemented: `ExprKind::InlineAsm` is not further destructured at the moment");
478 ExprKind::Struct(ref path, ref fields, ref opt_base) => {
479 let path_pat = self.next("path");
480 let fields_pat = self.next("fields");
481 if let Some(ref base) = *opt_base {
482 let base_pat = self.next("base");
484 "Struct(ref {}, ref {}, Some(ref {})) = {};",
485 path_pat, fields_pat, base_pat, current
487 self.current = base_pat;
488 self.visit_expr(base);
490 println!("Struct(ref {}, ref {}, None) = {};", path_pat, fields_pat, current);
492 self.current = path_pat;
493 self.print_qpath(path);
494 println!(" if {}.len() == {};", fields_pat, fields.len());
495 println!(" // unimplemented: field checks");
497 // FIXME: compute length (needs type info)
498 ExprKind::Repeat(ref value, _) => {
499 let value_pat = self.next("value");
500 println!("Repeat(ref {}, _) = {};", value_pat, current);
501 println!("// unimplemented: repeat count check");
502 self.current = value_pat;
503 self.visit_expr(value);
506 println!("Err = {}", current);
511 #[allow(clippy::too_many_lines)]
512 fn visit_pat(&mut self, pat: &Pat) {
513 print!(" if let PatKind::");
514 let current = format!("{}.node", self.current);
516 PatKind::Wild => println!("Wild = {};", current),
517 PatKind::Binding(anno, .., ident, ref sub) => {
518 let anno_pat = match anno {
519 BindingAnnotation::Unannotated => "BindingAnnotation::Unannotated",
520 BindingAnnotation::Mutable => "BindingAnnotation::Mutable",
521 BindingAnnotation::Ref => "BindingAnnotation::Ref",
522 BindingAnnotation::RefMut => "BindingAnnotation::RefMut",
524 let name_pat = self.next("name");
525 if let Some(ref sub) = *sub {
526 let sub_pat = self.next("sub");
528 "Binding({}, _, {}, Some(ref {})) = {};",
529 anno_pat, name_pat, sub_pat, current
531 self.current = sub_pat;
534 println!("Binding({}, _, {}, None) = {};", anno_pat, name_pat, current);
536 println!(" if {}.node.as_str() == \"{}\";", name_pat, ident.as_str());
538 PatKind::Struct(ref path, ref fields, ignore) => {
539 let path_pat = self.next("path");
540 let fields_pat = self.next("fields");
542 "Struct(ref {}, ref {}, {}) = {};",
543 path_pat, fields_pat, ignore, current
545 self.current = path_pat;
546 self.print_qpath(path);
547 println!(" if {}.len() == {};", fields_pat, fields.len());
548 println!(" // unimplemented: field checks");
550 PatKind::TupleStruct(ref path, ref fields, skip_pos) => {
551 let path_pat = self.next("path");
552 let fields_pat = self.next("fields");
554 "TupleStruct(ref {}, ref {}, {:?}) = {};",
555 path_pat, fields_pat, skip_pos, current
557 self.current = path_pat;
558 self.print_qpath(path);
559 println!(" if {}.len() == {};", fields_pat, fields.len());
560 println!(" // unimplemented: field checks");
562 PatKind::Path(ref path) => {
563 let path_pat = self.next("path");
564 println!("Path(ref {}) = {};", path_pat, current);
565 self.current = path_pat;
566 self.print_qpath(path);
568 PatKind::Tuple(ref fields, skip_pos) => {
569 let fields_pat = self.next("fields");
570 println!("Tuple(ref {}, {:?}) = {};", fields_pat, skip_pos, current);
571 println!(" if {}.len() == {};", fields_pat, fields.len());
572 println!(" // unimplemented: field checks");
574 PatKind::Box(ref pat) => {
575 let pat_pat = self.next("pat");
576 println!("Box(ref {}) = {};", pat_pat, current);
577 self.current = pat_pat;
580 PatKind::Ref(ref pat, muta) => {
581 let pat_pat = self.next("pat");
582 println!("Ref(ref {}, Mutability::{:?}) = {};", pat_pat, muta, current);
583 self.current = pat_pat;
586 PatKind::Lit(ref lit_expr) => {
587 let lit_expr_pat = self.next("lit_expr");
588 println!("Lit(ref {}) = {}", lit_expr_pat, current);
589 self.current = lit_expr_pat;
590 self.visit_expr(lit_expr);
592 PatKind::Range(ref start, ref end, end_kind) => {
593 let start_pat = self.next("start");
594 let end_pat = self.next("end");
596 "Range(ref {}, ref {}, RangeEnd::{:?}) = {};",
597 start_pat, end_pat, end_kind, current
599 self.current = start_pat;
600 self.visit_expr(start);
601 self.current = end_pat;
602 self.visit_expr(end);
604 PatKind::Slice(ref start, ref middle, ref end) => {
605 let start_pat = self.next("start");
606 let end_pat = self.next("end");
607 if let Some(ref middle) = middle {
608 let middle_pat = self.next("middle");
610 "Slice(ref {}, Some(ref {}), ref {}) = {};",
611 start_pat, middle_pat, end_pat, current
613 self.current = middle_pat;
614 self.visit_pat(middle);
616 println!("Slice(ref {}, None, ref {}) = {};", start_pat, end_pat, current);
618 println!(" if {}.len() == {};", start_pat, start.len());
619 for (i, pat) in start.iter().enumerate() {
620 self.current = format!("{}[{}]", start_pat, i);
623 println!(" if {}.len() == {};", end_pat, end.len());
624 for (i, pat) in end.iter().enumerate() {
625 self.current = format!("{}[{}]", end_pat, i);
632 fn visit_stmt(&mut self, s: &Stmt) {
633 print!(" if let StmtKind::");
634 let current = format!("{}.node", self.current);
636 // A local (let) binding:
637 StmtKind::Local(ref local) => {
638 let local_pat = self.next("local");
639 println!("Local(ref {}) = {};", local_pat, current);
640 if let Some(ref init) = local.init {
641 let init_pat = self.next("init");
642 println!(" if let Some(ref {}) = {}.init;", init_pat, local_pat);
643 self.current = init_pat;
644 self.visit_expr(init);
646 self.current = format!("{}.pat", local_pat);
647 self.visit_pat(&local.pat);
650 StmtKind::Item(_) => {
651 println!("Item(item_id) = {};", current);
654 // Expr without trailing semi-colon (must have unit type):
655 StmtKind::Expr(ref e) => {
656 let e_pat = self.next("e");
657 println!("Expr(ref {}, _) = {}", e_pat, current);
658 self.current = e_pat;
662 // Expr with trailing semi-colon (may have any type):
663 StmtKind::Semi(ref e) => {
664 let e_pat = self.next("e");
665 println!("Semi(ref {}, _) = {}", e_pat, current);
666 self.current = e_pat;
672 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
673 NestedVisitorMap::None
677 fn has_attr(sess: &Session, attrs: &[Attribute]) -> bool {
678 get_attr(sess, attrs, "author").count() > 0
681 fn desugaring_name(des: hir::MatchSource) -> String {
683 hir::MatchSource::ForLoopDesugar => "MatchSource::ForLoopDesugar".to_string(),
684 hir::MatchSource::TryDesugar => "MatchSource::TryDesugar".to_string(),
685 hir::MatchSource::WhileLetDesugar => "MatchSource::WhileLetDesugar".to_string(),
686 hir::MatchSource::Normal => "MatchSource::Normal".to_string(),
687 hir::MatchSource::IfLetDesugar { contains_else_clause } => format!(
688 "MatchSource::IfLetDesugar {{ contains_else_clause: {} }}",
694 fn loop_desugaring_name(des: hir::LoopSource) -> &'static str {
696 hir::LoopSource::ForLoop => "LoopSource::ForLoop",
697 hir::LoopSource::Loop => "LoopSource::Loop",
698 hir::LoopSource::WhileLet => "LoopSource::WhileLet",
702 fn print_path(path: &QPath, first: &mut bool) {
704 QPath::Resolved(_, ref path) => {
705 for segment in &path.segments {
711 print!("{:?}", segment.ident.as_str());
714 QPath::TypeRelative(ref ty, ref segment) => match ty.node {
715 hir::TyKind::Path(ref inner_path) => {
716 print_path(inner_path, first);
722 print!("{:?}", segment.ident.as_str());
724 ref other => print!("/* unimplemented: {:?}*/", other),