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, QPath, Expr_};
9 use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
10 use syntax::ast::{self, Attribute, NodeId, LitKind, 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 /// let Expr_::ExprIf(ref cond, ref then, None) = item.node,
33 /// let Expr_::ExprBinary(BinOp::Eq, ref left, ref right) = cond.node,
34 /// let Expr_::ExprPath(ref path) = left.node,
35 /// let Expr_::ExprLit(ref lit) = right.node,
36 /// let LitKind::Int(42, _) = lit.node,
38 /// // report your lint here
44 "helper for writing lints"
49 impl LintPass for Pass {
50 fn get_lints(&self) -> LintArray {
51 lint_array!(LINT_AUTHOR)
56 println!("if_let_chain!{{[");
61 println!(" // report your lint here");
65 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
66 fn check_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
67 if !has_attr(&item.attrs) {
71 PrintVisitor::new("item").visit_item(item);
75 fn check_impl_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem) {
76 if !has_attr(&item.attrs) {
80 PrintVisitor::new("item").visit_impl_item(item);
84 fn check_trait_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
85 if !has_attr(&item.attrs) {
89 PrintVisitor::new("item").visit_trait_item(item);
93 fn check_variant(&mut self, _cx: &LateContext<'a, 'tcx>, var: &'tcx hir::Variant, generics: &hir::Generics) {
94 if !has_attr(&var.node.attrs) {
98 PrintVisitor::new("var").visit_variant(var, generics, DUMMY_NODE_ID);
102 fn check_struct_field(&mut self, _cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField) {
103 if !has_attr(&field.attrs) {
107 PrintVisitor::new("field").visit_struct_field(field);
111 fn check_expr(&mut self, _cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
112 if !has_attr(&expr.attrs) {
116 PrintVisitor::new("expr").visit_expr(expr);
120 fn check_arm(&mut self, _cx: &LateContext<'a, 'tcx>, arm: &'tcx hir::Arm) {
121 if !has_attr(&arm.attrs) {
125 PrintVisitor::new("arm").visit_arm(arm);
129 fn check_stmt(&mut self, _cx: &LateContext<'a, 'tcx>, stmt: &'tcx hir::Stmt) {
130 if !has_attr(stmt.node.attrs()) {
134 PrintVisitor::new("stmt").visit_stmt(stmt);
138 fn check_foreign_item(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ForeignItem) {
139 if !has_attr(&item.attrs) {
143 PrintVisitor::new("item").visit_foreign_item(item);
149 fn new(s: &'static str) -> Self {
152 current: s.to_owned(),
156 fn next(&mut self, s: &'static str) -> String {
157 use std::collections::hash_map::Entry::*;
158 match self.ids.entry(s) {
159 // already there: start numbering from `1`
160 Occupied(mut occ) => {
161 let val = occ.get_mut();
163 format!("{}{}", s, *val)
165 // not there: insert and return name as given
174 struct PrintVisitor {
175 /// Fields are the current index that needs to be appended to pattern
177 ids: HashMap<&'static str, usize>,
178 /// the name that needs to be destructured
182 impl<'tcx> Visitor<'tcx> for PrintVisitor {
183 fn visit_expr(&mut self, expr: &Expr) {
184 print!(" let Expr_::Expr");
185 let current = format!("{}.node", self.current);
187 Expr_::ExprBox(ref inner) => {
188 let inner_pat = self.next("inner");
189 println!("Box(ref {}) = {},", inner_pat, current);
190 self.current = inner_pat;
191 self.visit_expr(inner);
193 Expr_::ExprArray(ref elements) => {
194 let elements_pat = self.next("elements");
195 println!("Array(ref {}) = {},", elements_pat, current);
196 println!(" {}.len() == {},", elements_pat, elements.len());
197 for (i, element) in elements.iter().enumerate() {
198 self.current = format!("{}[{}]", elements_pat, i);
199 self.visit_expr(element);
202 Expr_::ExprCall(ref _func, ref _args) => {
203 println!("Call(ref func, ref args) = {},", current);
204 println!(" // unimplemented: `ExprCall` is not further destructured at the moment");
206 Expr_::ExprMethodCall(ref _method_name, ref _generics, ref _args) => {
207 println!("MethodCall(ref method_name, ref generics, ref args) = {},", current);
208 println!(" // unimplemented: `ExprMethodCall` is not further destructured at the moment");
210 Expr_::ExprTup(ref elements) => {
211 let elements_pat = self.next("elements");
212 println!("Tup(ref {}) = {},", elements_pat, current);
213 println!(" {}.len() == {},", elements_pat, elements.len());
214 for (i, element) in elements.iter().enumerate() {
215 self.current = format!("{}[{}]", elements_pat, i);
216 self.visit_expr(element);
219 Expr_::ExprBinary(ref op, ref left, ref right) => {
220 let op_pat = self.next("op");
221 let left_pat = self.next("left");
222 let right_pat = self.next("right");
223 println!("Binary(ref {}, ref {}, ref {}) = {},", op_pat, left_pat, right_pat, current);
224 println!(" BinOp_::{:?} == {}.node,", op.node, op_pat);
225 self.current = left_pat;
226 self.visit_expr(left);
227 self.current = right_pat;
228 self.visit_expr(right);
230 Expr_::ExprUnary(ref op, ref inner) => {
231 let inner_pat = self.next("inner");
232 println!("Unary(UnOp::{:?}, ref {}) = {},", op, inner_pat, current);
233 self.current = inner_pat;
234 self.visit_expr(inner);
236 Expr_::ExprLit(ref lit) => {
237 let lit_pat = self.next("lit");
238 println!("Lit(ref {}) = {},", lit_pat, current);
240 LitKind::Bool(val) => println!(" let LitKind::Bool({:?}) = {}.node,", val, lit_pat),
241 LitKind::Char(c) => println!(" let LitKind::Char({:?}) = {}.node,", c, lit_pat),
242 LitKind::Byte(b) => println!(" let LitKind::Byte({}) = {}.node,", b, lit_pat),
243 // FIXME: also check int type
244 LitKind::Int(i, _) => println!(" let LitKind::Int({}, _) = {}.node,", i, lit_pat),
245 LitKind::Float(..) => println!(" let LitKind::Float(..) = {}.node,", lit_pat),
246 LitKind::FloatUnsuffixed(_) => println!(" let LitKind::FloatUnsuffixed(_) = {}.node,", lit_pat),
247 LitKind::ByteStr(ref vec) => {
248 let vec_pat = self.next("vec");
249 println!(" let LitKind::ByteStr(ref {}) = {}.node,", vec_pat, lit_pat);
250 println!(" let [{:?}] = **{},", vec, vec_pat);
252 LitKind::Str(ref text, _) => {
253 let str_pat = self.next("s");
254 println!(" let LitKind::Str(ref {}) = {}.node,", str_pat, lit_pat);
255 println!(" {}.as_str() == {:?}", str_pat, &*text.as_str())
259 Expr_::ExprCast(ref expr, ref _ty) => {
260 let cast_pat = self.next("expr");
261 println!("Cast(ref {}, _) = {},", cast_pat, current);
262 self.current = cast_pat;
263 self.visit_expr(expr);
265 Expr_::ExprType(ref expr, ref _ty) => {
266 let cast_pat = self.next("expr");
267 println!("Type(ref {}, _) = {},", cast_pat, current);
268 self.current = cast_pat;
269 self.visit_expr(expr);
271 Expr_::ExprIf(ref cond, ref then, ref opt_else) => {
272 let cond_pat = self.next("cond");
273 let then_pat = self.next("then");
274 if let Some(ref else_) = *opt_else {
275 let else_pat = self.next("else_");
276 println!("If(ref {}, ref {}, Some(ref {})) = {},", cond_pat, then_pat, else_pat, current);
277 self.current = else_pat;
278 self.visit_expr(else_);
280 println!("If(ref {}, ref {}, None) = {},", cond_pat, then_pat, current);
282 self.current = cond_pat;
283 self.visit_expr(cond);
284 self.current = then_pat;
285 self.visit_expr(then);
287 Expr_::ExprWhile(ref _cond, ref _body, ref _opt_label) => {
288 println!("While(ref cond, ref body, ref opt_label) = {},", current);
289 println!(" // unimplemented: `ExprWhile` is not further destructured at the moment");
291 Expr_::ExprLoop(ref _body, ref _opt_label, ref _desuraging) => {
292 println!("Loop(ref body, ref opt_label, ref desugaring) = {},", current);
293 println!(" // unimplemented: `ExprLoop` is not further destructured at the moment");
295 Expr_::ExprMatch(ref _expr, ref _arms, ref _desugaring) => {
296 println!("Match(ref expr, ref arms, ref desugaring) = {},", current);
297 println!(" // unimplemented: `ExprMatch` is not further destructured at the moment");
299 Expr_::ExprClosure(ref _capture_clause, ref _func, _, _) => {
300 println!("Closure(ref capture_clause, ref func, _, _) = {},", current);
301 println!(" // unimplemented: `ExprClosure` is not further destructured at the moment");
303 Expr_::ExprBlock(ref block) => {
304 let block_pat = self.next("block");
305 println!("Block(ref {}) = {},", block_pat, current);
306 self.current = block_pat;
307 self.visit_block(block);
309 Expr_::ExprAssign(ref target, ref value) => {
310 let target_pat = self.next("target");
311 let value_pat = self.next("value");
312 println!("Assign(ref {}, ref {}) = {},", target_pat, value_pat, current);
313 self.current = target_pat;
314 self.visit_expr(target);
315 self.current = value_pat;
316 self.visit_expr(value);
318 Expr_::ExprAssignOp(ref op, ref target, ref value) => {
319 let op_pat = self.next("op");
320 let target_pat = self.next("target");
321 let value_pat = self.next("value");
322 println!("AssignOp(ref {}, ref {}, ref {}) = {},", op_pat, target_pat, value_pat, current);
323 println!(" BinOp_::{:?} == {}.node,", op.node, op_pat);
324 self.current = target_pat;
325 self.visit_expr(target);
326 self.current = value_pat;
327 self.visit_expr(value);
329 Expr_::ExprField(ref object, ref field_name) => {
330 let obj_pat = self.next("object");
331 let field_name_pat = self.next("field_name");
332 println!("Field(ref {}, ref {}) = {},", obj_pat, field_name_pat, current);
333 println!(" {}.node.as_str() == {:?}", field_name_pat, field_name.node.as_str());
334 self.current = obj_pat;
335 self.visit_expr(object);
337 Expr_::ExprTupField(ref object, ref field_id) => {
338 let obj_pat = self.next("object");
339 let field_id_pat = self.next("field_id");
340 println!("TupField(ref {}, ref {}) = {},", obj_pat, field_id_pat, current);
341 println!(" {}.node == {}", field_id_pat, field_id.node);
342 self.current = obj_pat;
343 self.visit_expr(object);
345 Expr_::ExprIndex(ref object, ref index) => {
346 let object_pat = self.next("object");
347 let index_pat = self.next("index");
348 println!("Index(ref {}, ref {}) = {},", object_pat, index_pat, current);
349 self.current = object_pat;
350 self.visit_expr(object);
351 self.current = index_pat;
352 self.visit_expr(index);
354 Expr_::ExprPath(ref path) => {
355 let path_pat = self.next("path");
356 println!("Path(ref {}) = {},", path_pat, current);
357 self.current = path_pat;
358 self.visit_qpath(path, expr.id, expr.span);
360 Expr_::ExprAddrOf(mutability, ref inner) => {
361 let inner_pat = self.next("inner");
362 println!("AddrOf({:?}, ref {}) = {},", mutability, inner_pat, current);
363 self.current = inner_pat;
364 self.visit_expr(inner);
366 Expr_::ExprBreak(ref _destination, ref opt_value) => {
367 let destination_pat = self.next("destination");
368 if let Some(ref value) = *opt_value {
369 let value_pat = self.next("value");
370 println!("Break(ref {}, Some(ref {})) = {},", destination_pat, value_pat, current);
371 self.current = value_pat;
372 self.visit_expr(value);
374 println!("Break(ref {}, None) = {},", destination_pat, current);
376 // FIXME: implement label printing
378 Expr_::ExprAgain(ref _destination) => {
379 let destination_pat = self.next("destination");
380 println!("Again(ref {}) = {},", destination_pat, current);
381 // FIXME: implement label printing
383 Expr_::ExprRet(ref opt_value) => {
384 if let Some(ref value) = *opt_value {
385 let value_pat = self.next("value");
386 println!("Ret(Some(ref {})) = {},", value_pat, current);
387 self.current = value_pat;
388 self.visit_expr(value);
390 println!("Ret(None) = {},", current);
393 Expr_::ExprInlineAsm(_, ref _input, ref _output) => {
394 println!("InlineAsm(_, ref input, ref output) = {},", current);
395 println!(" // unimplemented: `ExprInlineAsm` is not further destructured at the moment");
397 Expr_::ExprStruct(ref path, ref fields, ref opt_base) => {
398 let path_pat = self.next("path");
399 let fields_pat = self.next("fields");
400 if let Some(ref base) = *opt_base {
401 let base_pat = self.next("base");
403 "Struct(ref {}, ref {}, Some(ref {})) = {},",
409 self.current = base_pat;
410 self.visit_expr(base);
412 println!("Struct(ref {}, ref {}, None) = {},", path_pat, fields_pat, current);
414 self.current = path_pat;
415 self.visit_qpath(path, expr.id, expr.span);
416 println!(" {}.len() == {},", fields_pat, fields.len());
417 println!(" // unimplemented: field checks");
419 // FIXME: compute length (needs type info)
420 Expr_::ExprRepeat(ref value, _) => {
421 let value_pat = self.next("value");
422 println!("Repeat(ref {}, _) = {},", value_pat, current);
423 println!("// unimplemented: repeat count check");
424 self.current = value_pat;
425 self.visit_expr(value);
430 fn visit_qpath(&mut self, path: &QPath, _: NodeId, _: Span) {
431 print!(" match_qpath({}, &[", self.current);
432 print_path(path, &mut true);
435 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
436 NestedVisitorMap::None
440 fn has_attr(attrs: &[Attribute]) -> bool {
441 attrs.iter().any(|attr| {
442 attr.check_name("clippy") &&
443 attr.meta_item_list().map_or(false, |list| {
446 ast::NestedMetaItemKind::MetaItem(ref it) => it.name == "author",
447 ast::NestedMetaItemKind::Literal(_) => false,
453 fn print_path(path: &QPath, first: &mut bool) {
455 QPath::Resolved(_, ref path) => {
456 for segment in &path.segments {
462 print!("{:?}", segment.name.as_str());
465 QPath::TypeRelative(ref ty, ref segment) => {
467 hir::Ty_::TyPath(ref inner_path) => {
468 print_path(inner_path, first);
474 print!("{:?}", segment.name.as_str());
476 ref other => print!("/* unimplemented: {:?}*/", other),