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