]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/functions.rs
Merge branch 'master' into never_loop
[rust.git] / clippy_lints / src / functions.rs
1 use rustc::hir::intravisit;
2 use rustc::hir;
3 use rustc::lint::*;
4 use std::collections::HashSet;
5 use syntax::ast;
6 use syntax::abi::Abi;
7 use syntax::codemap::Span;
8 use utils::{span_lint, type_is_unsafe_function, iter_input_pats};
9
10 /// **What it does:** Checks for functions with too many parameters.
11 ///
12 /// **Why is this bad?** Functions with lots of parameters are considered bad
13 /// style and reduce readability (“what does the 5th parameter mean?”). Consider
14 /// grouping some parameters into a new type.
15 ///
16 /// **Known problems:** None.
17 ///
18 /// **Example:**
19 /// ```rust
20 /// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) { .. }
21 /// ```
22 declare_lint! {
23     pub TOO_MANY_ARGUMENTS,
24     Warn,
25     "functions with too many arguments"
26 }
27
28 /// **What it does:** Checks for public functions that dereferences raw pointer
29 /// arguments but are not marked unsafe.
30 ///
31 /// **Why is this bad?** The function should probably be marked `unsafe`, since
32 /// for an arbitrary raw pointer, there is no way of telling for sure if it is
33 /// valid.
34 ///
35 /// **Known problems:**
36 ///
37 /// * It does not check functions recursively so if the pointer is passed to a
38 /// private non-`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
40 /// got from an argument in some other way (`fn foo(bar: &[*const u8])` or
41 /// `some_argument.get_raw_ptr()`).
42 ///
43 /// **Example:**
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<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions {
71     fn check_fn(
72         &mut self,
73         cx: &LateContext<'a, 'tcx>,
74         kind: intravisit::FnKind<'tcx>,
75         decl: &'tcx hir::FnDecl,
76         body: &'tcx hir::Body,
77         span: Span,
78         nodeid: ast::NodeId
79     ) {
80         use rustc::hir::map::Node::*;
81
82         let is_impl = if let Some(NodeItem(item)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(nodeid)) {
83             matches!(item.node, hir::ItemImpl(_, _, _, _, Some(_), _, _) | hir::ItemDefaultImpl(..))
84         } else {
85             false
86         };
87
88         let unsafety = match kind {
89             hir::intravisit::FnKind::ItemFn(_, _, unsafety, _, _, _, _) => unsafety,
90             hir::intravisit::FnKind::Method(_, sig, _, _) => sig.unsafety,
91             hir::intravisit::FnKind::Closure(_) => return,
92         };
93
94         // don't warn for implementations, it's not their fault
95         if !is_impl {
96             // don't lint extern functions decls, it's not their fault either
97             match kind {
98                 hir::intravisit::FnKind::Method(_, &hir::MethodSig { abi: Abi::Rust, .. }, _, _) |
99                 hir::intravisit::FnKind::ItemFn(_, _, _, _, Abi::Rust, _, _) => self.check_arg_number(cx, decl, span),
100                 _ => {},
101             }
102         }
103
104         self.check_raw_ptr(cx, unsafety, decl, body, nodeid);
105     }
106
107     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
108         if let hir::TraitItemKind::Method(ref sig, ref eid) = item.node {
109             // don't lint extern functions decls, it's not their fault
110             if sig.abi == Abi::Rust {
111                 self.check_arg_number(cx, &sig.decl, item.span);
112             }
113
114             if let hir::TraitMethod::Provided(eid) = *eid {
115                 let body = cx.tcx.hir.body(eid);
116                 self.check_raw_ptr(cx, sig.unsafety, &sig.decl, body, item.id);
117             }
118         }
119     }
120 }
121
122 impl<'a, 'tcx> Functions {
123     fn check_arg_number(&self, cx: &LateContext, decl: &hir::FnDecl, span: Span) {
124         let args = decl.inputs.len() as u64;
125         if args > self.threshold {
126             span_lint(cx,
127                       TOO_MANY_ARGUMENTS,
128                       span,
129                       &format!("this function has too many arguments ({}/{})", args, self.threshold));
130         }
131     }
132
133     fn check_raw_ptr(
134         &self,
135         cx: &LateContext<'a, 'tcx>,
136         unsafety: hir::Unsafety,
137         decl: &'tcx hir::FnDecl,
138         body: &'tcx hir::Body,
139         nodeid: ast::NodeId
140     ) {
141         let expr = &body.value;
142         if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(nodeid) {
143             let raw_ptrs = iter_input_pats(decl, body)
144                 .zip(decl.inputs.iter())
145                 .filter_map(|(arg, ty)| raw_ptr_arg(arg, ty))
146                 .collect::<HashSet<_>>();
147
148             if !raw_ptrs.is_empty() {
149                 let mut v = DerefVisitor {
150                     cx: cx,
151                     ptrs: raw_ptrs,
152                 };
153
154                 hir::intravisit::walk_expr(&mut v, expr);
155             }
156         }
157     }
158 }
159
160 fn raw_ptr_arg(arg: &hir::Arg, ty: &hir::Ty) -> Option<hir::def_id::DefId> {
161     if let (&hir::PatKind::Binding(_, def_id, _, _), &hir::TyPtr(_)) = (&arg.pat.node, &ty.node) {
162         Some(def_id)
163     } else {
164         None
165     }
166 }
167
168 struct DerefVisitor<'a, 'tcx: 'a> {
169     cx: &'a LateContext<'a, 'tcx>,
170     ptrs: HashSet<hir::def_id::DefId>,
171 }
172
173 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
174     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
175         match expr.node {
176             hir::ExprCall(ref f, ref args) => {
177                 let ty = self.cx.tables.expr_ty(f);
178
179                 if type_is_unsafe_function(ty) {
180                     for arg in args {
181                         self.check_arg(arg);
182                     }
183                 }
184             },
185             hir::ExprMethodCall(_, _, ref args) => {
186                 let def_id = self.cx.tables.type_dependent_defs[&expr.id].def_id();
187                 let base_type = self.cx.tcx.type_of(def_id);
188
189                 if type_is_unsafe_function(base_type) {
190                     for arg in args {
191                         self.check_arg(arg);
192                     }
193                 }
194             },
195             hir::ExprUnary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
196             _ => (),
197         }
198
199         hir::intravisit::walk_expr(self, expr);
200     }
201     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
202         intravisit::NestedVisitorMap::None
203     }
204 }
205
206 impl<'a, 'tcx: 'a> DerefVisitor<'a, 'tcx> {
207     fn check_arg(&self, ptr: &hir::Expr) {
208         if let hir::ExprPath(ref qpath) = ptr.node {
209             let def = self.cx.tables.qpath_def(qpath, ptr.id);
210             if self.ptrs.contains(&def.def_id()) {
211                 span_lint(self.cx,
212                           NOT_UNSAFE_PTR_ARG_DEREF,
213                           ptr.span,
214                           "this public function dereferences a raw pointer but is not marked `unsafe`");
215             }
216         }
217     }
218 }