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