]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/functions.rs
update to the rust-PR that unblocks clippy
[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<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions {
72     fn check_fn(
73         &mut self,
74         cx: &LateContext<'a, 'tcx>,
75         kind: intravisit::FnKind<'tcx>,
76         decl: &'tcx hir::FnDecl,
77         expr: &'tcx hir::Expr,
78         span: Span,
79         nodeid: ast::NodeId,
80     ) {
81         use rustc::hir::map::Node::*;
82
83         let is_impl = if let Some(NodeItem(item)) = cx.tcx.map.find(cx.tcx.map.get_parent_node(nodeid)) {
84             matches!(item.node, hir::ItemImpl(_, _, _, Some(_), _, _) | hir::ItemDefaultImpl(..))
85         } else {
86             false
87         };
88
89         let unsafety = match kind {
90             hir::intravisit::FnKind::ItemFn(_, _, unsafety, _, _, _, _) => unsafety,
91             hir::intravisit::FnKind::Method(_, sig, _, _) => sig.unsafety,
92             hir::intravisit::FnKind::Closure(_) => return,
93         };
94
95         // don't warn for implementations, it's not their fault
96         if !is_impl {
97             // don't lint extern functions decls, it's not their fault either
98             match kind {
99                 hir::intravisit::FnKind::Method(_, &hir::MethodSig { abi: Abi::Rust, .. }, _, _) |
100                 hir::intravisit::FnKind::ItemFn(_, _, _, _, Abi::Rust, _, _) => self.check_arg_number(cx, decl, span),
101                 _ => {},
102             }
103         }
104
105         self.check_raw_ptr(cx, unsafety, decl, expr, nodeid);
106     }
107
108     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
109         if let hir::MethodTraitItem(ref sig, eid) = item.node {
110             // don't lint extern functions decls, it's not their fault
111             if sig.abi == Abi::Rust {
112                 self.check_arg_number(cx, &sig.decl, item.span);
113             }
114
115             if let Some(eid) = eid {
116                 let expr = cx.tcx.map.expr(eid);
117                 self.check_raw_ptr(cx, sig.unsafety, &sig.decl, expr, item.id);
118             }
119         }
120     }
121 }
122
123 impl<'a, 'tcx> Functions {
124     fn check_arg_number(&self, cx: &LateContext, decl: &hir::FnDecl, span: Span) {
125         let args = decl.inputs.len() as u64;
126         if args > self.threshold {
127             span_lint(cx,
128                       TOO_MANY_ARGUMENTS,
129                       span,
130                       &format!("this function has too many arguments ({}/{})", args, self.threshold));
131         }
132     }
133
134     fn check_raw_ptr(
135         &self,
136         cx: &LateContext<'a, 'tcx>,
137         unsafety: hir::Unsafety,
138         decl: &'tcx hir::FnDecl,
139         expr: &'tcx hir::Expr,
140         nodeid: ast::NodeId,
141     ) {
142         if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(nodeid) {
143             let raw_ptrs = decl.inputs.iter().filter_map(|arg| raw_ptr_arg(cx, arg)).collect::<HashSet<_>>();
144
145             if !raw_ptrs.is_empty() {
146                 let mut v = DerefVisitor {
147                     cx: cx,
148                     ptrs: raw_ptrs,
149                 };
150
151                 hir::intravisit::walk_expr(&mut v, expr);
152             }
153         }
154     }
155 }
156
157 fn raw_ptr_arg(_cx: &LateContext, arg: &hir::Arg) -> Option<hir::def_id::DefId> {
158     if let (&hir::PatKind::Binding(_, def_id, _, _), &hir::TyPtr(_)) = (&arg.pat.node, &arg.ty.node) {
159         Some(def_id)
160     } else {
161         None
162     }
163 }
164
165 struct DerefVisitor<'a, 'tcx: 'a> {
166     cx: &'a LateContext<'a, 'tcx>,
167     ptrs: HashSet<hir::def_id::DefId>,
168 }
169
170 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
171     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
172         match expr.node {
173             hir::ExprCall(ref f, ref args) => {
174                 let ty = self.cx.tcx.tables().expr_ty(f);
175
176                 if type_is_unsafe_function(ty) {
177                     for arg in args {
178                         self.check_arg(arg);
179                     }
180                 }
181             }
182             hir::ExprMethodCall(_, _, ref args) => {
183                 let method_call = ty::MethodCall::expr(expr.id);
184                 let base_type = self.cx.tcx.tables.borrow().method_map[&method_call].ty;
185
186                 if type_is_unsafe_function(base_type) {
187                     for arg in args {
188                         self.check_arg(arg);
189                     }
190                 }
191             }
192             hir::ExprUnary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
193             _ => (),
194         }
195
196         hir::intravisit::walk_expr(self, expr);
197     }
198     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
199         intravisit::NestedVisitorMap::All(&self.cx.tcx.map)
200     }
201 }
202
203 impl<'a, 'tcx: 'a> DerefVisitor<'a, 'tcx> {
204     fn check_arg(&self, ptr: &hir::Expr) {
205         if let hir::ExprPath(ref qpath) = ptr.node {
206             let def = self.cx.tcx.tables().qpath_def(qpath, ptr.id);
207             if self.ptrs.contains(&def.def_id()) {
208                 span_lint(self.cx,
209                           NOT_UNSAFE_PTR_ARG_DEREF,
210                           ptr.span,
211                           "this public function dereferences a raw pointer but is not marked `unsafe`");
212             }
213         }
214     }
215 }