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