1 //! calculate cognitive complexity and warn about overly complex functions
4 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass};
8 use rustc::{declare_tool_lint, impl_lint_pass};
9 use syntax::ast::Attribute;
10 use syntax::source_map::Span;
12 use crate::utils::{is_allowed, match_type, paths, span_help_and_lint, LimitStack};
14 declare_clippy_lint! {
15 /// **What it does:** Checks for methods with high cognitive complexity.
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.
20 /// **Known problems:** Sometimes it's hard to find a way to reduce the
23 /// **Example:** No. You'll see it when you get the warning.
24 pub COGNITIVE_COMPLEXITY,
26 "functions that should be split up into multiple functions"
29 pub struct CognitiveComplexity {
33 impl CognitiveComplexity {
34 pub fn new(limit: u64) -> Self {
36 limit: LimitStack::new(limit),
41 impl_lint_pass!(CognitiveComplexity => [COGNITIVE_COMPLEXITY]);
43 impl CognitiveComplexity {
44 fn check<'a, 'tcx>(&mut self, cx: &'a LateContext<'a, 'tcx>, body: &'tcx Body, span: Span) {
45 if span.from_expansion() {
49 let cfg = CFG::new(cx.tcx, body);
50 let expr = &body.value;
51 let n = cfg.graph.len_nodes() as u64;
52 let e = cfg.graph.len_edges() as u64;
54 // the function has unreachable code, other lints should catch this
58 let mut helper = CCHelper {
65 helper.visit_expr(expr);
73 let ret_ty = cx.tables.node_type(expr.hir_id);
74 let ret_adjust = if match_type(cx, ret_ty, &paths::RESULT) {
77 #[allow(clippy::integer_division)]
81 if cc + divergence < match_arms + short_circuits {
93 let mut rust_cc = cc + divergence - match_arms - short_circuits;
94 // prevent degenerate cases where unreachable code contains `return` statements
95 if rust_cc >= ret_adjust {
96 rust_cc -= ret_adjust;
98 if rust_cc > self.limit.limit() {
101 COGNITIVE_COMPLEXITY,
104 "the function has a cognitive complexity of ({}/{})",
108 "you could split it up into multiple smaller functions",
115 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CognitiveComplexity {
118 cx: &LateContext<'a, 'tcx>,
119 _: intravisit::FnKind<'tcx>,
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, body, span);
131 fn enter_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
132 self.limit.push_attrs(cx.sess(), attrs, "cognitive_complexity");
134 fn exit_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
135 self.limit.pop_attrs(cx.sess(), attrs, "cognitive_complexity");
139 struct CCHelper<'a, 'tcx> {
143 short_circuits: u64, // && and ||
144 cx: &'a LateContext<'a, 'tcx>,
147 impl<'a, 'tcx> Visitor<'tcx> for CCHelper<'a, 'tcx> {
148 fn visit_expr(&mut self, e: &'tcx Expr) {
150 ExprKind::Match(_, ref arms, _) => {
152 let arms_n: u64 = arms.iter().map(|arm| arm.pats.len() as u64).sum();
154 self.match_arms += arms_n - 2;
157 ExprKind::Call(ref callee, _) => {
159 let ty = self.cx.tables.node_type(callee.hir_id);
161 ty::FnDef(..) | ty::FnPtr(_) => {
162 let sig = ty.fn_sig(self.cx.tcx);
163 if sig.skip_binder().output().sty == ty::Never {
164 self.divergence += 1;
170 ExprKind::Closure(.., _) => (),
171 ExprKind::Binary(op, _, _) => {
174 BinOpKind::And | BinOpKind::Or => self.short_circuits += 1,
178 ExprKind::Ret(_) => self.returns += 1,
179 _ => walk_expr(self, e),
182 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
183 NestedVisitorMap::None
187 #[cfg(feature = "debugging")]
188 #[allow(clippy::too_many_arguments)]
190 _: &LateContext<'_, '_>,
201 "Clippy encountered a bug calculating cognitive complexity: cc = {}, arms = {}, \
202 div = {}, shorts = {}, returns = {}. Please file a bug report.",
210 #[cfg(not(feature = "debugging"))]
211 #[allow(clippy::too_many_arguments)]
213 cx: &LateContext<'_, '_>,
222 if !is_allowed(cx, COGNITIVE_COMPLEXITY, id) {
223 cx.sess().span_note_without_error(
226 "Clippy encountered a bug calculating cognitive complexity \
227 (hide this message with `#[allow(cognitive_complexity)]`): \
228 cc = {}, arms = {}, div = {}, shorts = {}, returns = {}. \
229 Please file a bug report.",
230 cc, narms, div, shorts, returns