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, Expr_, QPath, Ty_, Pat, PatKind, BindingAnnotation, StmtSemi, StmtExpr, StmtDecl, Decl_, Stmt};
9 use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
10 use syntax::ast::{self, Attribute, LitKind, DUMMY_NODE_ID};
11 use std::collections::HashMap;
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 Expr_::ExprIf(ref cond, ref then, None) = item.node,
35 /// if let Expr_::ExprBinary(BinOp::Eq, ref left, ref right) = cond.node,
36 /// if let Expr_::ExprPath(ref path) = left.node,
37 /// if let Expr_::ExprLit(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 {
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: HashMap<&'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 Expr_::Expr");
195 let current = format!("{}.node", self.current);
197 Expr_::ExprBox(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 Expr_::ExprArray(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 Expr_::ExprCall(ref _func, ref _args) => {
213 println!("Call(ref func, ref args) = {};", current);
214 println!(" // unimplemented: `ExprCall` is not further destructured at the moment");
216 Expr_::ExprMethodCall(ref _method_name, ref _generics, ref _args) => {
217 println!("MethodCall(ref method_name, ref generics, ref args) = {};", current);
218 println!(" // unimplemented: `ExprMethodCall` is not further destructured at the moment");
220 Expr_::ExprTup(ref elements) => {
221 let elements_pat = self.next("elements");
222 println!("Tup(ref {}) = {};", elements_pat, current);
223 println!(" if {}.len() == {};", elements_pat, elements.len());
224 for (i, element) in elements.iter().enumerate() {
225 self.current = format!("{}[{}]", elements_pat, i);
226 self.visit_expr(element);
229 Expr_::ExprBinary(ref op, ref left, ref right) => {
230 let op_pat = self.next("op");
231 let left_pat = self.next("left");
232 let right_pat = self.next("right");
233 println!("Binary(ref {}, ref {}, ref {}) = {};", op_pat, left_pat, right_pat, current);
234 println!(" if BinOp_::{:?} == {}.node;", op.node, op_pat);
235 self.current = left_pat;
236 self.visit_expr(left);
237 self.current = right_pat;
238 self.visit_expr(right);
240 Expr_::ExprUnary(ref op, ref inner) => {
241 let inner_pat = self.next("inner");
242 println!("Unary(UnOp::{:?}, ref {}) = {};", op, inner_pat, current);
243 self.current = inner_pat;
244 self.visit_expr(inner);
246 Expr_::ExprLit(ref lit) => {
247 let lit_pat = self.next("lit");
248 println!("Lit(ref {}) = {};", lit_pat, current);
250 LitKind::Bool(val) => println!(" if let LitKind::Bool({:?}) = {}.node;", val, lit_pat),
251 LitKind::Char(c) => println!(" if let LitKind::Char({:?}) = {}.node;", c, lit_pat),
252 LitKind::Byte(b) => println!(" if let LitKind::Byte({}) = {}.node;", b, lit_pat),
253 // FIXME: also check int type
254 LitKind::Int(i, _) => println!(" if let LitKind::Int({}, _) = {}.node;", i, lit_pat),
255 LitKind::Float(..) => println!(" if let LitKind::Float(..) = {}.node;", lit_pat),
256 LitKind::FloatUnsuffixed(_) => {
257 println!(" if let LitKind::FloatUnsuffixed(_) = {}.node;", lit_pat)
259 LitKind::ByteStr(ref vec) => {
260 let vec_pat = self.next("vec");
261 println!(" if let LitKind::ByteStr(ref {}) = {}.node;", vec_pat, lit_pat);
262 println!(" if let [{:?}] = **{};", vec, vec_pat);
264 LitKind::Str(ref text, _) => {
265 let str_pat = self.next("s");
266 println!(" if let LitKind::Str(ref {}) = {}.node;", str_pat, lit_pat);
267 println!(" if {}.as_str() == {:?}", str_pat, &*text.as_str())
271 Expr_::ExprCast(ref expr, ref ty) => {
272 let cast_pat = self.next("expr");
273 let cast_ty = self.next("cast_ty");
274 let qp_label = self.next("qp");
276 println!("Cast(ref {}, ref {}) = {};", cast_pat, cast_ty, current);
277 if let Ty_::TyPath(ref qp) = ty.node {
278 println!(" if let Ty_::TyPath(ref {}) = {}.node;", qp_label, cast_ty);
279 self.current = qp_label;
280 self.print_qpath(qp);
282 self.current = cast_pat;
283 self.visit_expr(expr);
285 Expr_::ExprType(ref expr, ref _ty) => {
286 let cast_pat = self.next("expr");
287 println!("Type(ref {}, _) = {};", cast_pat, current);
288 self.current = cast_pat;
289 self.visit_expr(expr);
291 Expr_::ExprIf(ref cond, ref then, ref opt_else) => {
292 let cond_pat = self.next("cond");
293 let then_pat = self.next("then");
294 if let Some(ref else_) = *opt_else {
295 let else_pat = self.next("else_");
296 println!("If(ref {}, ref {}, Some(ref {})) = {};", cond_pat, then_pat, else_pat, current);
297 self.current = else_pat;
298 self.visit_expr(else_);
300 println!("If(ref {}, ref {}, None) = {};", cond_pat, then_pat, current);
302 self.current = cond_pat;
303 self.visit_expr(cond);
304 self.current = then_pat;
305 self.visit_expr(then);
307 Expr_::ExprWhile(ref cond, ref body, _) => {
308 let cond_pat = self.next("cond");
309 let body_pat = self.next("body");
310 let label_pat = self.next("label");
311 println!("While(ref {}, ref {}, ref {}) = {};", cond_pat, body_pat, label_pat, current);
312 self.current = cond_pat;
313 self.visit_expr(cond);
314 self.current = body_pat;
315 self.visit_block(body);
317 Expr_::ExprLoop(ref body, _, desugaring) => {
318 let body_pat = self.next("body");
319 let des = loop_desugaring_name(desugaring);
320 let label_pat = self.next("label");
321 println!("Loop(ref {}, ref {}, {}) = {};", body_pat, label_pat, des, current);
322 self.current = body_pat;
323 self.visit_block(body);
325 Expr_::ExprMatch(ref expr, ref arms, desugaring) => {
326 let des = desugaring_name(desugaring);
327 let expr_pat = self.next("expr");
328 let arms_pat = self.next("arms");
329 println!("Match(ref {}, ref {}, {}) = {};", expr_pat, arms_pat, des, current);
330 self.current = expr_pat;
331 self.visit_expr(expr);
332 println!(" if {}.len() == {};", arms_pat, arms.len());
333 for (i, arm) in arms.iter().enumerate() {
334 self.current = format!("{}[{}].body", arms_pat, i);
335 self.visit_expr(&arm.body);
336 if let Some(ref guard) = arm.guard {
337 let guard_pat = self.next("guard");
338 println!(" if let Some(ref {}) = {}[{}].guard", guard_pat, arms_pat, i);
339 self.current = guard_pat;
340 self.visit_expr(guard);
342 println!(" if {}[{}].pats.len() == {};", arms_pat, i, arm.pats.len());
343 for (j, pat) in arm.pats.iter().enumerate() {
344 self.current = format!("{}[{}].pats[{}]", arms_pat, i, j);
349 Expr_::ExprClosure(ref _capture_clause, ref _func, _, _, _) => {
350 println!("Closure(ref capture_clause, ref func, _, _, _) = {};", current);
351 println!(" // unimplemented: `ExprClosure` is not further destructured at the moment");
353 Expr_::ExprYield(ref sub) => {
354 let sub_pat = self.next("sub");
355 println!("Yield(ref sub) = {};", current);
356 self.current = sub_pat;
357 self.visit_expr(sub);
359 Expr_::ExprBlock(ref block) => {
360 let block_pat = self.next("block");
361 println!("Block(ref {}) = {};", block_pat, current);
362 self.current = block_pat;
363 self.visit_block(block);
365 Expr_::ExprAssign(ref target, ref value) => {
366 let target_pat = self.next("target");
367 let value_pat = self.next("value");
368 println!("Assign(ref {}, ref {}) = {};", target_pat, value_pat, current);
369 self.current = target_pat;
370 self.visit_expr(target);
371 self.current = value_pat;
372 self.visit_expr(value);
374 Expr_::ExprAssignOp(ref op, ref target, ref value) => {
375 let op_pat = self.next("op");
376 let target_pat = self.next("target");
377 let value_pat = self.next("value");
378 println!("AssignOp(ref {}, ref {}, ref {}) = {};", op_pat, target_pat, value_pat, current);
379 println!(" if BinOp_::{:?} == {}.node;", op.node, op_pat);
380 self.current = target_pat;
381 self.visit_expr(target);
382 self.current = value_pat;
383 self.visit_expr(value);
385 Expr_::ExprField(ref object, ref field_name) => {
386 let obj_pat = self.next("object");
387 let field_name_pat = self.next("field_name");
388 println!("Field(ref {}, ref {}) = {};", obj_pat, field_name_pat, current);
389 println!(" if {}.node.as_str() == {:?}", field_name_pat, field_name.node.as_str());
390 self.current = obj_pat;
391 self.visit_expr(object);
393 Expr_::ExprIndex(ref object, ref index) => {
394 let object_pat = self.next("object");
395 let index_pat = self.next("index");
396 println!("Index(ref {}, ref {}) = {};", object_pat, index_pat, current);
397 self.current = object_pat;
398 self.visit_expr(object);
399 self.current = index_pat;
400 self.visit_expr(index);
402 Expr_::ExprPath(ref path) => {
403 let path_pat = self.next("path");
404 println!("Path(ref {}) = {};", path_pat, current);
405 self.current = path_pat;
406 self.print_qpath(path);
408 Expr_::ExprAddrOf(mutability, ref inner) => {
409 let inner_pat = self.next("inner");
410 println!("AddrOf({:?}, ref {}) = {};", mutability, inner_pat, current);
411 self.current = inner_pat;
412 self.visit_expr(inner);
414 Expr_::ExprBreak(ref _destination, ref opt_value) => {
415 let destination_pat = self.next("destination");
416 if let Some(ref value) = *opt_value {
417 let value_pat = self.next("value");
418 println!("Break(ref {}, Some(ref {})) = {};", destination_pat, value_pat, current);
419 self.current = value_pat;
420 self.visit_expr(value);
422 println!("Break(ref {}, None) = {};", destination_pat, current);
424 // FIXME: implement label printing
426 Expr_::ExprAgain(ref _destination) => {
427 let destination_pat = self.next("destination");
428 println!("Again(ref {}) = {};", destination_pat, current);
429 // FIXME: implement label printing
431 Expr_::ExprRet(ref opt_value) => if let Some(ref value) = *opt_value {
432 let value_pat = self.next("value");
433 println!("Ret(Some(ref {})) = {};", value_pat, current);
434 self.current = value_pat;
435 self.visit_expr(value);
437 println!("Ret(None) = {};", current);
439 Expr_::ExprInlineAsm(_, ref _input, ref _output) => {
440 println!("InlineAsm(_, ref input, ref output) = {};", current);
441 println!(" // unimplemented: `ExprInlineAsm` is not further destructured at the moment");
443 Expr_::ExprStruct(ref path, ref fields, ref opt_base) => {
444 let path_pat = self.next("path");
445 let fields_pat = self.next("fields");
446 if let Some(ref base) = *opt_base {
447 let base_pat = self.next("base");
449 "Struct(ref {}, ref {}, Some(ref {})) = {};",
455 self.current = base_pat;
456 self.visit_expr(base);
458 println!("Struct(ref {}, ref {}, None) = {};", path_pat, fields_pat, current);
460 self.current = path_pat;
461 self.print_qpath(path);
462 println!(" if {}.len() == {};", fields_pat, fields.len());
463 println!(" // unimplemented: field checks");
465 // FIXME: compute length (needs type info)
466 Expr_::ExprRepeat(ref value, _) => {
467 let value_pat = self.next("value");
468 println!("Repeat(ref {}, _) = {};", value_pat, current);
469 println!("// unimplemented: repeat count check");
470 self.current = value_pat;
471 self.visit_expr(value);
476 fn visit_pat(&mut self, pat: &Pat) {
477 print!(" if let PatKind::");
478 let current = format!("{}.node", self.current);
480 PatKind::Wild => println!("Wild = {};", current),
481 PatKind::Binding(anno, _, name, ref sub) => {
482 let anno_pat = match anno {
483 BindingAnnotation::Unannotated => "BindingAnnotation::Unannotated",
484 BindingAnnotation::Mutable => "BindingAnnotation::Mutable",
485 BindingAnnotation::Ref => "BindingAnnotation::Ref",
486 BindingAnnotation::RefMut => "BindingAnnotation::RefMut",
488 let name_pat = self.next("name");
489 if let Some(ref sub) = *sub {
490 let sub_pat = self.next("sub");
491 println!("Binding({}, _, {}, Some(ref {})) = {};", anno_pat, name_pat, sub_pat, current);
492 self.current = sub_pat;
495 println!("Binding({}, _, {}, None) = {};", anno_pat, name_pat, current);
497 println!(" if {}.node.as_str() == \"{}\";", name_pat, name.node.as_str());
499 PatKind::Struct(ref path, ref fields, ignore) => {
500 let path_pat = self.next("path");
501 let fields_pat = self.next("fields");
502 println!("Struct(ref {}, ref {}, {}) = {};", path_pat, fields_pat, ignore, current);
503 self.current = path_pat;
504 self.print_qpath(path);
505 println!(" if {}.len() == {};", fields_pat, fields.len());
506 println!(" // unimplemented: field checks");
508 PatKind::TupleStruct(ref path, ref fields, skip_pos) => {
509 let path_pat = self.next("path");
510 let fields_pat = self.next("fields");
511 println!("TupleStruct(ref {}, ref {}, {:?}) = {};", path_pat, fields_pat, skip_pos, 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::Path(ref path) => {
518 let path_pat = self.next("path");
519 println!("Path(ref {}) = {};", path_pat, current);
520 self.current = path_pat;
521 self.print_qpath(path);
523 PatKind::Tuple(ref fields, skip_pos) => {
524 let fields_pat = self.next("fields");
525 println!("Tuple(ref {}, {:?}) = {};", fields_pat, skip_pos, current);
526 println!(" if {}.len() == {};", fields_pat, fields.len());
527 println!(" // unimplemented: field checks");
529 PatKind::Box(ref pat) => {
530 let pat_pat = self.next("pat");
531 println!("Box(ref {}) = {};", pat_pat, current);
532 self.current = pat_pat;
535 PatKind::Ref(ref pat, muta) => {
536 let pat_pat = self.next("pat");
537 println!("Ref(ref {}, Mutability::{:?}) = {};", pat_pat, muta, current);
538 self.current = pat_pat;
541 PatKind::Lit(ref lit_expr) => {
542 let lit_expr_pat = self.next("lit_expr");
543 println!("Lit(ref {}) = {}", lit_expr_pat, current);
544 self.current = lit_expr_pat;
545 self.visit_expr(lit_expr);
547 PatKind::Range(ref start, ref end, end_kind) => {
548 let start_pat = self.next("start");
549 let end_pat = self.next("end");
550 println!("Range(ref {}, ref {}, RangeEnd::{:?}) = {};", start_pat, end_pat, end_kind, current);
551 self.current = start_pat;
552 self.visit_expr(start);
553 self.current = end_pat;
554 self.visit_expr(end);
556 PatKind::Slice(ref start, ref middle, ref end) => {
557 let start_pat = self.next("start");
558 let end_pat = self.next("end");
559 if let Some(ref middle) = middle {
560 let middle_pat = self.next("middle");
561 println!("Slice(ref {}, Some(ref {}), ref {}) = {};", start_pat, middle_pat, end_pat, current);
562 self.current = middle_pat;
563 self.visit_pat(middle);
565 println!("Slice(ref {}, None, ref {}) = {};", start_pat, end_pat, current);
567 println!(" if {}.len() == {};", start_pat, start.len());
568 for (i, pat) in start.iter().enumerate() {
569 self.current = format!("{}[{}]", start_pat, i);
572 println!(" if {}.len() == {};", end_pat, end.len());
573 for (i, pat) in end.iter().enumerate() {
574 self.current = format!("{}[{}]", end_pat, i);
581 fn visit_stmt(&mut self, s: &Stmt) {
582 print!(" if let Stmt_::");
583 let current = format!("{}.node", self.current);
585 // Could be an item or a local (let) binding:
586 StmtDecl(ref decl, _) => {
587 let decl_pat = self.next("decl");
588 println!("StmtDecl(ref {}, _) = {}", decl_pat, current);
589 print!(" if let Decl_::");
590 let current = format!("{}.node", decl_pat);
592 // A local (let) binding:
593 Decl_::DeclLocal(ref local) => {
594 let local_pat = self.next("local");
595 println!("DeclLocal(ref {}) = {};", local_pat, current);
596 if let Some(ref init) = local.init {
597 let init_pat = self.next("init");
598 println!(" if let Some(ref {}) = {}.init", init_pat, local_pat);
599 self.current = init_pat;
600 self.visit_expr(init);
602 self.current = format!("{}.pat", local_pat);
603 self.visit_pat(&local.pat);
606 Decl_::DeclItem(_) => {
607 println!("DeclItem(item_id) = {};", current);
612 // Expr without trailing semi-colon (must have unit type):
613 StmtExpr(ref e, _) => {
614 let e_pat = self.next("e");
615 println!("StmtExpr(ref {}, _) = {}", e_pat, current);
616 self.current = e_pat;
620 // Expr with trailing semi-colon (may have any type):
621 StmtSemi(ref e, _) => {
622 let e_pat = self.next("e");
623 println!("StmtSemi(ref {}, _) = {}", e_pat, current);
624 self.current = e_pat;
630 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
631 NestedVisitorMap::None
635 fn has_attr(attrs: &[Attribute]) -> bool {
636 attrs.iter().any(|attr| {
637 attr.check_name("clippy") && attr.meta_item_list().map_or(false, |list| {
638 list.len() == 1 && match list[0].node {
639 ast::NestedMetaItemKind::MetaItem(ref it) => it.name() == "author",
640 ast::NestedMetaItemKind::Literal(_) => false,
646 fn desugaring_name(des: hir::MatchSource) -> String {
648 hir::MatchSource::ForLoopDesugar => "MatchSource::ForLoopDesugar".to_string(),
649 hir::MatchSource::TryDesugar => "MatchSource::TryDesugar".to_string(),
650 hir::MatchSource::WhileLetDesugar => "MatchSource::WhileLetDesugar".to_string(),
651 hir::MatchSource::Normal => "MatchSource::Normal".to_string(),
652 hir::MatchSource::IfLetDesugar { contains_else_clause } => format!("MatchSource::IfLetDesugar {{ contains_else_clause: {} }}", contains_else_clause),
656 fn loop_desugaring_name(des: hir::LoopSource) -> &'static str {
658 hir::LoopSource::ForLoop => "LoopSource::ForLoop",
659 hir::LoopSource::Loop => "LoopSource::Loop",
660 hir::LoopSource::WhileLet => "LoopSource::WhileLet",
664 fn print_path(path: &QPath, first: &mut bool) {
666 QPath::Resolved(_, ref path) => for segment in &path.segments {
672 print!("{:?}", segment.name.as_str());
674 QPath::TypeRelative(ref ty, ref segment) => match ty.node {
675 hir::Ty_::TyPath(ref inner_path) => {
676 print_path(inner_path, first);
682 print!("{:?}", segment.name.as_str());
684 ref other => print!("/* unimplemented: {:?}*/", other),