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, lint_array};
9 use syntax::ast::Attribute;
10 use syntax::source_map::Span;
12 use crate::utils::{in_macro, 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 LintPass for CognitiveComplexity {
42 fn get_lints(&self) -> LintArray {
43 lint_array!(COGNITIVE_COMPLEXITY)
46 fn name(&self) -> &'static str {
51 impl CognitiveComplexity {
52 fn check<'a, 'tcx: 'a>(&mut self, cx: &'a LateContext<'a, 'tcx>, body: &'tcx Body, span: Span) {
57 let cfg = CFG::new(cx.tcx, body);
58 let expr = &body.value;
59 let n = cfg.graph.len_nodes() as u64;
60 let e = cfg.graph.len_edges() as u64;
62 // the function has unreachable code, other lints should catch this
66 let mut helper = CCHelper {
73 helper.visit_expr(expr);
81 let ret_ty = cx.tables.node_type(expr.hir_id);
82 let ret_adjust = if match_type(cx, ret_ty, &paths::RESULT) {
88 if cc + divergence < match_arms + short_circuits {
100 let mut rust_cc = cc + divergence - match_arms - short_circuits;
101 // prevent degenerate cases where unreachable code contains `return` statements
102 if rust_cc >= ret_adjust {
103 rust_cc -= ret_adjust;
105 if rust_cc > self.limit.limit() {
108 COGNITIVE_COMPLEXITY,
110 &format!("the function has a cognitive complexity of {}", rust_cc),
111 "you could split it up into multiple smaller functions",
118 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CognitiveComplexity {
121 cx: &LateContext<'a, 'tcx>,
122 _: intravisit::FnKind<'tcx>,
128 let def_id = cx.tcx.hir().local_def_id_from_hir_id(hir_id);
129 if !cx.tcx.has_attr(def_id, "test") {
130 self.check(cx, body, span);
134 fn enter_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
135 self.limit.push_attrs(cx.sess(), attrs, "cognitive_complexity");
137 fn exit_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
138 self.limit.pop_attrs(cx.sess(), attrs, "cognitive_complexity");
142 struct CCHelper<'a, 'tcx: 'a> {
146 short_circuits: u64, // && and ||
147 cx: &'a LateContext<'a, 'tcx>,
150 impl<'a, 'tcx> Visitor<'tcx> for CCHelper<'a, 'tcx> {
151 fn visit_expr(&mut self, e: &'tcx Expr) {
153 ExprKind::Match(_, ref arms, _) => {
155 let arms_n: u64 = arms.iter().map(|arm| arm.pats.len() as u64).sum();
157 self.match_arms += arms_n - 2;
160 ExprKind::Call(ref callee, _) => {
162 let ty = self.cx.tables.node_type(callee.hir_id);
164 ty::FnDef(..) | ty::FnPtr(_) => {
165 let sig = ty.fn_sig(self.cx.tcx);
166 if sig.skip_binder().output().sty == ty::Never {
167 self.divergence += 1;
173 ExprKind::Closure(.., _) => (),
174 ExprKind::Binary(op, _, _) => {
177 BinOpKind::And | BinOpKind::Or => self.short_circuits += 1,
181 ExprKind::Ret(_) => self.returns += 1,
182 _ => walk_expr(self, e),
185 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
186 NestedVisitorMap::None
190 #[cfg(feature = "debugging")]
191 #[allow(clippy::too_many_arguments)]
193 _: &LateContext<'_, '_>,
204 "Clippy encountered a bug calculating cognitive complexity: cc = {}, arms = {}, \
205 div = {}, shorts = {}, returns = {}. Please file a bug report.",
213 #[cfg(not(feature = "debugging"))]
214 #[allow(clippy::too_many_arguments)]
216 cx: &LateContext<'_, '_>,
225 if !is_allowed(cx, COGNITIVE_COMPLEXITY, id) {
226 cx.sess().span_note_without_error(
229 "Clippy encountered a bug calculating cognitive complexity \
230 (hide this message with `#[allow(cognitive_complexity)]`): \
231 cc = {}, arms = {}, div = {}, shorts = {}, returns = {}. \
232 Please file a bug report.",
233 cc, narms, div, shorts, returns