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