1 //! calculate cognitive complexity and warn about overly complex functions
3 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass};
6 use rustc::{declare_tool_lint, impl_lint_pass};
7 use syntax::ast::Attribute;
8 use syntax::source_map::Span;
10 use crate::utils::{match_type, paths, span_help_and_lint, LimitStack};
12 declare_clippy_lint! {
13 /// **What it does:** Checks for methods with high cognitive complexity.
15 /// **Why is this bad?** Methods of high cognitive complexity tend to be hard to
16 /// both read and maintain. Also LLVM will tend to optimize small methods better.
18 /// **Known problems:** Sometimes it's hard to find a way to reduce the
21 /// **Example:** No. You'll see it when you get the warning.
22 pub COGNITIVE_COMPLEXITY,
24 "functions that should be split up into multiple functions"
27 pub struct CognitiveComplexity {
31 impl CognitiveComplexity {
32 pub fn new(limit: u64) -> Self {
34 limit: LimitStack::new(limit),
39 impl_lint_pass!(CognitiveComplexity => [COGNITIVE_COMPLEXITY]);
41 impl CognitiveComplexity {
42 fn check<'a, 'tcx>(&mut self, cx: &'a LateContext<'a, 'tcx>, body: &'tcx Body, span: Span) {
43 if span.from_expansion() {
47 let expr = &body.value;
49 let mut helper = CCHelper { cc: 1, returns: 0 };
50 helper.visit_expr(expr);
51 let CCHelper { cc, returns } = helper;
52 let ret_ty = cx.tables.node_type(expr.hir_id);
53 let ret_adjust = if match_type(cx, ret_ty, &paths::RESULT) {
56 #[allow(clippy::integer_division)]
61 // prevent degenerate cases where unreachable code contains `return` statements
62 if rust_cc >= ret_adjust {
63 rust_cc -= ret_adjust;
65 if rust_cc > self.limit.limit() {
71 "the function has a cognitive complexity of ({}/{})",
75 "you could split it up into multiple smaller functions",
81 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CognitiveComplexity {
84 cx: &LateContext<'a, 'tcx>,
85 _: intravisit::FnKind<'tcx>,
91 let def_id = cx.tcx.hir().local_def_id(hir_id);
92 if !cx.tcx.has_attr(def_id, sym!(test)) {
93 self.check(cx, body, span);
97 fn enter_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
98 self.limit.push_attrs(cx.sess(), attrs, "cognitive_complexity");
100 fn exit_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
101 self.limit.pop_attrs(cx.sess(), attrs, "cognitive_complexity");
110 impl<'tcx> Visitor<'tcx> for CCHelper {
111 fn visit_expr(&mut self, e: &'tcx Expr) {
114 ExprKind::Match(_, ref arms, _) => {
118 self.cc += arms.iter().filter(|arm| arm.guard.is_some()).count() as u64;
120 ExprKind::Ret(_) => self.returns += 1,
124 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
125 NestedVisitorMap::None