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};
9 use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
10 use syntax::ast::{self, Attribute, LitKind, NodeId, DUMMY_NODE_ID};
11 use syntax::codemap::Span;
12 use std::collections::HashMap;
14 /// **What it does:** Generates clippy code that detects the offending pattern
19 /// // detect the following pattern
22 /// // but ignore everything from here on
23 /// #![clippy(author = "ignore")]
32 /// if let Expr_::ExprIf(ref cond, ref then, None) = item.node,
33 /// if let Expr_::ExprBinary(BinOp::Eq, ref left, ref right) = cond.node,
34 /// if let Expr_::ExprPath(ref path) = left.node,
35 /// if let Expr_::ExprLit(ref lit) = right.node,
36 /// if let LitKind::Int(42, _) = lit.node,
38 /// // report your lint here
45 "helper for writing lints"
50 impl LintPass for Pass {
51 fn get_lints(&self) -> LintArray {
52 lint_array!(LINT_AUTHOR)
57 println!("if_chain! {{");
62 println!(" // report your lint here");
67 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
68 fn check_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
69 if !has_attr(&item.attrs) {
73 PrintVisitor::new("item").visit_item(item);
77 fn check_impl_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem) {
78 if !has_attr(&item.attrs) {
82 PrintVisitor::new("item").visit_impl_item(item);
86 fn check_trait_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
87 if !has_attr(&item.attrs) {
91 PrintVisitor::new("item").visit_trait_item(item);
95 fn check_variant(&mut self, _cx: &LateContext<'a, 'tcx>, var: &'tcx hir::Variant, generics: &hir::Generics) {
96 if !has_attr(&var.node.attrs) {
100 PrintVisitor::new("var").visit_variant(var, generics, DUMMY_NODE_ID);
104 fn check_struct_field(&mut self, _cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField) {
105 if !has_attr(&field.attrs) {
109 PrintVisitor::new("field").visit_struct_field(field);
113 fn check_expr(&mut self, _cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
114 if !has_attr(&expr.attrs) {
118 PrintVisitor::new("expr").visit_expr(expr);
122 fn check_arm(&mut self, _cx: &LateContext<'a, 'tcx>, arm: &'tcx hir::Arm) {
123 if !has_attr(&arm.attrs) {
127 PrintVisitor::new("arm").visit_arm(arm);
131 fn check_stmt(&mut self, _cx: &LateContext<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
132 if !has_attr(stmt.node.attrs()) {
136 PrintVisitor::new("stmt").visit_stmt(stmt);
140 fn check_foreign_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ForeignItem) {
141 if !has_attr(&item.attrs) {
145 PrintVisitor::new("item").visit_foreign_item(item);
151 fn new(s: &'static str) -> Self {
154 current: s.to_owned(),
158 fn next(&mut self, s: &'static str) -> String {
159 use std::collections::hash_map::Entry::*;
160 match self.ids.entry(s) {
161 // already there: start numbering from `1`
162 Occupied(mut occ) => {
163 let val = occ.get_mut();
165 format!("{}{}", s, *val)
167 // not there: insert and return name as given
176 struct PrintVisitor {
177 /// Fields are the current index that needs to be appended to pattern
179 ids: HashMap<&'static str, usize>,
180 /// the name that needs to be destructured
184 impl<'tcx> Visitor<'tcx> for PrintVisitor {
185 fn visit_expr(&mut self, expr: &Expr) {
186 print!(" if let Expr_::Expr");
187 let current = format!("{}.node", self.current);
189 Expr_::ExprBox(ref inner) => {
190 let inner_pat = self.next("inner");
191 println!("Box(ref {}) = {};", inner_pat, current);
192 self.current = inner_pat;
193 self.visit_expr(inner);
195 Expr_::ExprArray(ref elements) => {
196 let elements_pat = self.next("elements");
197 println!("Array(ref {}) = {};", elements_pat, current);
198 println!(" if {}.len() == {};", elements_pat, elements.len());
199 for (i, element) in elements.iter().enumerate() {
200 self.current = format!("{}[{}]", elements_pat, i);
201 self.visit_expr(element);
204 Expr_::ExprCall(ref _func, ref _args) => {
205 println!("Call(ref func, ref args) = {};", current);
206 println!(" // unimplemented: `ExprCall` is not further destructured at the moment");
208 Expr_::ExprMethodCall(ref _method_name, ref _generics, ref _args) => {
209 println!("MethodCall(ref method_name, ref generics, ref args) = {};", current);
210 println!(" // unimplemented: `ExprMethodCall` is not further destructured at the moment");
212 Expr_::ExprTup(ref elements) => {
213 let elements_pat = self.next("elements");
214 println!("Tup(ref {}) = {};", elements_pat, current);
215 println!(" if {}.len() == {};", elements_pat, elements.len());
216 for (i, element) in elements.iter().enumerate() {
217 self.current = format!("{}[{}]", elements_pat, i);
218 self.visit_expr(element);
221 Expr_::ExprBinary(ref op, ref left, ref right) => {
222 let op_pat = self.next("op");
223 let left_pat = self.next("left");
224 let right_pat = self.next("right");
225 println!("Binary(ref {}, ref {}, ref {}) = {};", op_pat, left_pat, right_pat, current);
226 println!(" if BinOp_::{:?} == {}.node;", op.node, op_pat);
227 self.current = left_pat;
228 self.visit_expr(left);
229 self.current = right_pat;
230 self.visit_expr(right);
232 Expr_::ExprUnary(ref op, ref inner) => {
233 let inner_pat = self.next("inner");
234 println!("Unary(UnOp::{:?}, ref {}) = {};", op, inner_pat, current);
235 self.current = inner_pat;
236 self.visit_expr(inner);
238 Expr_::ExprLit(ref lit) => {
239 let lit_pat = self.next("lit");
240 println!("Lit(ref {}) = {};", lit_pat, current);
242 LitKind::Bool(val) => println!(" if let LitKind::Bool({:?}) = {}.node;", val, lit_pat),
243 LitKind::Char(c) => println!(" if let LitKind::Char({:?}) = {}.node;", c, lit_pat),
244 LitKind::Byte(b) => println!(" if let LitKind::Byte({}) = {}.node;", b, lit_pat),
245 // FIXME: also check int type
246 LitKind::Int(i, _) => println!(" if let LitKind::Int({}, _) = {}.node;", i, lit_pat),
247 LitKind::Float(..) => println!(" if let LitKind::Float(..) = {}.node;", lit_pat),
248 LitKind::FloatUnsuffixed(_) => {
249 println!(" if let LitKind::FloatUnsuffixed(_) = {}.node;", lit_pat)
251 LitKind::ByteStr(ref vec) => {
252 let vec_pat = self.next("vec");
253 println!(" if let LitKind::ByteStr(ref {}) = {}.node;", vec_pat, lit_pat);
254 println!(" if let [{:?}] = **{};", vec, vec_pat);
256 LitKind::Str(ref text, _) => {
257 let str_pat = self.next("s");
258 println!(" if let LitKind::Str(ref {}) = {}.node;", str_pat, lit_pat);
259 println!(" if {}.as_str() == {:?}", str_pat, &*text.as_str())
263 Expr_::ExprCast(ref expr, ref _ty) => {
264 let cast_pat = self.next("expr");
265 println!("Cast(ref {}, _) = {};", cast_pat, current);
266 self.current = cast_pat;
267 self.visit_expr(expr);
269 Expr_::ExprType(ref expr, ref _ty) => {
270 let cast_pat = self.next("expr");
271 println!("Type(ref {}, _) = {};", cast_pat, current);
272 self.current = cast_pat;
273 self.visit_expr(expr);
275 Expr_::ExprIf(ref cond, ref then, ref opt_else) => {
276 let cond_pat = self.next("cond");
277 let then_pat = self.next("then");
278 if let Some(ref else_) = *opt_else {
279 let else_pat = self.next("else_");
280 println!("If(ref {}, ref {}, Some(ref {})) = {};", cond_pat, then_pat, else_pat, current);
281 self.current = else_pat;
282 self.visit_expr(else_);
284 println!("If(ref {}, ref {}, None) = {};", cond_pat, then_pat, current);
286 self.current = cond_pat;
287 self.visit_expr(cond);
288 self.current = then_pat;
289 self.visit_expr(then);
291 Expr_::ExprWhile(ref cond, ref body, _) => {
292 let cond_pat = self.next("cond");
293 let body_pat = self.next("body");
294 let label_pat = self.next("label");
295 println!("While(ref {}, ref {}, ref {}) = {};", cond_pat, body_pat, label_pat, current);
296 self.current = cond_pat;
297 self.visit_expr(cond);
298 self.current = body_pat;
299 self.visit_block(body);
301 Expr_::ExprLoop(ref body, _, desugaring) => {
302 let body_pat = self.next("body");
303 let des = loop_desugaring_name(desugaring);
304 let label_pat = self.next("label");
305 println!("Loop(ref {}, ref {}, {}) = {};", body_pat, label_pat, des, current);
306 self.current = body_pat;
307 self.visit_block(body);
309 Expr_::ExprMatch(ref _expr, ref _arms, desugaring) => {
310 let des = desugaring_name(desugaring);
311 println!("Match(ref expr, ref arms, {}) = {};", des, current);
312 println!(" // unimplemented: `ExprMatch` is not further destructured at the moment");
314 Expr_::ExprClosure(ref _capture_clause, ref _func, _, _, _) => {
315 println!("Closure(ref capture_clause, ref func, _, _, _) = {};", current);
316 println!(" // unimplemented: `ExprClosure` is not further destructured at the moment");
318 Expr_::ExprYield(ref sub) => {
319 let sub_pat = self.next("sub");
320 println!("Yield(ref sub) = {};", current);
321 self.current = sub_pat;
322 self.visit_expr(sub);
324 Expr_::ExprBlock(ref block) => {
325 let block_pat = self.next("block");
326 println!("Block(ref {}) = {};", block_pat, current);
327 self.current = block_pat;
328 self.visit_block(block);
330 Expr_::ExprAssign(ref target, ref value) => {
331 let target_pat = self.next("target");
332 let value_pat = self.next("value");
333 println!("Assign(ref {}, ref {}) = {};", target_pat, value_pat, current);
334 self.current = target_pat;
335 self.visit_expr(target);
336 self.current = value_pat;
337 self.visit_expr(value);
339 Expr_::ExprAssignOp(ref op, ref target, ref value) => {
340 let op_pat = self.next("op");
341 let target_pat = self.next("target");
342 let value_pat = self.next("value");
343 println!("AssignOp(ref {}, ref {}, ref {}) = {};", op_pat, target_pat, value_pat, current);
344 println!(" if BinOp_::{:?} == {}.node;", op.node, op_pat);
345 self.current = target_pat;
346 self.visit_expr(target);
347 self.current = value_pat;
348 self.visit_expr(value);
350 Expr_::ExprField(ref object, ref field_name) => {
351 let obj_pat = self.next("object");
352 let field_name_pat = self.next("field_name");
353 println!("Field(ref {}, ref {}) = {};", obj_pat, field_name_pat, current);
354 println!(" if {}.node.as_str() == {:?}", field_name_pat, field_name.node.as_str());
355 self.current = obj_pat;
356 self.visit_expr(object);
358 Expr_::ExprTupField(ref object, ref field_id) => {
359 let obj_pat = self.next("object");
360 let field_id_pat = self.next("field_id");
361 println!("TupField(ref {}, ref {}) = {};", obj_pat, field_id_pat, current);
362 println!(" if {}.node == {}", field_id_pat, field_id.node);
363 self.current = obj_pat;
364 self.visit_expr(object);
366 Expr_::ExprIndex(ref object, ref index) => {
367 let object_pat = self.next("object");
368 let index_pat = self.next("index");
369 println!("Index(ref {}, ref {}) = {};", object_pat, index_pat, current);
370 self.current = object_pat;
371 self.visit_expr(object);
372 self.current = index_pat;
373 self.visit_expr(index);
375 Expr_::ExprPath(ref path) => {
376 let path_pat = self.next("path");
377 println!("Path(ref {}) = {};", path_pat, current);
378 self.current = path_pat;
379 self.visit_qpath(path, expr.id, expr.span);
381 Expr_::ExprAddrOf(mutability, ref inner) => {
382 let inner_pat = self.next("inner");
383 println!("AddrOf({:?}, ref {}) = {};", mutability, inner_pat, current);
384 self.current = inner_pat;
385 self.visit_expr(inner);
387 Expr_::ExprBreak(ref _destination, ref opt_value) => {
388 let destination_pat = self.next("destination");
389 if let Some(ref value) = *opt_value {
390 let value_pat = self.next("value");
391 println!("Break(ref {}, Some(ref {})) = {};", destination_pat, value_pat, current);
392 self.current = value_pat;
393 self.visit_expr(value);
395 println!("Break(ref {}, None) = {};", destination_pat, current);
397 // FIXME: implement label printing
399 Expr_::ExprAgain(ref _destination) => {
400 let destination_pat = self.next("destination");
401 println!("Again(ref {}) = {};", destination_pat, current);
402 // FIXME: implement label printing
404 Expr_::ExprRet(ref opt_value) => if let Some(ref value) = *opt_value {
405 let value_pat = self.next("value");
406 println!("Ret(Some(ref {})) = {};", value_pat, current);
407 self.current = value_pat;
408 self.visit_expr(value);
410 println!("Ret(None) = {};", current);
412 Expr_::ExprInlineAsm(_, ref _input, ref _output) => {
413 println!("InlineAsm(_, ref input, ref output) = {};", current);
414 println!(" // unimplemented: `ExprInlineAsm` is not further destructured at the moment");
416 Expr_::ExprStruct(ref path, ref fields, ref opt_base) => {
417 let path_pat = self.next("path");
418 let fields_pat = self.next("fields");
419 if let Some(ref base) = *opt_base {
420 let base_pat = self.next("base");
422 "Struct(ref {}, ref {}, Some(ref {})) = {};",
428 self.current = base_pat;
429 self.visit_expr(base);
431 println!("Struct(ref {}, ref {}, None) = {};", path_pat, fields_pat, current);
433 self.current = path_pat;
434 self.visit_qpath(path, expr.id, expr.span);
435 println!(" if {}.len() == {};", fields_pat, fields.len());
436 println!(" // unimplemented: field checks");
438 // FIXME: compute length (needs type info)
439 Expr_::ExprRepeat(ref value, _) => {
440 let value_pat = self.next("value");
441 println!("Repeat(ref {}, _) = {};", value_pat, current);
442 println!("// unimplemented: repeat count check");
443 self.current = value_pat;
444 self.visit_expr(value);
449 fn visit_qpath(&mut self, path: &QPath, _: NodeId, _: Span) {
450 print!(" if match_qpath({}, &[", self.current);
451 print_path(path, &mut true);
454 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
455 NestedVisitorMap::None
459 fn has_attr(attrs: &[Attribute]) -> bool {
460 attrs.iter().any(|attr| {
461 attr.check_name("clippy") && attr.meta_item_list().map_or(false, |list| {
462 list.len() == 1 && match list[0].node {
463 ast::NestedMetaItemKind::MetaItem(ref it) => it.name == "author",
464 ast::NestedMetaItemKind::Literal(_) => false,
470 fn desugaring_name(des: hir::MatchSource) -> String {
472 hir::MatchSource::ForLoopDesugar => "MatchSource::ForLoopDesugar".to_string(),
473 hir::MatchSource::TryDesugar => "MatchSource::TryDesugar".to_string(),
474 hir::MatchSource::WhileLetDesugar => "MatchSource::WhileLetDesugar".to_string(),
475 hir::MatchSource::Normal => "MatchSource::Normal".to_string(),
476 hir::MatchSource::IfLetDesugar { contains_else_clause } => format!("MatchSource::IfLetDesugar {{ contains_else_clause: {} }}", contains_else_clause),
480 fn loop_desugaring_name(des: hir::LoopSource) -> &'static str {
482 hir::LoopSource::ForLoop => "LoopSource::ForLoop",
483 hir::LoopSource::Loop => "LoopSource::Loop",
484 hir::LoopSource::WhileLet => "LoopSource::WhileLet",
488 fn print_path(path: &QPath, first: &mut bool) {
490 QPath::Resolved(_, ref path) => for segment in &path.segments {
496 print!("{:?}", segment.name.as_str());
498 QPath::TypeRelative(ref ty, ref segment) => match ty.node {
499 hir::Ty_::TyPath(ref inner_path) => {
500 print_path(inner_path, first);
506 print!("{:?}", segment.name.as_str());
508 ref other => print!("/* unimplemented: {:?}*/", other),