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