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_};
9 use rustc::hir::intravisit::{NestedVisitorMap, Visitor, walk_decl};
11 use syntax::ast::{self, Attribute, LitKind, NodeId, DUMMY_NODE_ID};
12 use syntax::codemap::Span;
13 use std::collections::HashMap;
15 /// **What it does:** Generates clippy code that detects the offending pattern
20 /// // detect the following pattern
23 /// // but ignore everything from here on
24 /// #![clippy(author = "ignore")]
33 /// if let Expr_::ExprIf(ref cond, ref then, None) = item.node,
34 /// if let Expr_::ExprBinary(BinOp::Eq, ref left, ref right) = cond.node,
35 /// if let Expr_::ExprPath(ref path) = left.node,
36 /// if let Expr_::ExprLit(ref lit) = right.node,
37 /// if let LitKind::Int(42, _) = lit.node,
39 /// // report your lint here
46 "helper for writing lints"
51 impl LintPass for Pass {
52 fn get_lints(&self) -> LintArray {
53 lint_array!(LINT_AUTHOR)
58 println!("if_chain! {{");
63 println!(" // report your lint here");
68 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
69 fn check_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
70 if !has_attr(&item.attrs) {
74 PrintVisitor::new("item").visit_item(item);
78 fn check_impl_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem) {
79 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
178 struct PrintVisitor {
179 /// Fields are the current index that needs to be appended to pattern
181 ids: HashMap<&'static str, usize>,
182 /// the name that needs to be destructured
186 impl<'tcx> Visitor<'tcx> for PrintVisitor {
187 fn visit_decl(&mut self, d: &'tcx Decl) {
189 hir::DeclLocal(ref local) => {
190 self.visit_pat(&local.pat);
191 if let Some(ref e) = local.init {
195 _ => walk_decl(self, d)
199 fn visit_expr(&mut self, expr: &Expr) {
200 print!(" if let Expr_::Expr");
201 let current = format!("{}.node", self.current);
203 Expr_::ExprBox(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 Expr_::ExprArray(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 Expr_::ExprCall(ref _func, ref _args) => {
219 println!("Call(ref func, ref args) = {};", current);
220 println!(" // unimplemented: `ExprCall` is not further destructured at the moment");
222 Expr_::ExprMethodCall(ref _method_name, ref _generics, ref _args) => {
223 println!("MethodCall(ref method_name, ref generics, ref args) = {};", current);
224 println!(" // unimplemented: `ExprMethodCall` is not further destructured at the moment");
226 Expr_::ExprTup(ref elements) => {
227 let elements_pat = self.next("elements");
228 println!("Tup(ref {}) = {};", elements_pat, current);
229 println!(" if {}.len() == {};", elements_pat, elements.len());
230 for (i, element) in elements.iter().enumerate() {
231 self.current = format!("{}[{}]", elements_pat, i);
232 self.visit_expr(element);
235 Expr_::ExprBinary(ref op, ref left, ref right) => {
236 let op_pat = self.next("op");
237 let left_pat = self.next("left");
238 let right_pat = self.next("right");
239 println!("Binary(ref {}, ref {}, ref {}) = {};", op_pat, left_pat, right_pat, current);
240 println!(" if BinOp_::{:?} == {}.node;", op.node, op_pat);
241 self.current = left_pat;
242 self.visit_expr(left);
243 self.current = right_pat;
244 self.visit_expr(right);
246 Expr_::ExprUnary(ref op, ref inner) => {
247 let inner_pat = self.next("inner");
248 println!("Unary(UnOp::{:?}, ref {}) = {};", op, inner_pat, current);
249 self.current = inner_pat;
250 self.visit_expr(inner);
252 Expr_::ExprLit(ref lit) => {
253 let lit_pat = self.next("lit");
254 println!("Lit(ref {}) = {};", lit_pat, current);
256 LitKind::Bool(val) => println!(" if let LitKind::Bool({:?}) = {}.node;", val, lit_pat),
257 LitKind::Char(c) => println!(" if let LitKind::Char({:?}) = {}.node;", c, lit_pat),
258 LitKind::Byte(b) => println!(" if let LitKind::Byte({}) = {}.node;", b, lit_pat),
259 // FIXME: also check int type
260 LitKind::Int(i, _) => println!(" if let LitKind::Int({}, _) = {}.node;", i, lit_pat),
261 LitKind::Float(..) => println!(" if let LitKind::Float(..) = {}.node;", lit_pat),
262 LitKind::FloatUnsuffixed(_) => {
263 println!(" if let LitKind::FloatUnsuffixed(_) = {}.node;", lit_pat)
265 LitKind::ByteStr(ref vec) => {
266 let vec_pat = self.next("vec");
267 println!(" if let LitKind::ByteStr(ref {}) = {}.node;", vec_pat, lit_pat);
268 println!(" if let [{:?}] = **{};", vec, vec_pat);
270 LitKind::Str(ref text, _) => {
271 let str_pat = self.next("s");
272 println!(" if let LitKind::Str(ref {}) = {}.node;", str_pat, lit_pat);
273 println!(" if {}.as_str() == {:?}", str_pat, &*text.as_str())
277 Expr_::ExprCast(ref expr, ref ty) => {
278 let cast_pat = self.next("expr");
279 let cast_ty = self.next("cast_ty");
280 let qp_label = self.next("qp");
282 println!("Cast(ref {}, ref {}) = {};", cast_pat, cast_ty, current);
283 if let Ty_::TyPath(ref qp) = ty.node {
284 println!(" if let Ty_::TyPath(ref {}) = {}.node;", qp_label, cast_ty);
285 self.current = qp_label;
286 self.visit_qpath(&qp, ty.id, ty.span);
288 self.current = cast_pat;
289 self.visit_expr(expr);
291 Expr_::ExprType(ref expr, ref _ty) => {
292 let cast_pat = self.next("expr");
293 println!("Type(ref {}, _) = {};", cast_pat, current);
294 self.current = cast_pat;
295 self.visit_expr(expr);
297 Expr_::ExprIf(ref cond, ref then, ref opt_else) => {
298 let cond_pat = self.next("cond");
299 let then_pat = self.next("then");
300 if let Some(ref else_) = *opt_else {
301 let else_pat = self.next("else_");
302 println!("If(ref {}, ref {}, Some(ref {})) = {};", cond_pat, then_pat, else_pat, current);
303 self.current = else_pat;
304 self.visit_expr(else_);
306 println!("If(ref {}, ref {}, None) = {};", cond_pat, then_pat, current);
308 self.current = cond_pat;
309 self.visit_expr(cond);
310 self.current = then_pat;
311 self.visit_expr(then);
313 Expr_::ExprWhile(ref cond, ref body, _) => {
314 let cond_pat = self.next("cond");
315 let body_pat = self.next("body");
316 let label_pat = self.next("label");
317 println!("While(ref {}, ref {}, ref {}) = {};", cond_pat, body_pat, label_pat, current);
318 self.current = cond_pat;
319 self.visit_expr(cond);
320 self.current = body_pat;
321 self.visit_block(body);
323 Expr_::ExprLoop(ref body, _, desugaring) => {
324 let body_pat = self.next("body");
325 let des = loop_desugaring_name(desugaring);
326 let label_pat = self.next("label");
327 println!("Loop(ref {}, ref {}, {}) = {};", body_pat, label_pat, des, current);
328 self.current = body_pat;
329 self.visit_block(body);
331 Expr_::ExprMatch(ref _expr, ref _arms, desugaring) => {
332 let des = desugaring_name(desugaring);
333 println!("Match(ref expr, ref arms, {}) = {};", des, current);
334 println!(" // unimplemented: `ExprMatch` is not further destructured at the moment");
336 Expr_::ExprClosure(ref _capture_clause, ref _func, _, _, _) => {
337 println!("Closure(ref capture_clause, ref func, _, _, _) = {};", current);
338 println!(" // unimplemented: `ExprClosure` is not further destructured at the moment");
340 Expr_::ExprYield(ref sub) => {
341 let sub_pat = self.next("sub");
342 println!("Yield(ref sub) = {};", current);
343 self.current = sub_pat;
344 self.visit_expr(sub);
346 Expr_::ExprBlock(ref block) => {
347 let block_pat = self.next("block");
348 println!("Block(ref {}) = {};", block_pat, current);
349 self.current = block_pat;
350 self.visit_block(block);
352 Expr_::ExprAssign(ref target, ref value) => {
353 let target_pat = self.next("target");
354 let value_pat = self.next("value");
355 println!("Assign(ref {}, ref {}) = {};", target_pat, value_pat, current);
356 self.current = target_pat;
357 self.visit_expr(target);
358 self.current = value_pat;
359 self.visit_expr(value);
361 Expr_::ExprAssignOp(ref op, ref target, ref value) => {
362 let op_pat = self.next("op");
363 let target_pat = self.next("target");
364 let value_pat = self.next("value");
365 println!("AssignOp(ref {}, ref {}, ref {}) = {};", op_pat, target_pat, value_pat, current);
366 println!(" if BinOp_::{:?} == {}.node;", op.node, op_pat);
367 self.current = target_pat;
368 self.visit_expr(target);
369 self.current = value_pat;
370 self.visit_expr(value);
372 Expr_::ExprField(ref object, ref field_name) => {
373 let obj_pat = self.next("object");
374 let field_name_pat = self.next("field_name");
375 println!("Field(ref {}, ref {}) = {};", obj_pat, field_name_pat, current);
376 println!(" if {}.node.as_str() == {:?}", field_name_pat, field_name.node.as_str());
377 self.current = obj_pat;
378 self.visit_expr(object);
380 Expr_::ExprTupField(ref object, ref field_id) => {
381 let obj_pat = self.next("object");
382 let field_id_pat = self.next("field_id");
383 println!("TupField(ref {}, ref {}) = {};", obj_pat, field_id_pat, current);
384 println!(" if {}.node == {}", field_id_pat, field_id.node);
385 self.current = obj_pat;
386 self.visit_expr(object);
388 Expr_::ExprIndex(ref object, ref index) => {
389 let object_pat = self.next("object");
390 let index_pat = self.next("index");
391 println!("Index(ref {}, ref {}) = {};", object_pat, index_pat, current);
392 self.current = object_pat;
393 self.visit_expr(object);
394 self.current = index_pat;
395 self.visit_expr(index);
397 Expr_::ExprPath(ref path) => {
398 let path_pat = self.next("path");
399 println!("Path(ref {}) = {};", path_pat, current);
400 self.current = path_pat;
401 self.visit_qpath(path, expr.id, expr.span);
403 Expr_::ExprAddrOf(mutability, ref inner) => {
404 let inner_pat = self.next("inner");
405 println!("AddrOf({:?}, ref {}) = {};", mutability, inner_pat, current);
406 self.current = inner_pat;
407 self.visit_expr(inner);
409 Expr_::ExprBreak(ref _destination, ref opt_value) => {
410 let destination_pat = self.next("destination");
411 if let Some(ref value) = *opt_value {
412 let value_pat = self.next("value");
413 println!("Break(ref {}, Some(ref {})) = {};", destination_pat, value_pat, current);
414 self.current = value_pat;
415 self.visit_expr(value);
417 println!("Break(ref {}, None) = {};", destination_pat, current);
419 // FIXME: implement label printing
421 Expr_::ExprAgain(ref _destination) => {
422 let destination_pat = self.next("destination");
423 println!("Again(ref {}) = {};", destination_pat, current);
424 // FIXME: implement label printing
426 Expr_::ExprRet(ref opt_value) => if let Some(ref value) = *opt_value {
427 let value_pat = self.next("value");
428 println!("Ret(Some(ref {})) = {};", value_pat, current);
429 self.current = value_pat;
430 self.visit_expr(value);
432 println!("Ret(None) = {};", current);
434 Expr_::ExprInlineAsm(_, ref _input, ref _output) => {
435 println!("InlineAsm(_, ref input, ref output) = {};", current);
436 println!(" // unimplemented: `ExprInlineAsm` is not further destructured at the moment");
438 Expr_::ExprStruct(ref path, ref fields, ref opt_base) => {
439 let path_pat = self.next("path");
440 let fields_pat = self.next("fields");
441 if let Some(ref base) = *opt_base {
442 let base_pat = self.next("base");
444 "Struct(ref {}, ref {}, Some(ref {})) = {};",
450 self.current = base_pat;
451 self.visit_expr(base);
453 println!("Struct(ref {}, ref {}, None) = {};", path_pat, fields_pat, current);
455 self.current = path_pat;
456 self.visit_qpath(path, expr.id, expr.span);
457 println!(" if {}.len() == {};", fields_pat, fields.len());
458 println!(" // unimplemented: field checks");
460 // FIXME: compute length (needs type info)
461 Expr_::ExprRepeat(ref value, _) => {
462 let value_pat = self.next("value");
463 println!("Repeat(ref {}, _) = {};", value_pat, current);
464 println!("// unimplemented: repeat count check");
465 self.current = value_pat;
466 self.visit_expr(value);
471 fn visit_qpath(&mut self, path: &QPath, _: NodeId, _: Span) {
472 print!(" if match_qpath({}, &[", self.current);
473 print_path(path, &mut true);
476 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
477 NestedVisitorMap::None
481 fn has_attr(attrs: &[Attribute]) -> bool {
482 attrs.iter().any(|attr| {
483 attr.check_name("clippy") && attr.meta_item_list().map_or(false, |list| {
484 list.len() == 1 && match list[0].node {
485 ast::NestedMetaItemKind::MetaItem(ref it) => it.name == "author",
486 ast::NestedMetaItemKind::Literal(_) => false,
492 fn desugaring_name(des: hir::MatchSource) -> String {
494 hir::MatchSource::ForLoopDesugar => "MatchSource::ForLoopDesugar".to_string(),
495 hir::MatchSource::TryDesugar => "MatchSource::TryDesugar".to_string(),
496 hir::MatchSource::WhileLetDesugar => "MatchSource::WhileLetDesugar".to_string(),
497 hir::MatchSource::Normal => "MatchSource::Normal".to_string(),
498 hir::MatchSource::IfLetDesugar { contains_else_clause } => format!("MatchSource::IfLetDesugar {{ contains_else_clause: {} }}", contains_else_clause),
502 fn loop_desugaring_name(des: hir::LoopSource) -> &'static str {
504 hir::LoopSource::ForLoop => "LoopSource::ForLoop",
505 hir::LoopSource::Loop => "LoopSource::Loop",
506 hir::LoopSource::WhileLet => "LoopSource::WhileLet",
510 fn print_path(path: &QPath, first: &mut bool) {
512 QPath::Resolved(_, ref path) => for segment in &path.segments {
518 print!("{:?}", segment.name.as_str());
520 QPath::TypeRelative(ref ty, ref segment) => match ty.node {
521 hir::Ty_::TyPath(ref inner_path) => {
522 print_path(inner_path, first);
528 print!("{:?}", segment.name.as_str());
530 ref other => print!("/* unimplemented: {:?}*/", other),