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