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