1 //! calculate cognitive complexity and warn about overly complex functions
3 use rustc_ast::ast::Attribute;
4 use rustc_hir::intravisit::{walk_expr, FnKind, NestedVisitorMap, Visitor};
5 use rustc_hir::{Body, Expr, ExprKind, FnDecl, HirId};
6 use rustc_lint::{LateContext, LateLintPass, LintContext};
7 use rustc_middle::hir::map::Map;
8 use rustc_session::{declare_tool_lint, impl_lint_pass};
9 use rustc_span::source_map::Span;
10 use rustc_span::BytePos;
12 use crate::utils::{is_type_diagnostic_item, snippet_opt, span_lint_and_help, 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 {
35 pub fn new(limit: u64) -> Self {
37 limit: LimitStack::new(limit),
42 impl_lint_pass!(CognitiveComplexity => [COGNITIVE_COMPLEXITY]);
44 impl CognitiveComplexity {
45 #[allow(clippy::cast_possible_truncation)]
48 cx: &'a LateContext<'a, 'tcx>,
50 decl: &'tcx FnDecl<'_>,
54 if body_span.from_expansion() {
58 let expr = &body.value;
60 let mut helper = CCHelper { cc: 1, returns: 0 };
61 helper.visit_expr(expr);
62 let CCHelper { cc, returns } = helper;
63 let ret_ty = cx.tables.node_type(expr.hir_id);
64 let ret_adjust = if is_type_diagnostic_item(cx, ret_ty, sym!(result_type)) {
67 #[allow(clippy::integer_division)]
72 // prevent degenerate cases where unreachable code contains `return` statements
73 if rust_cc >= ret_adjust {
74 rust_cc -= ret_adjust;
77 if rust_cc > self.limit.limit() {
78 let fn_span = match kind {
79 FnKind::ItemFn(ident, _, _, _, _) | FnKind::Method(ident, _, _, _) => ident.span,
80 FnKind::Closure(_) => {
81 let header_span = body_span.with_hi(decl.output.span().lo());
82 let pos = snippet_opt(cx, header_span).and_then(|snip| {
83 let low_offset = snip.find('|')?;
84 let high_offset = 1 + snip.get(low_offset + 1..)?.find('|')?;
85 let low = header_span.lo() + BytePos(low_offset as u32);
86 let high = low + BytePos(high_offset as u32 + 1);
91 if let Some((low, high)) = pos {
92 Span::new(low, high, header_span.ctxt())
101 COGNITIVE_COMPLEXITY,
104 "the function has a cognitive complexity of ({}/{})",
109 "you could split it up into multiple smaller functions",
115 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CognitiveComplexity {
118 cx: &LateContext<'a, 'tcx>,
120 decl: &'tcx FnDecl<'_>,
121 body: &'tcx Body<'_>,
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, kind, decl, 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");
144 impl<'tcx> Visitor<'tcx> for CCHelper {
145 type Map = Map<'tcx>;
147 fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
150 ExprKind::Match(_, ref arms, _) => {
154 self.cc += arms.iter().filter(|arm| arm.guard.is_some()).count() as u64;
156 ExprKind::Ret(_) => self.returns += 1,
160 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
161 NestedVisitorMap::None