]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/functions.rs
Fix question_mark.rs
[rust.git] / clippy_lints / src / functions.rs
1 use std::convert::TryFrom;
2
3 use crate::utils::{iter_input_pats, snippet, snippet_opt, span_lint, type_is_unsafe_function};
4 use matches::matches;
5 use rustc::hir;
6 use rustc::hir::def::Res;
7 use rustc::hir::intravisit;
8 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
9 use rustc::ty;
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};
14
15 declare_clippy_lint! {
16     /// **What it does:** Checks for functions with too many parameters.
17     ///
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.
21     ///
22     /// **Known problems:** None.
23     ///
24     /// **Example:**
25     /// ```rust
26     /// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) {
27     ///     ..
28     /// }
29     /// ```
30     pub TOO_MANY_ARGUMENTS,
31     complexity,
32     "functions with too many arguments"
33 }
34
35 declare_clippy_lint! {
36     /// **What it does:** Checks for functions with a large amount of lines.
37     ///
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.
42     ///
43     /// **Known problems:** None.
44     ///
45     /// **Example:**
46     /// ``` rust
47     /// fn im_too_long() {
48     /// println!("");
49     /// // ... 100 more LoC
50     /// println!("");
51     /// }
52     /// ```
53     pub TOO_MANY_LINES,
54     pedantic,
55     "functions with too many lines"
56 }
57
58 declare_clippy_lint! {
59     /// **What it does:** Checks for public functions that dereferences raw pointer
60     /// arguments but are not marked unsafe.
61     ///
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
64     /// valid.
65     ///
66     /// **Known problems:**
67     ///
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
70     /// trigger.
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()`).
74     ///
75     /// **Example:**
76     /// ```rust
77     /// pub fn foo(x: *const u8) {
78     ///     println!("{}", unsafe { *x });
79     /// }
80     /// ```
81     pub NOT_UNSAFE_PTR_ARG_DEREF,
82     correctness,
83     "public functions dereferencing raw pointer arguments but not marked `unsafe`"
84 }
85
86 #[derive(Copy, Clone)]
87 pub struct Functions {
88     threshold: u64,
89     max_lines: u64,
90 }
91
92 impl Functions {
93     pub fn new(threshold: u64, max_lines: u64) -> Self {
94         Self { threshold, max_lines }
95     }
96 }
97
98 impl_lint_pass!(Functions => [TOO_MANY_ARGUMENTS, TOO_MANY_LINES, NOT_UNSAFE_PTR_ARG_DEREF]);
99
100 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions {
101     fn check_fn(
102         &mut self,
103         cx: &LateContext<'a, 'tcx>,
104         kind: intravisit::FnKind<'tcx>,
105         decl: &'tcx hir::FnDecl,
106         body: &'tcx hir::Body,
107         span: Span,
108         hir_id: hir::HirId,
109     ) {
110         let is_impl = if let Some(hir::Node::Item(item)) = cx
111             .tcx
112             .hir()
113             .find_by_hir_id(cx.tcx.hir().get_parent_node_by_hir_id(hir_id))
114         {
115             matches!(item.node, hir::ItemKind::Impl(_, _, _, _, Some(_), _, _))
116         } else {
117             false
118         };
119
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,
124         };
125
126         // don't warn for implementations, it's not their fault
127         if !is_impl {
128             // don't lint extern functions decls, it's not their fault either
129             match kind {
130                 hir::intravisit::FnKind::Method(
131                     _,
132                     &hir::MethodSig {
133                         header: hir::FnHeader { abi: Abi::Rust, .. },
134                         ..
135                     },
136                     _,
137                     _,
138                 )
139                 | hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _, _) => {
140                     self.check_arg_number(cx, decl, span)
141                 },
142                 _ => {},
143             }
144         }
145
146         self.check_raw_ptr(cx, unsafety, decl, body, hir_id);
147         self.check_line_number(cx, span, body);
148     }
149
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);
155             }
156
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);
160             }
161         }
162     }
163 }
164
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() {
172                 span
173             } else {
174                 span.with_hi(BytePos(span.lo().0 + u32::try_from(snippet.len()).unwrap()))
175             }
176         } else {
177             span
178         };
179
180         let args = decl.inputs.len() as u64;
181         if args > self.threshold {
182             span_lint(
183                 cx,
184                 TOO_MANY_ARGUMENTS,
185                 span,
186                 &format!("this function has too many arguments ({}/{})", args, self.threshold),
187             );
188         }
189     }
190
191     fn check_line_number(self, cx: &LateContext<'_, '_>, span: Span, body: &'tcx hir::Body) {
192         if in_external_macro(cx.sess(), span) {
193             return;
194         }
195
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;
200
201         // Skip the surrounding function decl.
202         let start_brace_idx = match code_snippet.find('{') {
203             Some(i) => i + 1,
204             None => 0,
205         };
206         let end_brace_idx = match code_snippet.find('}') {
207             Some(i) => i,
208             None => code_snippet.len(),
209         };
210         let function_lines = code_snippet[start_brace_idx..end_brace_idx].lines();
211
212         for mut line in function_lines {
213             code_in_line = false;
214             loop {
215                 line = line.trim_start();
216                 if line.is_empty() {
217                     break;
218                 }
219                 if in_comment {
220                     match line.find("*/") {
221                         Some(i) => {
222                             line = &line[i + 2..];
223                             in_comment = false;
224                             continue;
225                         },
226                         None => break,
227                     }
228                 } else {
229                     let multi_idx = match line.find("/*") {
230                         Some(i) => i,
231                         None => line.len(),
232                     };
233                     let single_idx = match line.find("//") {
234                         Some(i) => i,
235                         None => line.len(),
236                     };
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..];
241                         in_comment = true;
242                         continue;
243                     }
244                     break;
245                 }
246             }
247             if code_in_line {
248                 line_count += 1;
249             }
250         }
251
252         if line_count > self.max_lines {
253             span_lint(cx, TOO_MANY_LINES, span, "This function has a large number of lines.")
254         }
255     }
256
257     fn check_raw_ptr(
258         self,
259         cx: &LateContext<'a, 'tcx>,
260         unsafety: hir::Unsafety,
261         decl: &'tcx hir::FnDecl,
262         body: &'tcx hir::Body,
263         hir_id: hir::HirId,
264     ) {
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<_>>();
271
272             if !raw_ptrs.is_empty() {
273                 let tables = cx.tcx.body_tables(body.id());
274                 let mut v = DerefVisitor {
275                     cx,
276                     ptrs: raw_ptrs,
277                     tables,
278                 };
279
280                 hir::intravisit::walk_expr(&mut v, expr);
281             }
282         }
283     }
284 }
285
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) {
288         Some(id)
289     } else {
290         None
291     }
292 }
293
294 struct DerefVisitor<'a, 'tcx: 'a> {
295     cx: &'a LateContext<'a, 'tcx>,
296     ptrs: FxHashSet<hir::HirId>,
297     tables: &'a ty::TypeckTables<'tcx>,
298 }
299
300 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
301     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
302         match expr.node {
303             hir::ExprKind::Call(ref f, ref args) => {
304                 let ty = self.tables.expr_ty(f);
305
306                 if type_is_unsafe_function(self.cx, ty) {
307                     for arg in args {
308                         self.check_arg(arg);
309                     }
310                 }
311             },
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);
315
316                 if type_is_unsafe_function(self.cx, base_type) {
317                     for arg in args {
318                         self.check_arg(arg);
319                     }
320                 }
321             },
322             hir::ExprKind::Unary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
323             _ => (),
324         }
325
326         hir::intravisit::walk_expr(self, expr);
327     }
328     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
329         intravisit::NestedVisitorMap::None
330     }
331 }
332
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) {
338                     span_lint(
339                         self.cx,
340                         NOT_UNSAFE_PTR_ARG_DEREF,
341                         ptr.span,
342                         "this public function dereferences a raw pointer but is not marked `unsafe`",
343                     );
344                 }
345             }
346         }
347     }
348 }