]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/functions.rs
Merge pull request #3285 from devonhollowood/pedantic-dogfood-items-after-statements
[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
11 use matches::matches;
12 use crate::rustc::hir::intravisit;
13 use crate::rustc::hir;
14 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
15 use crate::rustc::{declare_tool_lint, lint_array};
16 use crate::rustc::ty;
17 use crate::rustc::hir::def::Def;
18 use crate::rustc_data_structures::fx::FxHashSet;
19 use crate::syntax::ast;
20 use crate::rustc_target::spec::abi::Abi;
21 use crate::syntax::source_map::Span;
22 use crate::utils::{iter_input_pats, span_lint, type_is_unsafe_function};
23
24 /// **What it does:** Checks for functions with too many parameters.
25 ///
26 /// **Why is this bad?** Functions with lots of parameters are considered bad
27 /// style and reduce readability (“what does the 5th parameter mean?”). Consider
28 /// grouping some parameters into a new type.
29 ///
30 /// **Known problems:** None.
31 ///
32 /// **Example:**
33 /// ```rust
34 /// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b:
35 /// f32) { .. }
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) { println!("{}", unsafe { *x }); }
62 /// ```
63 declare_clippy_lint! {
64     pub NOT_UNSAFE_PTR_ARG_DEREF,
65     correctness,
66     "public functions dereferencing raw pointer arguments but not marked `unsafe`"
67 }
68
69 #[derive(Copy, Clone)]
70 pub struct Functions {
71     threshold: u64,
72 }
73
74 impl Functions {
75     pub fn new(threshold: u64) -> Self {
76         Self {
77             threshold,
78         }
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(_, &hir::MethodSig { header: hir::FnHeader { abi: Abi::Rust, .. }, .. }, _, _) |
115                 hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _, _) => self.check_arg_number(cx, decl, span),
116                 _ => {},
117             }
118         }
119
120         self.check_raw_ptr(cx, unsafety, decl, body, nodeid);
121     }
122
123     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
124         if let hir::TraitItemKind::Method(ref sig, ref eid) = item.node {
125             // don't lint extern functions decls, it's not their fault
126             if sig.header.abi == Abi::Rust {
127                 self.check_arg_number(cx, &sig.decl, item.span);
128             }
129
130             if let hir::TraitMethod::Provided(eid) = *eid {
131                 let body = cx.tcx.hir.body(eid);
132                 self.check_raw_ptr(cx, sig.header.unsafety, &sig.decl, body, item.id);
133             }
134         }
135     }
136 }
137
138 impl<'a, 'tcx> Functions {
139     fn check_arg_number(self, cx: &LateContext<'_, '_>, decl: &hir::FnDecl, span: Span) {
140         let args = decl.inputs.len() as u64;
141         if args > self.threshold {
142             span_lint(
143                 cx,
144                 TOO_MANY_ARGUMENTS,
145                 span,
146                 &format!("this function has too many arguments ({}/{})", args, self.threshold),
147             );
148         }
149     }
150
151     fn check_raw_ptr(
152         self,
153         cx: &LateContext<'a, 'tcx>,
154         unsafety: hir::Unsafety,
155         decl: &'tcx hir::FnDecl,
156         body: &'tcx hir::Body,
157         nodeid: ast::NodeId,
158     ) {
159         let expr = &body.value;
160         if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(nodeid) {
161             let raw_ptrs = iter_input_pats(decl, body)
162                 .zip(decl.inputs.iter())
163                 .filter_map(|(arg, ty)| raw_ptr_arg(arg, ty))
164                 .collect::<FxHashSet<_>>();
165
166             if !raw_ptrs.is_empty() {
167                 let tables = cx.tcx.body_tables(body.id());
168                 let mut v = DerefVisitor {
169                     cx,
170                     ptrs: raw_ptrs,
171                     tables,
172                 };
173
174                 hir::intravisit::walk_expr(&mut v, expr);
175             }
176         }
177     }
178 }
179
180 fn raw_ptr_arg(arg: &hir::Arg, ty: &hir::Ty) -> Option<ast::NodeId> {
181     if let (&hir::PatKind::Binding(_, id, _, _), &hir::TyKind::Ptr(_)) = (&arg.pat.node, &ty.node) {
182         Some(id)
183     } else {
184         None
185     }
186 }
187
188 struct DerefVisitor<'a, 'tcx: 'a> {
189     cx: &'a LateContext<'a, 'tcx>,
190     ptrs: FxHashSet<ast::NodeId>,
191     tables: &'a ty::TypeckTables<'tcx>,
192 }
193
194 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
195     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
196         match expr.node {
197             hir::ExprKind::Call(ref f, ref args) => {
198                 let ty = self.tables.expr_ty(f);
199
200                 if type_is_unsafe_function(self.cx, ty) {
201                     for arg in args {
202                         self.check_arg(arg);
203                     }
204                 }
205             },
206             hir::ExprKind::MethodCall(_, _, ref args) => {
207                 let def_id = self.tables.type_dependent_defs()[expr.hir_id].def_id();
208                 let base_type = self.cx.tcx.type_of(def_id);
209
210                 if type_is_unsafe_function(self.cx, base_type) {
211                     for arg in args {
212                         self.check_arg(arg);
213                     }
214                 }
215             },
216             hir::ExprKind::Unary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
217             _ => (),
218         }
219
220         hir::intravisit::walk_expr(self, expr);
221     }
222     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
223         intravisit::NestedVisitorMap::None
224     }
225 }
226
227 impl<'a, 'tcx: 'a> DerefVisitor<'a, 'tcx> {
228     fn check_arg(&self, ptr: &hir::Expr) {
229         if let hir::ExprKind::Path(ref qpath) = ptr.node {
230             if let Def::Local(id) = self.cx.tables.qpath_def(qpath, ptr.hir_id) {
231                 if self.ptrs.contains(&id) {
232                     span_lint(
233                         self.cx,
234                         NOT_UNSAFE_PTR_ARG_DEREF,
235                         ptr.span,
236                         "this public function dereferences a raw pointer but is not marked `unsafe`",
237                     );
238                 }
239             }
240         }
241     }
242 }