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