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.
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};
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};
24 /// **What it does:** Checks for functions with too many parameters.
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.
30 /// **Known problems:** None.
34 /// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b:
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) { println!("{}", unsafe { *x }); }
63 declare_clippy_lint! {
64 pub NOT_UNSAFE_PTR_ARG_DEREF,
66 "public functions dereferencing raw pointer arguments but not marked `unsafe`"
69 #[derive(Copy, Clone)]
70 pub struct Functions {
75 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(_, &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),
120 self.check_raw_ptr(cx, unsafety, decl, body, nodeid);
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);
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);
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 {
146 &format!("this function has too many arguments ({}/{})", args, self.threshold),
153 cx: &LateContext<'a, 'tcx>,
154 unsafety: hir::Unsafety,
155 decl: &'tcx hir::FnDecl,
156 body: &'tcx hir::Body,
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<_>>();
166 if !raw_ptrs.is_empty() {
167 let tables = cx.tcx.body_tables(body.id());
168 let mut v = DerefVisitor {
174 hir::intravisit::walk_expr(&mut v, expr);
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) {
188 struct DerefVisitor<'a, 'tcx: 'a> {
189 cx: &'a LateContext<'a, 'tcx>,
190 ptrs: FxHashSet<ast::NodeId>,
191 tables: &'a ty::TypeckTables<'tcx>,
194 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
195 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
197 hir::ExprKind::Call(ref f, ref args) => {
198 let ty = self.tables.expr_ty(f);
200 if type_is_unsafe_function(self.cx, ty) {
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);
210 if type_is_unsafe_function(self.cx, base_type) {
216 hir::ExprKind::Unary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
220 hir::intravisit::walk_expr(self, expr);
222 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
223 intravisit::NestedVisitorMap::None
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) {
234 NOT_UNSAFE_PTR_ARG_DEREF,
236 "this public function dereferences a raw pointer but is not marked `unsafe`",