1 use std::convert::TryFrom;
3 use crate::utils::{iter_input_pats, snippet, snippet_opt, span_lint, type_is_unsafe_function};
6 use rustc::hir::def::Res;
7 use rustc::hir::intravisit;
8 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
10 use rustc::{declare_tool_lint, impl_lint_pass};
11 use rustc_data_structures::fx::FxHashSet;
12 use rustc_target::spec::abi::Abi;
13 use syntax::source_map::{BytePos, Span};
15 declare_clippy_lint! {
16 /// **What it does:** Checks for functions with too many parameters.
18 /// **Why is this bad?** Functions with lots of parameters are considered bad
19 /// style and reduce readability (“what does the 5th parameter mean?”). Consider
20 /// grouping some parameters into a new type.
22 /// **Known problems:** None.
26 /// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) {
30 pub TOO_MANY_ARGUMENTS,
32 "functions with too many arguments"
35 declare_clippy_lint! {
36 /// **What it does:** Checks for functions with a large amount of lines.
38 /// **Why is this bad?** Functions with a lot of lines are harder to understand
39 /// due to having to look at a larger amount of code to understand what the
40 /// function is doing. Consider splitting the body of the function into
41 /// multiple functions.
43 /// **Known problems:** None.
47 /// fn im_too_long() {
49 /// // ... 100 more LoC
55 "functions with too many lines"
58 declare_clippy_lint! {
59 /// **What it does:** Checks for public functions that dereferences raw pointer
60 /// arguments but are not marked unsafe.
62 /// **Why is this bad?** The function should probably be marked `unsafe`, since
63 /// for an arbitrary raw pointer, there is no way of telling for sure if it is
66 /// **Known problems:**
68 /// * It does not check functions recursively so if the pointer is passed to a
69 /// private non-`unsafe` function which does the dereferencing, the lint won't
71 /// * It only checks for arguments whose type are raw pointers, not raw pointers
72 /// got from an argument in some other way (`fn foo(bar: &[*const u8])` or
73 /// `some_argument.get_raw_ptr()`).
77 /// pub fn foo(x: *const u8) {
78 /// println!("{}", unsafe { *x });
81 pub NOT_UNSAFE_PTR_ARG_DEREF,
83 "public functions dereferencing raw pointer arguments but not marked `unsafe`"
86 #[derive(Copy, Clone)]
87 pub struct Functions {
93 pub fn new(threshold: u64, max_lines: u64) -> Self {
94 Self { threshold, max_lines }
98 impl_lint_pass!(Functions => [TOO_MANY_ARGUMENTS, TOO_MANY_LINES, NOT_UNSAFE_PTR_ARG_DEREF]);
100 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions {
103 cx: &LateContext<'a, 'tcx>,
104 kind: intravisit::FnKind<'tcx>,
105 decl: &'tcx hir::FnDecl,
106 body: &'tcx hir::Body,
110 let is_impl = if let Some(hir::Node::Item(item)) = cx
113 .find_by_hir_id(cx.tcx.hir().get_parent_node_by_hir_id(hir_id))
115 matches!(item.node, hir::ItemKind::Impl(_, _, _, _, Some(_), _, _))
120 let unsafety = match kind {
121 hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { unsafety, .. }, _, _) => unsafety,
122 hir::intravisit::FnKind::Method(_, sig, _, _) => sig.header.unsafety,
123 hir::intravisit::FnKind::Closure(_) => return,
126 // don't warn for implementations, it's not their fault
128 // don't lint extern functions decls, it's not their fault either
130 hir::intravisit::FnKind::Method(
133 header: hir::FnHeader { abi: Abi::Rust, .. },
139 | hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _, _) => {
140 self.check_arg_number(cx, decl, span)
146 self.check_raw_ptr(cx, unsafety, decl, body, hir_id);
147 self.check_line_number(cx, span, body);
150 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
151 if let hir::TraitItemKind::Method(ref sig, ref eid) = item.node {
152 // don't lint extern functions decls, it's not their fault
153 if sig.header.abi == Abi::Rust {
154 self.check_arg_number(cx, &sig.decl, item.span);
157 if let hir::TraitMethod::Provided(eid) = *eid {
158 let body = cx.tcx.hir().body(eid);
159 self.check_raw_ptr(cx, sig.header.unsafety, &sig.decl, body, item.hir_id);
165 impl<'a, 'tcx> Functions {
166 fn check_arg_number(self, cx: &LateContext<'_, '_>, decl: &hir::FnDecl, span: Span) {
167 // Remove the function body from the span. We can't use `SourceMap::def_span` because the
168 // argument list might span multiple lines.
169 let span = if let Some(snippet) = snippet_opt(cx, span) {
170 let snippet = snippet.split('{').nth(0).unwrap_or("").trim_end();
171 if snippet.is_empty() {
174 span.with_hi(BytePos(span.lo().0 + u32::try_from(snippet.len()).unwrap()))
180 let args = decl.inputs.len() as u64;
181 if args > self.threshold {
186 &format!("this function has too many arguments ({}/{})", args, self.threshold),
191 fn check_line_number(self, cx: &LateContext<'_, '_>, span: Span, body: &'tcx hir::Body) {
192 if in_external_macro(cx.sess(), span) {
196 let code_snippet = snippet(cx, body.value.span, "..");
197 let mut line_count: u64 = 0;
198 let mut in_comment = false;
199 let mut code_in_line;
201 // Skip the surrounding function decl.
202 let start_brace_idx = match code_snippet.find('{') {
206 let end_brace_idx = match code_snippet.find('}') {
208 None => code_snippet.len(),
210 let function_lines = code_snippet[start_brace_idx..end_brace_idx].lines();
212 for mut line in function_lines {
213 code_in_line = false;
215 line = line.trim_start();
220 match line.find("*/") {
222 line = &line[i + 2..];
229 let multi_idx = match line.find("/*") {
233 let single_idx = match line.find("//") {
237 code_in_line |= multi_idx > 0 && single_idx > 0;
238 // Implies multi_idx is below line.len()
239 if multi_idx < single_idx {
240 line = &line[multi_idx + 2..];
252 if line_count > self.max_lines {
253 span_lint(cx, TOO_MANY_LINES, span, "This function has a large number of lines.")
259 cx: &LateContext<'a, 'tcx>,
260 unsafety: hir::Unsafety,
261 decl: &'tcx hir::FnDecl,
262 body: &'tcx hir::Body,
265 let expr = &body.value;
266 if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(hir_id) {
267 let raw_ptrs = iter_input_pats(decl, body)
268 .zip(decl.inputs.iter())
269 .filter_map(|(arg, ty)| raw_ptr_arg(arg, ty))
270 .collect::<FxHashSet<_>>();
272 if !raw_ptrs.is_empty() {
273 let tables = cx.tcx.body_tables(body.id());
274 let mut v = DerefVisitor {
280 hir::intravisit::walk_expr(&mut v, expr);
286 fn raw_ptr_arg(arg: &hir::Arg, ty: &hir::Ty) -> Option<hir::HirId> {
287 if let (&hir::PatKind::Binding(_, id, _, _), &hir::TyKind::Ptr(_)) = (&arg.pat.node, &ty.node) {
294 struct DerefVisitor<'a, 'tcx: 'a> {
295 cx: &'a LateContext<'a, 'tcx>,
296 ptrs: FxHashSet<hir::HirId>,
297 tables: &'a ty::TypeckTables<'tcx>,
300 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
301 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
303 hir::ExprKind::Call(ref f, ref args) => {
304 let ty = self.tables.expr_ty(f);
306 if type_is_unsafe_function(self.cx, ty) {
312 hir::ExprKind::MethodCall(_, _, ref args) => {
313 let def_id = self.tables.type_dependent_def_id(expr.hir_id).unwrap();
314 let base_type = self.cx.tcx.type_of(def_id);
316 if type_is_unsafe_function(self.cx, base_type) {
322 hir::ExprKind::Unary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
326 hir::intravisit::walk_expr(self, expr);
328 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
329 intravisit::NestedVisitorMap::None
333 impl<'a, 'tcx: 'a> DerefVisitor<'a, 'tcx> {
334 fn check_arg(&self, ptr: &hir::Expr) {
335 if let hir::ExprKind::Path(ref qpath) = ptr.node {
336 if let Res::Local(id) = self.cx.tables.qpath_res(qpath, ptr.hir_id) {
337 if self.ptrs.contains(&id) {
340 NOT_UNSAFE_PTR_ARG_DEREF,
342 "this public function dereferences a raw pointer but is not marked `unsafe`",