]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/functions.rs
Auto merge of #3845 - euclio:unused-comments, r=phansch
[rust.git] / clippy_lints / src / functions.rs
1 use crate::utils::{iter_input_pats, snippet, span_lint, type_is_unsafe_function};
2 use matches::matches;
3 use rustc::hir;
4 use rustc::hir::def::Def;
5 use rustc::hir::intravisit;
6 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
7 use rustc::ty;
8 use rustc::{declare_tool_lint, lint_array};
9 use rustc_data_structures::fx::FxHashSet;
10 use rustc_target::spec::abi::Abi;
11 use syntax::ast;
12 use syntax::source_map::Span;
13
14 declare_clippy_lint! {
15     /// **What it does:** Checks for functions with too many parameters.
16     ///
17     /// **Why is this bad?** Functions with lots of parameters are considered bad
18     /// style and reduce readability (“what does the 5th parameter mean?”). Consider
19     /// grouping some parameters into a new type.
20     ///
21     /// **Known problems:** None.
22     ///
23     /// **Example:**
24     /// ```rust
25     /// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) {
26     ///     ..
27     /// }
28     /// ```
29     pub TOO_MANY_ARGUMENTS,
30     complexity,
31     "functions with too many arguments"
32 }
33
34 declare_clippy_lint! {
35     /// **What it does:** Checks for functions with a large amount of lines.
36     ///
37     /// **Why is this bad?** Functions with a lot of lines are harder to understand
38     /// due to having to look at a larger amount of code to understand what the
39     /// function is doing. Consider splitting the body of the function into
40     /// multiple functions.
41     ///
42     /// **Known problems:** None.
43     ///
44     /// **Example:**
45     /// ``` rust
46     /// fn im_too_long() {
47     /// println!("");
48     /// // ... 100 more LoC
49     /// println!("");
50     /// }
51     /// ```
52     pub TOO_MANY_LINES,
53     pedantic,
54     "functions with too many lines"
55 }
56
57 declare_clippy_lint! {
58     /// **What it does:** Checks for public functions that dereferences raw pointer
59     /// arguments but are not marked unsafe.
60     ///
61     /// **Why is this bad?** The function should probably be marked `unsafe`, since
62     /// for an arbitrary raw pointer, there is no way of telling for sure if it is
63     /// valid.
64     ///
65     /// **Known problems:**
66     ///
67     /// * It does not check functions recursively so if the pointer is passed to a
68     /// private non-`unsafe` function which does the dereferencing, the lint won't
69     /// trigger.
70     /// * It only checks for arguments whose type are raw pointers, not raw pointers
71     /// got from an argument in some other way (`fn foo(bar: &[*const u8])` or
72     /// `some_argument.get_raw_ptr()`).
73     ///
74     /// **Example:**
75     /// ```rust
76     /// pub fn foo(x: *const u8) {
77     ///     println!("{}", unsafe { *x });
78     /// }
79     /// ```
80     pub NOT_UNSAFE_PTR_ARG_DEREF,
81     correctness,
82     "public functions dereferencing raw pointer arguments but not marked `unsafe`"
83 }
84
85 #[derive(Copy, Clone)]
86 pub struct Functions {
87     threshold: u64,
88     max_lines: u64,
89 }
90
91 impl Functions {
92     pub fn new(threshold: u64, max_lines: u64) -> Self {
93         Self { threshold, max_lines }
94     }
95 }
96
97 impl LintPass for Functions {
98     fn get_lints(&self) -> LintArray {
99         lint_array!(TOO_MANY_ARGUMENTS, TOO_MANY_LINES, NOT_UNSAFE_PTR_ARG_DEREF)
100     }
101
102     fn name(&self) -> &'static str {
103         "Functions"
104     }
105 }
106
107 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions {
108     fn check_fn(
109         &mut self,
110         cx: &LateContext<'a, 'tcx>,
111         kind: intravisit::FnKind<'tcx>,
112         decl: &'tcx hir::FnDecl,
113         body: &'tcx hir::Body,
114         span: Span,
115         hir_id: hir::HirId,
116     ) {
117         let is_impl = if let Some(hir::Node::Item(item)) = cx
118             .tcx
119             .hir()
120             .find_by_hir_id(cx.tcx.hir().get_parent_node_by_hir_id(hir_id))
121         {
122             matches!(item.node, hir::ItemKind::Impl(_, _, _, _, Some(_), _, _))
123         } else {
124             false
125         };
126
127         let unsafety = match kind {
128             hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { unsafety, .. }, _, _) => unsafety,
129             hir::intravisit::FnKind::Method(_, sig, _, _) => sig.header.unsafety,
130             hir::intravisit::FnKind::Closure(_) => return,
131         };
132
133         // don't warn for implementations, it's not their fault
134         if !is_impl {
135             // don't lint extern functions decls, it's not their fault either
136             match kind {
137                 hir::intravisit::FnKind::Method(
138                     _,
139                     &hir::MethodSig {
140                         header: hir::FnHeader { abi: Abi::Rust, .. },
141                         ..
142                     },
143                     _,
144                     _,
145                 )
146                 | hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _, _) => {
147                     self.check_arg_number(cx, decl, span)
148                 },
149                 _ => {},
150             }
151         }
152
153         self.check_raw_ptr(cx, unsafety, decl, body, hir_id);
154         self.check_line_number(cx, span, body);
155     }
156
157     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
158         if let hir::TraitItemKind::Method(ref sig, ref eid) = item.node {
159             // don't lint extern functions decls, it's not their fault
160             if sig.header.abi == Abi::Rust {
161                 self.check_arg_number(cx, &sig.decl, item.span);
162             }
163
164             if let hir::TraitMethod::Provided(eid) = *eid {
165                 let body = cx.tcx.hir().body(eid);
166                 self.check_raw_ptr(cx, sig.header.unsafety, &sig.decl, body, item.hir_id);
167             }
168         }
169     }
170 }
171
172 impl<'a, 'tcx> Functions {
173     fn check_arg_number(self, cx: &LateContext<'_, '_>, decl: &hir::FnDecl, span: Span) {
174         let args = decl.inputs.len() as u64;
175         if args > self.threshold {
176             span_lint(
177                 cx,
178                 TOO_MANY_ARGUMENTS,
179                 span,
180                 &format!("this function has too many arguments ({}/{})", args, self.threshold),
181             );
182         }
183     }
184
185     fn check_line_number(self, cx: &LateContext<'_, '_>, span: Span, body: &'tcx hir::Body) {
186         if in_external_macro(cx.sess(), span) {
187             return;
188         }
189
190         let code_snippet = snippet(cx, body.value.span, "..");
191         let mut line_count: u64 = 0;
192         let mut in_comment = false;
193         let mut code_in_line;
194
195         // Skip the surrounding function decl.
196         let start_brace_idx = match code_snippet.find('{') {
197             Some(i) => i + 1,
198             None => 0,
199         };
200         let end_brace_idx = match code_snippet.find('}') {
201             Some(i) => i,
202             None => code_snippet.len(),
203         };
204         let function_lines = code_snippet[start_brace_idx..end_brace_idx].lines();
205
206         for mut line in function_lines {
207             code_in_line = false;
208             loop {
209                 line = line.trim_start();
210                 if line.is_empty() {
211                     break;
212                 }
213                 if in_comment {
214                     match line.find("*/") {
215                         Some(i) => {
216                             line = &line[i + 2..];
217                             in_comment = false;
218                             continue;
219                         },
220                         None => break,
221                     }
222                 } else {
223                     let multi_idx = match line.find("/*") {
224                         Some(i) => i,
225                         None => line.len(),
226                     };
227                     let single_idx = match line.find("//") {
228                         Some(i) => i,
229                         None => line.len(),
230                     };
231                     code_in_line |= multi_idx > 0 && single_idx > 0;
232                     // Implies multi_idx is below line.len()
233                     if multi_idx < single_idx {
234                         line = &line[multi_idx + 2..];
235                         in_comment = true;
236                         continue;
237                     }
238                     break;
239                 }
240             }
241             if code_in_line {
242                 line_count += 1;
243             }
244         }
245
246         if line_count > self.max_lines {
247             span_lint(cx, TOO_MANY_LINES, span, "This function has a large number of lines.")
248         }
249     }
250
251     fn check_raw_ptr(
252         self,
253         cx: &LateContext<'a, 'tcx>,
254         unsafety: hir::Unsafety,
255         decl: &'tcx hir::FnDecl,
256         body: &'tcx hir::Body,
257         hir_id: hir::HirId,
258     ) {
259         let expr = &body.value;
260         let node_id = cx.tcx.hir().hir_to_node_id(hir_id);
261         if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(node_id) {
262             let raw_ptrs = iter_input_pats(decl, body)
263                 .zip(decl.inputs.iter())
264                 .filter_map(|(arg, ty)| raw_ptr_arg(arg, ty))
265                 .collect::<FxHashSet<_>>();
266
267             if !raw_ptrs.is_empty() {
268                 let tables = cx.tcx.body_tables(body.id());
269                 let mut v = DerefVisitor {
270                     cx,
271                     ptrs: raw_ptrs,
272                     tables,
273                 };
274
275                 hir::intravisit::walk_expr(&mut v, expr);
276             }
277         }
278     }
279 }
280
281 fn raw_ptr_arg(arg: &hir::Arg, ty: &hir::Ty) -> Option<ast::NodeId> {
282     if let (&hir::PatKind::Binding(_, id, _, _, _), &hir::TyKind::Ptr(_)) = (&arg.pat.node, &ty.node) {
283         Some(id)
284     } else {
285         None
286     }
287 }
288
289 struct DerefVisitor<'a, 'tcx: 'a> {
290     cx: &'a LateContext<'a, 'tcx>,
291     ptrs: FxHashSet<ast::NodeId>,
292     tables: &'a ty::TypeckTables<'tcx>,
293 }
294
295 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
296     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
297         match expr.node {
298             hir::ExprKind::Call(ref f, ref args) => {
299                 let ty = self.tables.expr_ty(f);
300
301                 if type_is_unsafe_function(self.cx, ty) {
302                     for arg in args {
303                         self.check_arg(arg);
304                     }
305                 }
306             },
307             hir::ExprKind::MethodCall(_, _, ref args) => {
308                 let def_id = self.tables.type_dependent_defs()[expr.hir_id].def_id();
309                 let base_type = self.cx.tcx.type_of(def_id);
310
311                 if type_is_unsafe_function(self.cx, base_type) {
312                     for arg in args {
313                         self.check_arg(arg);
314                     }
315                 }
316             },
317             hir::ExprKind::Unary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
318             _ => (),
319         }
320
321         hir::intravisit::walk_expr(self, expr);
322     }
323     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
324         intravisit::NestedVisitorMap::None
325     }
326 }
327
328 impl<'a, 'tcx: 'a> DerefVisitor<'a, 'tcx> {
329     fn check_arg(&self, ptr: &hir::Expr) {
330         if let hir::ExprKind::Path(ref qpath) = ptr.node {
331             if let Def::Local(id) = self.cx.tables.qpath_def(qpath, ptr.hir_id) {
332                 if self.ptrs.contains(&id) {
333                     span_lint(
334                         self.cx,
335                         NOT_UNSAFE_PTR_ARG_DEREF,
336                         ptr.span,
337                         "this public function dereferences a raw pointer but is not marked `unsafe`",
338                     );
339                 }
340             }
341         }
342     }
343 }