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