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