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
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 println!("Match(ref expr, ref arms, {}) = {};", des, current);
328 println!(" // unimplemented: `ExprMatch` is not further destructured at the moment");
330 Expr_::ExprClosure(ref _capture_clause, ref _func, _, _, _) => {
331 println!("Closure(ref capture_clause, ref func, _, _, _) = {};", current);
332 println!(" // unimplemented: `ExprClosure` is not further destructured at the moment");
334 Expr_::ExprYield(ref sub) => {
335 let sub_pat = self.next("sub");
336 println!("Yield(ref sub) = {};", current);
337 self.current = sub_pat;
338 self.visit_expr(sub);
340 Expr_::ExprBlock(ref block) => {
341 let block_pat = self.next("block");
342 println!("Block(ref {}) = {};", block_pat, current);
343 self.current = block_pat;
344 self.visit_block(block);
346 Expr_::ExprAssign(ref target, ref value) => {
347 let target_pat = self.next("target");
348 let value_pat = self.next("value");
349 println!("Assign(ref {}, ref {}) = {};", target_pat, value_pat, current);
350 self.current = target_pat;
351 self.visit_expr(target);
352 self.current = value_pat;
353 self.visit_expr(value);
355 Expr_::ExprAssignOp(ref op, ref target, ref value) => {
356 let op_pat = self.next("op");
357 let target_pat = self.next("target");
358 let value_pat = self.next("value");
359 println!("AssignOp(ref {}, ref {}, ref {}) = {};", op_pat, target_pat, value_pat, current);
360 println!(" if BinOp_::{:?} == {}.node;", op.node, op_pat);
361 self.current = target_pat;
362 self.visit_expr(target);
363 self.current = value_pat;
364 self.visit_expr(value);
366 Expr_::ExprField(ref object, ref field_name) => {
367 let obj_pat = self.next("object");
368 let field_name_pat = self.next("field_name");
369 println!("Field(ref {}, ref {}) = {};", obj_pat, field_name_pat, current);
370 println!(" if {}.node.as_str() == {:?}", field_name_pat, field_name.node.as_str());
371 self.current = obj_pat;
372 self.visit_expr(object);
374 Expr_::ExprTupField(ref object, ref field_id) => {
375 let obj_pat = self.next("object");
376 let field_id_pat = self.next("field_id");
377 println!("TupField(ref {}, ref {}) = {};", obj_pat, field_id_pat, current);
378 println!(" if {}.node == {}", field_id_pat, field_id.node);
379 self.current = obj_pat;
380 self.visit_expr(object);
382 Expr_::ExprIndex(ref object, ref index) => {
383 let object_pat = self.next("object");
384 let index_pat = self.next("index");
385 println!("Index(ref {}, ref {}) = {};", object_pat, index_pat, current);
386 self.current = object_pat;
387 self.visit_expr(object);
388 self.current = index_pat;
389 self.visit_expr(index);
391 Expr_::ExprPath(ref path) => {
392 let path_pat = self.next("path");
393 println!("Path(ref {}) = {};", path_pat, current);
394 self.current = path_pat;
395 self.print_qpath(path);
397 Expr_::ExprAddrOf(mutability, ref inner) => {
398 let inner_pat = self.next("inner");
399 println!("AddrOf({:?}, ref {}) = {};", mutability, inner_pat, current);
400 self.current = inner_pat;
401 self.visit_expr(inner);
403 Expr_::ExprBreak(ref _destination, ref opt_value) => {
404 let destination_pat = self.next("destination");
405 if let Some(ref value) = *opt_value {
406 let value_pat = self.next("value");
407 println!("Break(ref {}, Some(ref {})) = {};", destination_pat, value_pat, current);
408 self.current = value_pat;
409 self.visit_expr(value);
411 println!("Break(ref {}, None) = {};", destination_pat, current);
413 // FIXME: implement label printing
415 Expr_::ExprAgain(ref _destination) => {
416 let destination_pat = self.next("destination");
417 println!("Again(ref {}) = {};", destination_pat, current);
418 // FIXME: implement label printing
420 Expr_::ExprRet(ref opt_value) => if let Some(ref value) = *opt_value {
421 let value_pat = self.next("value");
422 println!("Ret(Some(ref {})) = {};", value_pat, current);
423 self.current = value_pat;
424 self.visit_expr(value);
426 println!("Ret(None) = {};", current);
428 Expr_::ExprInlineAsm(_, ref _input, ref _output) => {
429 println!("InlineAsm(_, ref input, ref output) = {};", current);
430 println!(" // unimplemented: `ExprInlineAsm` is not further destructured at the moment");
432 Expr_::ExprStruct(ref path, ref fields, ref opt_base) => {
433 let path_pat = self.next("path");
434 let fields_pat = self.next("fields");
435 if let Some(ref base) = *opt_base {
436 let base_pat = self.next("base");
438 "Struct(ref {}, ref {}, Some(ref {})) = {};",
444 self.current = base_pat;
445 self.visit_expr(base);
447 println!("Struct(ref {}, ref {}, None) = {};", path_pat, fields_pat, current);
449 self.current = path_pat;
450 self.print_qpath(path);
451 println!(" if {}.len() == {};", fields_pat, fields.len());
452 println!(" // unimplemented: field checks");
454 // FIXME: compute length (needs type info)
455 Expr_::ExprRepeat(ref value, _) => {
456 let value_pat = self.next("value");
457 println!("Repeat(ref {}, _) = {};", value_pat, current);
458 println!("// unimplemented: repeat count check");
459 self.current = value_pat;
460 self.visit_expr(value);
465 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
466 NestedVisitorMap::None
470 fn has_attr(attrs: &[Attribute]) -> bool {
471 attrs.iter().any(|attr| {
472 attr.check_name("clippy") && attr.meta_item_list().map_or(false, |list| {
473 list.len() == 1 && match list[0].node {
474 ast::NestedMetaItemKind::MetaItem(ref it) => it.name == "author",
475 ast::NestedMetaItemKind::Literal(_) => false,
481 fn desugaring_name(des: hir::MatchSource) -> String {
483 hir::MatchSource::ForLoopDesugar => "MatchSource::ForLoopDesugar".to_string(),
484 hir::MatchSource::TryDesugar => "MatchSource::TryDesugar".to_string(),
485 hir::MatchSource::WhileLetDesugar => "MatchSource::WhileLetDesugar".to_string(),
486 hir::MatchSource::Normal => "MatchSource::Normal".to_string(),
487 hir::MatchSource::IfLetDesugar { contains_else_clause } => format!("MatchSource::IfLetDesugar {{ contains_else_clause: {} }}", contains_else_clause),
491 fn loop_desugaring_name(des: hir::LoopSource) -> &'static str {
493 hir::LoopSource::ForLoop => "LoopSource::ForLoop",
494 hir::LoopSource::Loop => "LoopSource::Loop",
495 hir::LoopSource::WhileLet => "LoopSource::WhileLet",
499 fn print_path(path: &QPath, first: &mut bool) {
501 QPath::Resolved(_, ref path) => for segment in &path.segments {
507 print!("{:?}", segment.name.as_str());
509 QPath::TypeRelative(ref ty, ref segment) => match ty.node {
510 hir::Ty_::TyPath(ref inner_path) => {
511 print_path(inner_path, first);
517 print!("{:?}", segment.name.as_str());
519 ref other => print!("/* unimplemented: {:?}*/", other),