]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/cognitive_complexity.rs
Merge remote-tracking branch 'origin/beta_backport' into HEAD
[rust.git] / clippy_lints / src / cognitive_complexity.rs
1 //! calculate cognitive complexity and warn about overly complex functions
2
3 use rustc::cfg::CFG;
4 use rustc::hir::intravisit::{walk_expr, NestedVisitorMap, Visitor};
5 use rustc::hir::*;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass};
7 use rustc::ty;
8 use rustc::{declare_tool_lint, impl_lint_pass};
9 use syntax::ast::Attribute;
10 use syntax::source_map::Span;
11
12 use crate::utils::sym;
13 use crate::utils::{in_macro_or_desugar, is_allowed, match_type, paths, span_help_and_lint, LimitStack};
14
15 declare_clippy_lint! {
16     /// **What it does:** Checks for methods with high cognitive complexity.
17     ///
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.
20     ///
21     /// **Known problems:** Sometimes it's hard to find a way to reduce the
22     /// complexity.
23     ///
24     /// **Example:** No. You'll see it when you get the warning.
25     pub COGNITIVE_COMPLEXITY,
26     complexity,
27     "functions that should be split up into multiple functions"
28 }
29
30 pub struct CognitiveComplexity {
31     limit: LimitStack,
32 }
33
34 impl CognitiveComplexity {
35     pub fn new(limit: u64) -> Self {
36         Self {
37             limit: LimitStack::new(limit),
38         }
39     }
40 }
41
42 impl_lint_pass!(CognitiveComplexity => [COGNITIVE_COMPLEXITY]);
43
44 impl CognitiveComplexity {
45     fn check<'a, 'tcx: 'a>(&mut self, cx: &'a LateContext<'a, 'tcx>, body: &'tcx Body, span: Span) {
46         if in_macro_or_desugar(span) {
47             return;
48         }
49
50         let cfg = CFG::new(cx.tcx, body);
51         let expr = &body.value;
52         let n = cfg.graph.len_nodes() as u64;
53         let e = cfg.graph.len_edges() as u64;
54         if e + 2 < n {
55             // the function has unreachable code, other lints should catch this
56             return;
57         }
58         let cc = e + 2 - n;
59         let mut helper = CCHelper {
60             match_arms: 0,
61             divergence: 0,
62             short_circuits: 0,
63             returns: 0,
64             cx,
65         };
66         helper.visit_expr(expr);
67         let CCHelper {
68             match_arms,
69             divergence,
70             short_circuits,
71             returns,
72             ..
73         } = helper;
74         let ret_ty = cx.tables.node_type(expr.hir_id);
75         let ret_adjust = if match_type(cx, ret_ty, &*paths::RESULT) {
76             returns
77         } else {
78             returns / 2
79         };
80
81         if cc + divergence < match_arms + short_circuits {
82             report_cc_bug(
83                 cx,
84                 cc,
85                 match_arms,
86                 divergence,
87                 short_circuits,
88                 ret_adjust,
89                 span,
90                 body.id().hir_id,
91             );
92         } else {
93             let mut rust_cc = cc + divergence - match_arms - short_circuits;
94             // prevent degenerate cases where unreachable code contains `return` statements
95             if rust_cc >= ret_adjust {
96                 rust_cc -= ret_adjust;
97             }
98             if rust_cc > self.limit.limit() {
99                 span_help_and_lint(
100                     cx,
101                     COGNITIVE_COMPLEXITY,
102                     span,
103                     &format!("the function has a cognitive complexity of {}", rust_cc),
104                     "you could split it up into multiple smaller functions",
105                 );
106             }
107         }
108     }
109 }
110
111 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CognitiveComplexity {
112     fn check_fn(
113         &mut self,
114         cx: &LateContext<'a, 'tcx>,
115         _: intravisit::FnKind<'tcx>,
116         _: &'tcx FnDecl,
117         body: &'tcx Body,
118         span: Span,
119         hir_id: HirId,
120     ) {
121         let def_id = cx.tcx.hir().local_def_id_from_hir_id(hir_id);
122         if !cx.tcx.has_attr(def_id, *sym::test) {
123             self.check(cx, body, span);
124         }
125     }
126
127     fn enter_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
128         self.limit.push_attrs(cx.sess(), attrs, "cognitive_complexity");
129     }
130     fn exit_lint_attrs(&mut self, cx: &LateContext<'a, 'tcx>, attrs: &'tcx [Attribute]) {
131         self.limit.pop_attrs(cx.sess(), attrs, "cognitive_complexity");
132     }
133 }
134
135 struct CCHelper<'a, 'tcx: 'a> {
136     match_arms: u64,
137     divergence: u64,
138     returns: u64,
139     short_circuits: u64, // && and ||
140     cx: &'a LateContext<'a, 'tcx>,
141 }
142
143 impl<'a, 'tcx> Visitor<'tcx> for CCHelper<'a, 'tcx> {
144     fn visit_expr(&mut self, e: &'tcx Expr) {
145         match e.node {
146             ExprKind::Match(_, ref arms, _) => {
147                 walk_expr(self, e);
148                 let arms_n: u64 = arms.iter().map(|arm| arm.pats.len() as u64).sum();
149                 if arms_n > 1 {
150                     self.match_arms += arms_n - 2;
151                 }
152             },
153             ExprKind::Call(ref callee, _) => {
154                 walk_expr(self, e);
155                 let ty = self.cx.tables.node_type(callee.hir_id);
156                 match ty.sty {
157                     ty::FnDef(..) | ty::FnPtr(_) => {
158                         let sig = ty.fn_sig(self.cx.tcx);
159                         if sig.skip_binder().output().sty == ty::Never {
160                             self.divergence += 1;
161                         }
162                     },
163                     _ => (),
164                 }
165             },
166             ExprKind::Closure(.., _) => (),
167             ExprKind::Binary(op, _, _) => {
168                 walk_expr(self, e);
169                 match op.node {
170                     BinOpKind::And | BinOpKind::Or => self.short_circuits += 1,
171                     _ => (),
172                 }
173             },
174             ExprKind::Ret(_) => self.returns += 1,
175             _ => walk_expr(self, e),
176         }
177     }
178     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
179         NestedVisitorMap::None
180     }
181 }
182
183 #[cfg(feature = "debugging")]
184 #[allow(clippy::too_many_arguments)]
185 fn report_cc_bug(
186     _: &LateContext<'_, '_>,
187     cc: u64,
188     narms: u64,
189     div: u64,
190     shorts: u64,
191     returns: u64,
192     span: Span,
193     _: HirId,
194 ) {
195     span_bug!(
196         span,
197         "Clippy encountered a bug calculating cognitive complexity: cc = {}, arms = {}, \
198          div = {}, shorts = {}, returns = {}. Please file a bug report.",
199         cc,
200         narms,
201         div,
202         shorts,
203         returns
204     );
205 }
206 #[cfg(not(feature = "debugging"))]
207 #[allow(clippy::too_many_arguments)]
208 fn report_cc_bug(
209     cx: &LateContext<'_, '_>,
210     cc: u64,
211     narms: u64,
212     div: u64,
213     shorts: u64,
214     returns: u64,
215     span: Span,
216     id: HirId,
217 ) {
218     if !is_allowed(cx, COGNITIVE_COMPLEXITY, id) {
219         cx.sess().span_note_without_error(
220             span,
221             &format!(
222                 "Clippy encountered a bug calculating cognitive complexity \
223                  (hide this message with `#[allow(cognitive_complexity)]`): \
224                  cc = {}, arms = {}, div = {}, shorts = {}, returns = {}. \
225                  Please file a bug report.",
226                 cc, narms, div, shorts, returns
227             ),
228         );
229     }
230 }