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