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