1 //! calculate cyclomatic complexity and warn about overly complex functions
4 use rustc_front::hir::*;
5 use rustc::middle::cfg::CFG;
7 use syntax::codemap::Span;
9 use syntax::ast::Attribute;
10 use rustc_front::intravisit::{Visitor, walk_expr};
12 use utils::{in_macro, LimitStack};
14 /// **What it does:** It `Warn`s on methods with high cyclomatic complexity
16 /// **Why is this bad?** Methods of high cyclomatic complexity tend to be badly readable. Also LLVM will usually optimize small methods better.
18 /// **Known problems:** Sometimes it's hard to find a way to reduce the complexity
20 /// **Example:** No. You'll see it when you get the warning.
21 declare_lint! { pub CYCLOMATIC_COMPLEXITY, Warn,
22 "finds functions that should be split up into multiple functions" }
24 pub struct CyclomaticComplexity {
28 impl CyclomaticComplexity {
29 pub fn new(limit: u64) -> Self {
30 CyclomaticComplexity {
31 limit: LimitStack::new(limit),
36 impl LintPass for CyclomaticComplexity {
37 fn get_lints(&self) -> LintArray {
38 lint_array!(CYCLOMATIC_COMPLEXITY)
42 impl CyclomaticComplexity {
43 fn check<'a, 'tcx>(&mut self, cx: &'a LateContext<'a, 'tcx>, block: &Block, span: Span) {
44 if in_macro(cx, span) { return; }
45 let cfg = CFG::new(cx.tcx, block);
46 let n = cfg.graph.len_nodes() as u64;
47 let e = cfg.graph.len_edges() as u64;
49 let mut arm_counter = MatchArmCounter(0);
50 arm_counter.visit_block(block);
51 let narms = arm_counter.0;
53 let mut diverge_counter = DivergenceCounter(0, &cx.tcx);
54 diverge_counter.visit_block(block);
55 let divergence = diverge_counter.0;
57 if cc + divergence < narms {
58 report_cc_bug(cx, cc, narms, divergence, span);
60 let rust_cc = cc + divergence - narms;
61 if rust_cc > self.limit.limit() {
62 cx.span_lint_help(CYCLOMATIC_COMPLEXITY, span,
63 &format!("The function has a cyclomatic complexity of {}.", rust_cc),
64 "You could split it up into multiple smaller functions");
70 impl LateLintPass for CyclomaticComplexity {
71 fn check_item(&mut self, cx: &LateContext, item: &Item) {
72 if let ItemFn(_, _, _, _, _, ref block) = item.node {
73 self.check(cx, block, item.span);
77 fn check_impl_item(&mut self, cx: &LateContext, item: &ImplItem) {
78 if let ImplItemKind::Method(_, ref block) = item.node {
79 self.check(cx, block, item.span);
83 fn check_trait_item(&mut self, cx: &LateContext, item: &TraitItem) {
84 if let MethodTraitItem(_, Some(ref block)) = item.node {
85 self.check(cx, block, item.span);
89 fn enter_lint_attrs(&mut self, cx: &LateContext, attrs: &[Attribute]) {
90 self.limit.push_attrs(cx.sess(), attrs, "cyclomatic_complexity");
92 fn exit_lint_attrs(&mut self, cx: &LateContext, attrs: &[Attribute]) {
93 self.limit.pop_attrs(cx.sess(), attrs, "cyclomatic_complexity");
97 struct MatchArmCounter(u64);
99 impl<'a> Visitor<'a> for MatchArmCounter {
100 fn visit_expr(&mut self, e: &'a Expr) {
102 ExprMatch(_, ref arms, _) => {
104 let arms_n: u64 = arms.iter().map(|arm| arm.pats.len() as u64).sum();
106 self.0 += arms_n - 2;
109 ExprClosure(..) => {},
110 _ => walk_expr(self, e),
115 struct DivergenceCounter<'a, 'tcx: 'a>(u64, &'a ty::ctxt<'tcx>);
117 impl<'a, 'b, 'tcx> Visitor<'a> for DivergenceCounter<'b, 'tcx> {
118 fn visit_expr(&mut self, e: &'a Expr) {
120 ExprCall(ref callee, _) => {
122 let ty = self.1.node_id_to_type(callee.id);
123 if let ty::TyBareFn(_, ty) = ty.sty {
124 if ty.sig.skip_binder().output.diverges() {
129 ExprClosure(..) => {},
130 _ => walk_expr(self, e),
135 #[cfg(feature="debugging")]
136 fn report_cc_bug(cx: &LateContext, cc: u64, narms: u64, div: u64, span: Span) {
137 cx.sess().span_bug(span, &format!("Clippy encountered a bug calculating cyclomatic complexity: \
138 cc = {}, arms = {}, div = {}. Please file a bug report.", cc, narms, div));;
140 #[cfg(not(feature="debugging"))]
141 fn report_cc_bug(cx: &LateContext, cc: u64, narms: u64, div: u64, span: Span) {
142 if cx.current_level(CYCLOMATIC_COMPLEXITY) != Level::Allow {
143 cx.sess().span_note(span, &format!("Clippy encountered a bug calculating cyclomatic complexity \
144 (hide this message with `#[allow(cyclomatic_complexity)]`): \
145 cc = {}, arms = {}, div = {}. Please file a bug report.", cc, narms, div));