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};
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
18 /// // detect the following pattern
21 /// // but ignore everything from here on
22 /// #![clippy(author = "ignore")]
31 /// if let Expr_::ExprIf(ref cond, ref then, None) = item.node,
32 /// if let Expr_::ExprBinary(BinOp::Eq, ref left, ref right) = cond.node,
33 /// if let Expr_::ExprPath(ref path) = left.node,
34 /// if let Expr_::ExprLit(ref lit) = right.node,
35 /// if let LitKind::Int(42, _) = lit.node,
37 /// // report your lint here
41 declare_clippy_lint! {
44 "helper for writing lints"
49 impl LintPass for Pass {
50 fn get_lints(&self) -> LintArray {
51 lint_array!(LINT_AUTHOR)
56 println!("if_chain! {{");
61 println!(" // report your lint here");
66 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
67 fn check_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
68 if !has_attr(&item.attrs) {
72 PrintVisitor::new("item").visit_item(item);
76 fn check_impl_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem) {
77 if !has_attr(&item.attrs) {
81 PrintVisitor::new("item").visit_impl_item(item);
85 fn check_trait_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
86 if !has_attr(&item.attrs) {
90 PrintVisitor::new("item").visit_trait_item(item);
94 fn check_variant(&mut self, _cx: &LateContext<'a, 'tcx>, var: &'tcx hir::Variant, generics: &hir::Generics) {
95 if !has_attr(&var.node.attrs) {
99 PrintVisitor::new("var").visit_variant(var, generics, DUMMY_NODE_ID);
103 fn check_struct_field(&mut self, _cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField) {
104 if !has_attr(&field.attrs) {
108 PrintVisitor::new("field").visit_struct_field(field);
112 fn check_expr(&mut self, _cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
113 if !has_attr(&expr.attrs) {
117 PrintVisitor::new("expr").visit_expr(expr);
121 fn check_arm(&mut self, _cx: &LateContext<'a, 'tcx>, arm: &'tcx hir::Arm) {
122 if !has_attr(&arm.attrs) {
126 PrintVisitor::new("arm").visit_arm(arm);
130 fn check_stmt(&mut self, _cx: &LateContext<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
131 if !has_attr(stmt.node.attrs()) {
135 PrintVisitor::new("stmt").visit_stmt(stmt);
139 fn check_foreign_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ForeignItem) {
140 if !has_attr(&item.attrs) {
144 PrintVisitor::new("item").visit_foreign_item(item);
150 fn new(s: &'static str) -> Self {
153 current: s.to_owned(),
157 fn next(&mut self, s: &'static str) -> String {
158 use std::collections::hash_map::Entry::*;
159 match self.ids.entry(s) {
160 // already there: start numbering from `1`
161 Occupied(mut occ) => {
162 let val = occ.get_mut();
164 format!("{}{}", s, *val)
166 // not there: insert and return name as given
174 fn print_qpath(&mut self, path: &QPath) {
175 print!(" if match_qpath({}, &[", self.current);
176 print_path(path, &mut true);
181 struct PrintVisitor {
182 /// Fields are the current index that needs to be appended to pattern
184 ids: HashMap<&'static str, usize>,
185 /// the name that needs to be destructured
189 impl<'tcx> Visitor<'tcx> for PrintVisitor {
190 fn visit_expr(&mut self, expr: &Expr) {
191 print!(" if let Expr_::Expr");
192 let current = format!("{}.node", self.current);
194 Expr_::ExprBox(ref inner) => {
195 let inner_pat = self.next("inner");
196 println!("Box(ref {}) = {};", inner_pat, current);
197 self.current = inner_pat;
198 self.visit_expr(inner);
200 Expr_::ExprArray(ref elements) => {
201 let elements_pat = self.next("elements");
202 println!("Array(ref {}) = {};", elements_pat, current);
203 println!(" if {}.len() == {};", elements_pat, elements.len());
204 for (i, element) in elements.iter().enumerate() {
205 self.current = format!("{}[{}]", elements_pat, i);
206 self.visit_expr(element);
209 Expr_::ExprCall(ref _func, ref _args) => {
210 println!("Call(ref func, ref args) = {};", current);
211 println!(" // unimplemented: `ExprCall` is not further destructured at the moment");
213 Expr_::ExprMethodCall(ref _method_name, ref _generics, ref _args) => {
214 println!("MethodCall(ref method_name, ref generics, ref args) = {};", current);
215 println!(" // unimplemented: `ExprMethodCall` is not further destructured at the moment");
217 Expr_::ExprTup(ref elements) => {
218 let elements_pat = self.next("elements");
219 println!("Tup(ref {}) = {};", elements_pat, current);
220 println!(" if {}.len() == {};", elements_pat, elements.len());
221 for (i, element) in elements.iter().enumerate() {
222 self.current = format!("{}[{}]", elements_pat, i);
223 self.visit_expr(element);
226 Expr_::ExprBinary(ref op, ref left, ref right) => {
227 let op_pat = self.next("op");
228 let left_pat = self.next("left");
229 let right_pat = self.next("right");
230 println!("Binary(ref {}, ref {}, ref {}) = {};", op_pat, left_pat, right_pat, current);
231 println!(" if BinOp_::{:?} == {}.node;", op.node, op_pat);
232 self.current = left_pat;
233 self.visit_expr(left);
234 self.current = right_pat;
235 self.visit_expr(right);
237 Expr_::ExprUnary(ref op, ref inner) => {
238 let inner_pat = self.next("inner");
239 println!("Unary(UnOp::{:?}, ref {}) = {};", op, inner_pat, current);
240 self.current = inner_pat;
241 self.visit_expr(inner);
243 Expr_::ExprLit(ref lit) => {
244 let lit_pat = self.next("lit");
245 println!("Lit(ref {}) = {};", lit_pat, current);
247 LitKind::Bool(val) => println!(" if let LitKind::Bool({:?}) = {}.node;", val, lit_pat),
248 LitKind::Char(c) => println!(" if let LitKind::Char({:?}) = {}.node;", c, lit_pat),
249 LitKind::Byte(b) => println!(" if let LitKind::Byte({}) = {}.node;", b, lit_pat),
250 // FIXME: also check int type
251 LitKind::Int(i, _) => println!(" if let LitKind::Int({}, _) = {}.node;", i, lit_pat),
252 LitKind::Float(..) => println!(" if let LitKind::Float(..) = {}.node;", lit_pat),
253 LitKind::FloatUnsuffixed(_) => {
254 println!(" if let LitKind::FloatUnsuffixed(_) = {}.node;", lit_pat)
256 LitKind::ByteStr(ref vec) => {
257 let vec_pat = self.next("vec");
258 println!(" if let LitKind::ByteStr(ref {}) = {}.node;", vec_pat, lit_pat);
259 println!(" if let [{:?}] = **{};", vec, vec_pat);
261 LitKind::Str(ref text, _) => {
262 let str_pat = self.next("s");
263 println!(" if let LitKind::Str(ref {}) = {}.node;", str_pat, lit_pat);
264 println!(" if {}.as_str() == {:?}", str_pat, &*text.as_str())
268 Expr_::ExprCast(ref expr, ref ty) => {
269 let cast_pat = self.next("expr");
270 let cast_ty = self.next("cast_ty");
271 let qp_label = self.next("qp");
273 println!("Cast(ref {}, ref {}) = {};", cast_pat, cast_ty, current);
274 if let Ty_::TyPath(ref qp) = ty.node {
275 println!(" if let Ty_::TyPath(ref {}) = {}.node;", qp_label, cast_ty);
276 self.current = qp_label;
277 self.print_qpath(qp);
279 self.current = cast_pat;
280 self.visit_expr(expr);
282 Expr_::ExprType(ref expr, ref _ty) => {
283 let cast_pat = self.next("expr");
284 println!("Type(ref {}, _) = {};", cast_pat, current);
285 self.current = cast_pat;
286 self.visit_expr(expr);
288 Expr_::ExprIf(ref cond, ref then, ref opt_else) => {
289 let cond_pat = self.next("cond");
290 let then_pat = self.next("then");
291 if let Some(ref else_) = *opt_else {
292 let else_pat = self.next("else_");
293 println!("If(ref {}, ref {}, Some(ref {})) = {};", cond_pat, then_pat, else_pat, current);
294 self.current = else_pat;
295 self.visit_expr(else_);
297 println!("If(ref {}, ref {}, None) = {};", cond_pat, then_pat, current);
299 self.current = cond_pat;
300 self.visit_expr(cond);
301 self.current = then_pat;
302 self.visit_expr(then);
304 Expr_::ExprWhile(ref cond, ref body, _) => {
305 let cond_pat = self.next("cond");
306 let body_pat = self.next("body");
307 let label_pat = self.next("label");
308 println!("While(ref {}, ref {}, ref {}) = {};", cond_pat, body_pat, label_pat, current);
309 self.current = cond_pat;
310 self.visit_expr(cond);
311 self.current = body_pat;
312 self.visit_block(body);
314 Expr_::ExprLoop(ref body, _, desugaring) => {
315 let body_pat = self.next("body");
316 let des = loop_desugaring_name(desugaring);
317 let label_pat = self.next("label");
318 println!("Loop(ref {}, ref {}, {}) = {};", body_pat, label_pat, des, current);
319 self.current = body_pat;
320 self.visit_block(body);
322 Expr_::ExprMatch(ref _expr, ref _arms, desugaring) => {
323 let des = desugaring_name(desugaring);
324 println!("Match(ref expr, ref arms, {}) = {};", des, current);
325 println!(" // unimplemented: `ExprMatch` is not further destructured at the moment");
327 Expr_::ExprClosure(ref _capture_clause, ref _func, _, _, _) => {
328 println!("Closure(ref capture_clause, ref func, _, _, _) = {};", current);
329 println!(" // unimplemented: `ExprClosure` is not further destructured at the moment");
331 Expr_::ExprYield(ref sub) => {
332 let sub_pat = self.next("sub");
333 println!("Yield(ref sub) = {};", current);
334 self.current = sub_pat;
335 self.visit_expr(sub);
337 Expr_::ExprBlock(ref block) => {
338 let block_pat = self.next("block");
339 println!("Block(ref {}) = {};", block_pat, current);
340 self.current = block_pat;
341 self.visit_block(block);
343 Expr_::ExprAssign(ref target, ref value) => {
344 let target_pat = self.next("target");
345 let value_pat = self.next("value");
346 println!("Assign(ref {}, ref {}) = {};", target_pat, value_pat, current);
347 self.current = target_pat;
348 self.visit_expr(target);
349 self.current = value_pat;
350 self.visit_expr(value);
352 Expr_::ExprAssignOp(ref op, ref target, ref value) => {
353 let op_pat = self.next("op");
354 let target_pat = self.next("target");
355 let value_pat = self.next("value");
356 println!("AssignOp(ref {}, ref {}, ref {}) = {};", op_pat, target_pat, value_pat, current);
357 println!(" if BinOp_::{:?} == {}.node;", op.node, op_pat);
358 self.current = target_pat;
359 self.visit_expr(target);
360 self.current = value_pat;
361 self.visit_expr(value);
363 Expr_::ExprField(ref object, ref field_name) => {
364 let obj_pat = self.next("object");
365 let field_name_pat = self.next("field_name");
366 println!("Field(ref {}, ref {}) = {};", obj_pat, field_name_pat, current);
367 println!(" if {}.node.as_str() == {:?}", field_name_pat, field_name.node.as_str());
368 self.current = obj_pat;
369 self.visit_expr(object);
371 Expr_::ExprTupField(ref object, ref field_id) => {
372 let obj_pat = self.next("object");
373 let field_id_pat = self.next("field_id");
374 println!("TupField(ref {}, ref {}) = {};", obj_pat, field_id_pat, current);
375 println!(" if {}.node == {}", field_id_pat, field_id.node);
376 self.current = obj_pat;
377 self.visit_expr(object);
379 Expr_::ExprIndex(ref object, ref index) => {
380 let object_pat = self.next("object");
381 let index_pat = self.next("index");
382 println!("Index(ref {}, ref {}) = {};", object_pat, index_pat, current);
383 self.current = object_pat;
384 self.visit_expr(object);
385 self.current = index_pat;
386 self.visit_expr(index);
388 Expr_::ExprPath(ref path) => {
389 let path_pat = self.next("path");
390 println!("Path(ref {}) = {};", path_pat, current);
391 self.current = path_pat;
392 self.print_qpath(path);
394 Expr_::ExprAddrOf(mutability, ref inner) => {
395 let inner_pat = self.next("inner");
396 println!("AddrOf({:?}, ref {}) = {};", mutability, inner_pat, current);
397 self.current = inner_pat;
398 self.visit_expr(inner);
400 Expr_::ExprBreak(ref _destination, ref opt_value) => {
401 let destination_pat = self.next("destination");
402 if let Some(ref value) = *opt_value {
403 let value_pat = self.next("value");
404 println!("Break(ref {}, Some(ref {})) = {};", destination_pat, value_pat, current);
405 self.current = value_pat;
406 self.visit_expr(value);
408 println!("Break(ref {}, None) = {};", destination_pat, current);
410 // FIXME: implement label printing
412 Expr_::ExprAgain(ref _destination) => {
413 let destination_pat = self.next("destination");
414 println!("Again(ref {}) = {};", destination_pat, current);
415 // FIXME: implement label printing
417 Expr_::ExprRet(ref opt_value) => if let Some(ref value) = *opt_value {
418 let value_pat = self.next("value");
419 println!("Ret(Some(ref {})) = {};", value_pat, current);
420 self.current = value_pat;
421 self.visit_expr(value);
423 println!("Ret(None) = {};", current);
425 Expr_::ExprInlineAsm(_, ref _input, ref _output) => {
426 println!("InlineAsm(_, ref input, ref output) = {};", current);
427 println!(" // unimplemented: `ExprInlineAsm` is not further destructured at the moment");
429 Expr_::ExprStruct(ref path, ref fields, ref opt_base) => {
430 let path_pat = self.next("path");
431 let fields_pat = self.next("fields");
432 if let Some(ref base) = *opt_base {
433 let base_pat = self.next("base");
435 "Struct(ref {}, ref {}, Some(ref {})) = {};",
441 self.current = base_pat;
442 self.visit_expr(base);
444 println!("Struct(ref {}, ref {}, None) = {};", path_pat, fields_pat, current);
446 self.current = path_pat;
447 self.print_qpath(path);
448 println!(" if {}.len() == {};", fields_pat, fields.len());
449 println!(" // unimplemented: field checks");
451 // FIXME: compute length (needs type info)
452 Expr_::ExprRepeat(ref value, _) => {
453 let value_pat = self.next("value");
454 println!("Repeat(ref {}, _) = {};", value_pat, current);
455 println!("// unimplemented: repeat count check");
456 self.current = value_pat;
457 self.visit_expr(value);
462 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
463 NestedVisitorMap::None
467 fn has_attr(attrs: &[Attribute]) -> bool {
468 attrs.iter().any(|attr| {
469 attr.check_name("clippy") && attr.meta_item_list().map_or(false, |list| {
470 list.len() == 1 && match list[0].node {
471 ast::NestedMetaItemKind::MetaItem(ref it) => it.name == "author",
472 ast::NestedMetaItemKind::Literal(_) => false,
478 fn desugaring_name(des: hir::MatchSource) -> String {
480 hir::MatchSource::ForLoopDesugar => "MatchSource::ForLoopDesugar".to_string(),
481 hir::MatchSource::TryDesugar => "MatchSource::TryDesugar".to_string(),
482 hir::MatchSource::WhileLetDesugar => "MatchSource::WhileLetDesugar".to_string(),
483 hir::MatchSource::Normal => "MatchSource::Normal".to_string(),
484 hir::MatchSource::IfLetDesugar { contains_else_clause } => format!("MatchSource::IfLetDesugar {{ contains_else_clause: {} }}", contains_else_clause),
488 fn loop_desugaring_name(des: hir::LoopSource) -> &'static str {
490 hir::LoopSource::ForLoop => "LoopSource::ForLoop",
491 hir::LoopSource::Loop => "LoopSource::Loop",
492 hir::LoopSource::WhileLet => "LoopSource::WhileLet",
496 fn print_path(path: &QPath, first: &mut bool) {
498 QPath::Resolved(_, ref path) => for segment in &path.segments {
504 print!("{:?}", segment.name.as_str());
506 QPath::TypeRelative(ref ty, ref segment) => match ty.node {
507 hir::Ty_::TyPath(ref inner_path) => {
508 print_path(inner_path, first);
514 print!("{:?}", segment.name.as_str());
516 ref other => print!("/* unimplemented: {:?}*/", other),