1 //! calculate cognitive complexity and warn about overly complex functions
3 use rustc::hir::map::Map;
4 use rustc::impl_lint_pass;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass};
6 use rustc_hir::intravisit::{walk_expr, FnKind, NestedVisitorMap, Visitor};
8 use rustc_session::declare_tool_lint;
9 use rustc_span::source_map::Span;
10 use rustc_span::BytePos;
11 use syntax::ast::Attribute;
13 use crate::utils::{match_type, paths, snippet_opt, span_help_and_lint, LimitStack};
15 declare_clippy_lint! {
16 /// **What it does:** Checks for methods with high cognitive complexity.
18 /// **Why is this bad?** Methods of high cognitive complexity tend to be hard to
19 /// both read and maintain. Also LLVM will tend to optimize small methods better.
21 /// **Known problems:** Sometimes it's hard to find a way to reduce the
24 /// **Example:** No. You'll see it when you get the warning.
25 pub COGNITIVE_COMPLEXITY,
27 "functions that should be split up into multiple functions"
30 pub struct CognitiveComplexity {
34 impl CognitiveComplexity {
36 pub fn new(limit: u64) -> Self {
38 limit: LimitStack::new(limit),
43 impl_lint_pass!(CognitiveComplexity => [COGNITIVE_COMPLEXITY]);
45 impl CognitiveComplexity {
46 #[allow(clippy::cast_possible_truncation)]
49 cx: &'a LateContext<'a, 'tcx>,
51 decl: &'tcx FnDecl<'_>,
55 if body_span.from_expansion() {
59 let expr = &body.value;
61 let mut helper = CCHelper { cc: 1, returns: 0 };
62 helper.visit_expr(expr);
63 let CCHelper { cc, returns } = helper;
64 let ret_ty = cx.tables.node_type(expr.hir_id);
65 let ret_adjust = if match_type(cx, ret_ty, &paths::RESULT) {
68 #[allow(clippy::integer_division)]
73 // prevent degenerate cases where unreachable code contains `return` statements
74 if rust_cc >= ret_adjust {
75 rust_cc -= ret_adjust;
78 if rust_cc > self.limit.limit() {
79 let fn_span = match kind {
80 FnKind::ItemFn(ident, _, _, _, _) | FnKind::Method(ident, _, _, _) => ident.span,
81 FnKind::Closure(_) => {
82 let header_span = body_span.with_hi(decl.output.span().lo());
83 let pos = snippet_opt(cx, header_span).and_then(|snip| {
84 let low_offset = snip.find('|')?;
85 let high_offset = 1 + snip.get(low_offset + 1..)?.find('|')?;
86 let low = header_span.lo() + BytePos(low_offset as u32);
87 let high = low + BytePos(high_offset as u32 + 1);
92 if let Some((low, high)) = pos {
93 Span::new(low, high, header_span.ctxt())
102 COGNITIVE_COMPLEXITY,
105 "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