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 dereference 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.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
111 matches!(item.node, hir::ItemKind::Impl(_, _, _, _, Some(_), _, _))
116 let unsafety = match kind {
117 hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { unsafety, .. }, _, _) => unsafety,
118 hir::intravisit::FnKind::Method(_, sig, _, _) => sig.header.unsafety,
119 hir::intravisit::FnKind::Closure(_) => return,
122 // don't warn for implementations, it's not their fault
124 // don't lint extern functions decls, it's not their fault either
126 hir::intravisit::FnKind::Method(
129 header: hir::FnHeader { abi: Abi::Rust, .. },
135 | hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _, _) => {
136 self.check_arg_number(cx, decl, span)
142 self.check_raw_ptr(cx, unsafety, decl, body, hir_id);
143 self.check_line_number(cx, span, body);
146 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
147 if let hir::TraitItemKind::Method(ref sig, ref eid) = item.node {
148 // don't lint extern functions decls, it's not their fault
149 if sig.header.abi == Abi::Rust {
150 self.check_arg_number(cx, &sig.decl, item.span);
153 if let hir::TraitMethod::Provided(eid) = *eid {
154 let body = cx.tcx.hir().body(eid);
155 self.check_raw_ptr(cx, sig.header.unsafety, &sig.decl, body, item.hir_id);
161 impl<'a, 'tcx> Functions {
162 fn check_arg_number(self, cx: &LateContext<'_, '_>, decl: &hir::FnDecl, span: Span) {
163 // Remove the function body from the span. We can't use `SourceMap::def_span` because the
164 // argument list might span multiple lines.
165 let span = if let Some(snippet) = snippet_opt(cx, span) {
166 let snippet = snippet.split('{').nth(0).unwrap_or("").trim_end();
167 if snippet.is_empty() {
170 span.with_hi(BytePos(span.lo().0 + u32::try_from(snippet.len()).unwrap()))
176 let args = decl.inputs.len() as u64;
177 if args > self.threshold {
182 &format!("this function has too many arguments ({}/{})", args, self.threshold),
187 fn check_line_number(self, cx: &LateContext<'_, '_>, span: Span, body: &'tcx hir::Body) {
188 if in_external_macro(cx.sess(), span) {
192 let code_snippet = snippet(cx, body.value.span, "..");
193 let mut line_count: u64 = 0;
194 let mut in_comment = false;
195 let mut code_in_line;
197 // Skip the surrounding function decl.
198 let start_brace_idx = match code_snippet.find('{') {
202 let end_brace_idx = match code_snippet.find('}') {
204 None => code_snippet.len(),
206 let function_lines = code_snippet[start_brace_idx..end_brace_idx].lines();
208 for mut line in function_lines {
209 code_in_line = false;
211 line = line.trim_start();
216 match line.find("*/") {
218 line = &line[i + 2..];
225 let multi_idx = match line.find("/*") {
229 let single_idx = match line.find("//") {
233 code_in_line |= multi_idx > 0 && single_idx > 0;
234 // Implies multi_idx is below line.len()
235 if multi_idx < single_idx {
236 line = &line[multi_idx + 2..];
248 if line_count > self.max_lines {
249 span_lint(cx, TOO_MANY_LINES, span, "This function has a large number of lines.")
255 cx: &LateContext<'a, 'tcx>,
256 unsafety: hir::Unsafety,
257 decl: &'tcx hir::FnDecl,
258 body: &'tcx hir::Body,
261 let expr = &body.value;
262 if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(hir_id) {
263 let raw_ptrs = iter_input_pats(decl, body)
264 .zip(decl.inputs.iter())
265 .filter_map(|(arg, ty)| raw_ptr_arg(arg, ty))
266 .collect::<FxHashSet<_>>();
268 if !raw_ptrs.is_empty() {
269 let tables = cx.tcx.body_tables(body.id());
270 let mut v = DerefVisitor {
276 hir::intravisit::walk_expr(&mut v, expr);
282 fn raw_ptr_arg(arg: &hir::Arg, ty: &hir::Ty) -> Option<hir::HirId> {
283 if let (&hir::PatKind::Binding(_, id, _, _), &hir::TyKind::Ptr(_)) = (&arg.pat.node, &ty.node) {
290 struct DerefVisitor<'a, 'tcx> {
291 cx: &'a LateContext<'a, 'tcx>,
292 ptrs: FxHashSet<hir::HirId>,
293 tables: &'a ty::TypeckTables<'tcx>,
296 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
297 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
299 hir::ExprKind::Call(ref f, ref args) => {
300 let ty = self.tables.expr_ty(f);
302 if type_is_unsafe_function(self.cx, ty) {
308 hir::ExprKind::MethodCall(_, _, ref args) => {
309 let def_id = self.tables.type_dependent_def_id(expr.hir_id).unwrap();
310 let base_type = self.cx.tcx.type_of(def_id);
312 if type_is_unsafe_function(self.cx, base_type) {
318 hir::ExprKind::Unary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
322 hir::intravisit::walk_expr(self, expr);
324 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
325 intravisit::NestedVisitorMap::None
329 impl<'a, 'tcx> DerefVisitor<'a, 'tcx> {
330 fn check_arg(&self, ptr: &hir::Expr) {
331 if let hir::ExprKind::Path(ref qpath) = ptr.node {
332 if let Res::Local(id) = self.cx.tables.qpath_res(qpath, ptr.hir_id) {
333 if self.ptrs.contains(&id) {
336 NOT_UNSAFE_PTR_ARG_DEREF,
338 "this public function dereferences a raw pointer but is not marked `unsafe`",