]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/cognitive_complexity.rs
non_copy_const: remove incorrect suggestion
[rust.git] / clippy_lints / src / cognitive_complexity.rs
1 //! calculate cognitive complexity and warn about overly complex functions
2
3 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
4 use rustc::hir::*;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass};
6 use rustc::{declare_tool_lint, impl_lint_pass};
7 use syntax::ast::Attribute;
8 use syntax::source_map::Span;
9
10 use crate::utils::{match_type, paths, span_help_and_lint, LimitStack};
11
12 declare_clippy_lint! {
13     /// **What it does:** Checks for methods with high cognitive complexity.
14     ///
15     /// **Why is this bad?** Methods of high cognitive complexity tend to be hard to
16     /// both read and maintain. Also LLVM will tend to optimize small methods better.
17     ///
18     /// **Known problems:** Sometimes it's hard to find a way to reduce the
19     /// complexity.
20     ///
21     /// **Example:** No. You'll see it when you get the warning.
22     pub COGNITIVE_COMPLEXITY,
23     complexity,
24     "functions that should be split up into multiple functions"
25 }
26
27 pub struct CognitiveComplexity {
28     limit: LimitStack,
29 }
30
31 impl CognitiveComplexity {
32     pub fn new(limit: u64) -> Self {
33         Self {
34             limit: LimitStack::new(limit),
35         }
36     }
37 }
38
39 impl_lint_pass!(CognitiveComplexity => [COGNITIVE_COMPLEXITY]);
40
41 impl CognitiveComplexity {
42     fn check<'a, 'tcx>(&mut self, cx: &'a LateContext<'a, 'tcx>, body: &'tcx Body, span: Span) {
43         if span.from_expansion() {
44             return;
45         }
46
47         let expr = &body.value;
48
49         let mut helper = CCHelper { cc: 1, returns: 0 };
50         helper.visit_expr(expr);
51         let CCHelper { cc, returns } = helper;
52         let ret_ty = cx.tables.node_type(expr.hir_id);
53         let ret_adjust = if match_type(cx, ret_ty, &paths::RESULT) {
54             returns
55         } else {
56             #[allow(clippy::integer_division)]
57             (returns / 2)
58         };
59
60         let mut rust_cc = cc;
61         // prevent degenerate cases where unreachable code contains `return` statements
62         if rust_cc >= ret_adjust {
63             rust_cc -= ret_adjust;
64         }
65         if rust_cc > self.limit.limit() {
66             span_help_and_lint(
67                 cx,
68                 COGNITIVE_COMPLEXITY,
69                 span,
70                 &format!(
71                     "the function has a cognitive complexity of ({}/{})",
72                     rust_cc,
73                     self.limit.limit()
74                 ),
75                 "you could split it up into multiple smaller functions",
76             );
77         }
78     }
79 }
80
81 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CognitiveComplexity {
82     fn check_fn(
83         &mut self,
84         cx: &LateContext<'a, 'tcx>,
85         _: intravisit::FnKind<'tcx>,
86         _: &'tcx FnDecl,
87         body: &'tcx Body,
88         span: Span,
89         hir_id: HirId,
90     ) {
91         let def_id = cx.tcx.hir().local_def_id(hir_id);
92         if !cx.tcx.has_attr(def_id, sym!(test)) {
93             self.check(cx, body, span);
94         }
95     }
96
97     fn enter_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
98         self.limit.push_attrs(cx.sess(), attrs, "cognitive_complexity");
99     }
100     fn exit_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
101         self.limit.pop_attrs(cx.sess(), attrs, "cognitive_complexity");
102     }
103 }
104
105 struct CCHelper {
106     cc: u64,
107     returns: u64,
108 }
109
110 impl<'tcx> Visitor<'tcx> for CCHelper {
111     fn visit_expr(&mut self, e: &'tcx Expr) {
112         walk_expr(self, e);
113         match e.node {
114             ExprKind::Match(_, ref arms, _) => {
115                 if arms.len() > 1 {
116                     self.cc += 1;
117                 }
118                 self.cc += arms.iter().filter(|arm| arm.guard.is_some()).count() as u64;
119             },
120             ExprKind::Ret(_) => self.returns += 1,
121             _ => {},
122         }
123     }
124     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
125         NestedVisitorMap::None
126     }
127 }