1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
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.
10 use crate::utils::{iter_input_pats, span_lint, type_is_unsafe_function};
13 use rustc::hir::def::Def;
14 use rustc::hir::intravisit;
15 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
17 use rustc::{declare_tool_lint, lint_array};
18 use rustc_data_structures::fx::FxHashSet;
19 use rustc_target::spec::abi::Abi;
21 use syntax::source_map::Span;
23 /// **What it does:** Checks for functions with too many parameters.
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.
29 /// **Known problems:** None.
33 /// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) {
37 declare_clippy_lint! {
38 pub TOO_MANY_ARGUMENTS,
40 "functions with too many arguments"
43 /// **What it does:** Checks for public functions that dereferences raw pointer
44 /// arguments but are not marked unsafe.
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
50 /// **Known problems:**
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
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()`).
61 /// pub fn foo(x: *const u8) {
62 /// println!("{}", unsafe { *x });
65 declare_clippy_lint! {
66 pub NOT_UNSAFE_PTR_ARG_DEREF,
68 "public functions dereferencing raw pointer arguments but not marked `unsafe`"
71 #[derive(Copy, Clone)]
72 pub struct Functions {
77 pub fn new(threshold: u64) -> Self {
82 impl LintPass for Functions {
83 fn get_lints(&self) -> LintArray {
84 lint_array!(TOO_MANY_ARGUMENTS, NOT_UNSAFE_PTR_ARG_DEREF)
88 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions {
91 cx: &LateContext<'a, 'tcx>,
92 kind: intravisit::FnKind<'tcx>,
93 decl: &'tcx hir::FnDecl,
94 body: &'tcx hir::Body,
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(_), _, _))
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,
110 // don't warn for implementations, it's not their fault
112 // don't lint extern functions decls, it's not their fault either
114 hir::intravisit::FnKind::Method(
117 header: hir::FnHeader { abi: Abi::Rust, .. },
123 | hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _, _) => {
124 self.check_arg_number(cx, decl, span)
130 self.check_raw_ptr(cx, unsafety, decl, body, nodeid);
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);
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);
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 {
156 &format!("this function has too many arguments ({}/{})", args, self.threshold),
163 cx: &LateContext<'a, 'tcx>,
164 unsafety: hir::Unsafety,
165 decl: &'tcx hir::FnDecl,
166 body: &'tcx hir::Body,
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<_>>();
176 if !raw_ptrs.is_empty() {
177 let tables = cx.tcx.body_tables(body.id());
178 let mut v = DerefVisitor {
184 hir::intravisit::walk_expr(&mut v, expr);
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) {
198 struct DerefVisitor<'a, 'tcx: 'a> {
199 cx: &'a LateContext<'a, 'tcx>,
200 ptrs: FxHashSet<ast::NodeId>,
201 tables: &'a ty::TypeckTables<'tcx>,
204 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
205 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
207 hir::ExprKind::Call(ref f, ref args) => {
208 let ty = self.tables.expr_ty(f);
210 if type_is_unsafe_function(self.cx, ty) {
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);
220 if type_is_unsafe_function(self.cx, base_type) {
226 hir::ExprKind::Unary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
230 hir::intravisit::walk_expr(self, expr);
232 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
233 intravisit::NestedVisitorMap::None
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) {
244 NOT_UNSAFE_PTR_ARG_DEREF,
246 "this public function dereferences a raw pointer but is not marked `unsafe`",