]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/functions.rs
Make #991 work with current rust
[rust.git] / clippy_lints / src / functions.rs
1 use rustc::hir::intravisit;
2 use rustc::hir;
3 use rustc::ty;
4 use rustc::lint::*;
5 use std::collections::HashSet;
6 use syntax::ast;
7 use syntax::codemap::Span;
8 use utils::{span_lint, type_is_unsafe_function};
9
10 /// **What it does:** Check for functions with too many parameters.
11 ///
12 /// **Why is this bad?** Functions with lots of parameters are considered bad style and reduce
13 /// readability (“what does the 5th parameter mean?”). Consider grouping some parameters into a
14 /// new type.
15 ///
16 /// **Known problems:** None.
17 ///
18 /// **Example:**
19 ///
20 /// ```rust
21 /// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) { .. }
22 /// ```
23 declare_lint! {
24     pub TOO_MANY_ARGUMENTS,
25     Warn,
26     "functions with too many arguments"
27 }
28
29 /// **What it does:** Check for public functions that dereferences raw pointer arguments but are
30 /// not marked unsafe.
31 ///
32 /// **Why is this bad?** The function should probably be marked `unsafe`, since for an arbitrary
33 /// raw pointer, there is no way of telling for sure if it is valid.
34 ///
35 /// **Known problems:**
36 ///
37 /// * It does not check functions recursively so if the pointer is passed to a private non-
38 /// `unsafe` function which does the dereferencing, the lint won't trigger.
39 /// * It only checks for arguments whose type are raw pointers, not raw pointers got from an
40 /// argument in some other way (`fn foo(bar: &[*const u8])` or `some_argument.get_raw_ptr()`).
41 ///
42 /// **Example:**
43 ///
44 /// ```rust
45 /// pub fn foo(x: *const u8) { println!("{}", unsafe { *x }); }
46 /// ```
47 declare_lint! {
48     pub NOT_UNSAFE_PTR_ARG_DEREF,
49     Warn,
50     "public functions dereferencing raw pointer arguments but not marked `unsafe`"
51 }
52
53 #[derive(Copy,Clone)]
54 pub struct Functions {
55     threshold: u64,
56 }
57
58 impl Functions {
59     pub fn new(threshold: u64) -> Functions {
60         Functions { threshold: threshold }
61     }
62 }
63
64 impl LintPass for Functions {
65     fn get_lints(&self) -> LintArray {
66         lint_array!(TOO_MANY_ARGUMENTS, NOT_UNSAFE_PTR_ARG_DEREF)
67     }
68 }
69
70 impl LateLintPass for Functions {
71     fn check_fn(&mut self, cx: &LateContext, kind: intravisit::FnKind, decl: &hir::FnDecl, block: &hir::Block, span: Span, nodeid: ast::NodeId) {
72         use rustc::hir::map::Node::*;
73
74         let is_impl = if let Some(NodeItem(ref item)) = cx.tcx.map.find(cx.tcx.map.get_parent_node(nodeid)) {
75             matches!(item.node, hir::ItemImpl(_, _, _, Some(_), _, _) | hir::ItemDefaultImpl(..))
76         } else {
77             false
78         };
79
80         let unsafety = match kind {
81             hir::intravisit::FnKind::ItemFn(_, _, unsafety, _, _, _, _) => unsafety,
82             hir::intravisit::FnKind::Method(_, sig, _, _) => sig.unsafety,
83             hir::intravisit::FnKind::Closure(_) => return,
84         };
85
86         // don't warn for implementations, it's not their fault
87         if !is_impl {
88             self.check_arg_number(cx, decl, span);
89         }
90
91         self.check_raw_ptr(cx, unsafety, decl, block, nodeid);
92     }
93
94     fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
95         if let hir::MethodTraitItem(ref sig, ref block) = item.node {
96             self.check_arg_number(cx, &sig.decl, item.span);
97
98             if let Some(ref block) = *block {
99                 self.check_raw_ptr(cx, sig.unsafety, &sig.decl, block, item.id);
100             }
101         }
102     }
103 }
104
105 impl Functions {
106     fn check_arg_number(&self, cx: &LateContext, decl: &hir::FnDecl, span: Span) {
107         let args = decl.inputs.len() as u64;
108         if args > self.threshold {
109             span_lint(cx,
110                       TOO_MANY_ARGUMENTS,
111                       span,
112                       &format!("this function has too many arguments ({}/{})", args, self.threshold));
113         }
114     }
115
116     fn check_raw_ptr(&self, cx: &LateContext, unsafety: hir::Unsafety, decl: &hir::FnDecl, block: &hir::Block, nodeid: ast::NodeId) {
117         if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(nodeid) {
118             let raw_ptrs = decl.inputs.iter().filter_map(|arg| raw_ptr_arg(cx, arg)).collect::<HashSet<_>>();
119
120             if !raw_ptrs.is_empty() {
121                 let mut v = DerefVisitor {
122                     cx: cx,
123                     ptrs: raw_ptrs,
124                 };
125
126                 hir::intravisit::walk_block(&mut v, block);
127             }
128         }
129     }
130 }
131
132 fn raw_ptr_arg(cx: &LateContext, arg: &hir::Arg) -> Option<hir::def_id::DefId> {
133     if let (&hir::PatKind::Binding(_, _, _), &hir::TyPtr(_)) = (&arg.pat.node, &arg.ty.node) {
134         cx.tcx.def_map.borrow().get(&arg.pat.id).map(|pr| pr.full_def().def_id())
135     } else {
136         None
137     }
138 }
139
140 struct DerefVisitor<'a, 'tcx: 'a> {
141     cx: &'a LateContext<'a, 'tcx>,
142     ptrs: HashSet<hir::def_id::DefId>,
143 }
144
145 impl<'a, 'tcx, 'v> hir::intravisit::Visitor<'v> for DerefVisitor<'a, 'tcx> {
146     fn visit_expr(&mut self, expr: &'v hir::Expr) {
147         match expr.node {
148             hir::ExprCall(ref f, ref args) => {
149                 let ty = self.cx.tcx.expr_ty(f);
150
151                 if type_is_unsafe_function(ty) {
152                     for arg in args {
153                         self.check_arg(arg);
154                     }
155                 }
156             }
157             hir::ExprMethodCall(_, _, ref args) => {
158                 let method_call = ty::MethodCall::expr(expr.id);
159                 let base_type = self.cx.tcx.tables.borrow().method_map[&method_call].ty;
160
161                 if type_is_unsafe_function(base_type) {
162                     for arg in args {
163                         self.check_arg(arg);
164                     }
165                 }
166             }
167             hir::ExprUnary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
168             _ => (),
169         }
170
171         hir::intravisit::walk_expr(self, expr);
172     }
173 }
174
175 impl<'a, 'tcx: 'a> DerefVisitor<'a, 'tcx> {
176     fn check_arg(&self, ptr: &hir::Expr) {
177         if let Some(def) = self.cx.tcx.def_map.borrow().get(&ptr.id) {
178             if self.ptrs.contains(&def.full_def().def_id()) {
179                 span_lint(self.cx,
180                           NOT_UNSAFE_PTR_ARG_DEREF,
181                           ptr.span,
182                           "this public function dereferences a raw pointer but is not marked `unsafe`");
183             }
184         }
185     }
186 }