1 //! calculate cognitive complexity and warn about overly complex functions
3 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
5 use rustc::impl_lint_pass;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass};
7 use rustc_session::declare_tool_lint;
8 use syntax::ast::Attribute;
9 use syntax::source_map::Span;
11 use crate::utils::{match_type, paths, span_help_and_lint, LimitStack};
13 declare_clippy_lint! {
14 /// **What it does:** Checks for methods with high cognitive complexity.
16 /// **Why is this bad?** Methods of high cognitive complexity tend to be hard to
17 /// both read and maintain. Also LLVM will tend to optimize small methods better.
19 /// **Known problems:** Sometimes it's hard to find a way to reduce the
22 /// **Example:** No. You'll see it when you get the warning.
23 pub COGNITIVE_COMPLEXITY,
25 "functions that should be split up into multiple functions"
28 pub struct CognitiveComplexity {
32 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 expr = &body.value;
51 let mut helper = CCHelper { cc: 1, returns: 0 };
52 helper.visit_expr(expr);
53 let CCHelper { cc, returns } = helper;
54 let ret_ty = cx.tables.node_type(expr.hir_id);
55 let ret_adjust = if match_type(cx, ret_ty, &paths::RESULT) {
58 #[allow(clippy::integer_division)]
63 // prevent degenerate cases where unreachable code contains `return` statements
64 if rust_cc >= ret_adjust {
65 rust_cc -= ret_adjust;
67 if rust_cc > self.limit.limit() {
73 "the function has a cognitive complexity of ({}/{})",
77 "you could split it up into multiple smaller functions",
83 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CognitiveComplexity {
86 cx: &LateContext<'a, 'tcx>,
87 _: intravisit::FnKind<'tcx>,
93 let def_id = cx.tcx.hir().local_def_id(hir_id);
94 if !cx.tcx.has_attr(def_id, sym!(test)) {
95 self.check(cx, body, span);
99 fn enter_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
100 self.limit.push_attrs(cx.sess(), attrs, "cognitive_complexity");
102 fn exit_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
103 self.limit.pop_attrs(cx.sess(), attrs, "cognitive_complexity");
112 impl<'tcx> Visitor<'tcx> for CCHelper {
113 fn visit_expr(&mut self, e: &'tcx Expr) {
116 ExprKind::Match(_, ref arms, _) => {
120 self.cc += arms.iter().filter(|arm| arm.guard.is_some()).count() as u64;
122 ExprKind::Ret(_) => self.returns += 1,
126 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
127 NestedVisitorMap::None