This repository has been archived by the owner on Nov 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 93
/
AvoidComplexMethodsRule.cs
334 lines (300 loc) · 11.3 KB
/
AvoidComplexMethodsRule.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
//
// Gendarme.Rules.Maintainability.AvoidComplexMethodsRule class
//
// Authors:
// Cedric Vivier <[email protected]>
// Sebastien Pouliot <[email protected]>
//
// (C) 2008 Cedric Vivier
// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Gendarme.Framework;
using Gendarme.Framework.Engines;
using Gendarme.Framework.Helpers;
using Gendarme.Framework.Rocks;
namespace Gendarme.Rules.Maintainability {
/// <summary>
/// This rule computes the cyclomatic complexity (CC) for every method and reports any method
/// with a CC over 25 (this limit is configurable). Large CC value often indicate complex
/// code that is hard to understand and maintain. It's likely that breaking the
/// method into several methods will help readability. This rule won't report any defects
/// on code generated by the compiler or by tools.
/// </summary>
/// <remarks>This rule is available since Gendarme 2.0</remarks>
[Problem ("Methods with a large cyclomatic complexity are hard to understand and maintain.")]
[Solution ("Simplify the method using refactors like Extract Method.")]
[FxCopCompatibility ("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[EngineDependency (typeof (OpCodeEngine))]
public class AvoidComplexMethodsRule : Rule, IMethodRule {
// defaults match fxcop rule http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1575061&SiteID=1
// so people using both tools should not see conflicting results
private const int DefaultSuccessThreshold = 25;
static OpCodeBitmask ld = new OpCodeBitmask (0xFFFF6C3FC, 0x1B0300000000FFE0, 0x400100FFF800, 0xDE0);
public AvoidComplexMethodsRule ()
{
SuccessThreshold = DefaultSuccessThreshold;
}
public override void Initialize (IRunner runner)
{
base.Initialize (runner);
// works if only SuccessThreshold is configured in rules.xml
if (LowThreshold == 0)
LowThreshold = SuccessThreshold * 2;
if (MediumThreshold == 0)
MediumThreshold = SuccessThreshold * 3;
if (HighThreshold == 0)
HighThreshold = SuccessThreshold * 4;
}
/// <summary>The cyclomatic complexity at which defects begin to be reported.</summary>
/// <remarks>This defaults to 25 and larger values will mean fewer reported defects.</remarks>
[DefaultValue (DefaultSuccessThreshold)]
[Description ("The cyclomatic complexity at which defects are reported.")]
public int SuccessThreshold { get; set; }
/// <summary>Methods with cyclomatic complexity less than this will be reported as low severity.</summary>
/// <remarks>If left as zero then the rule will initialize it to 2*SuccessThreshold.</remarks>
[DefaultValue (0)]
[Description ("Methods with cyclomatic complexity less than this will be reported as low severity.")]
public int LowThreshold { get; set; }
/// <summary>Methods with cyclomatic complexity less than this (but higher than LowThreshold) will be reported as medium severity.</summary>
/// <remarks>If left as zero then the rule will initialize it to 3*SuccessThreshold.</remarks>
[DefaultValue (0)]
[Description ("Methods with cyclomatic complexity less than this will be reported as medium severity.")]
public int MediumThreshold { get; set; }
/// <summary>Methods with cyclomatic complexity less than this (but higher than MediumThreshold) will be reported as high severity.</summary>
/// <remarks>Methods with cyclomatic complexity greater than this will be reported as critical severity.
/// If left as zero then the rule will initialize it to 4*SuccessThreshold.</remarks>
[DefaultValue (0)]
[Description ("Methods with cyclomatic complexity less than this will be reported as high severity.")]
public int HighThreshold { get; set; }
public RuleResult CheckMethod (MethodDefinition method)
{
//does rule apply?
if (!method.HasBody || method.IsGeneratedCode () || method.IsCompilerControlled)
return RuleResult.DoesNotApply;
//yay! rule do apply!
// quick optimization: if the number of instructions is lower
// than our SuccessThreshold then it cannot be too complex
if (method.Body.Instructions.Count < SuccessThreshold)
return RuleResult.Success;
int cc = GetCyclomaticComplexity (method);
if (cc < SuccessThreshold)
return RuleResult.Success;
//how's severity?
Severity sev = GetCyclomaticComplexitySeverity(cc);
string msg = String.Format (CultureInfo.CurrentCulture, "Method's cyclomatic complexity : {0}.", cc);
Runner.Report (method, sev, Confidence.High, msg);
return RuleResult.Failure;
}
public Severity GetCyclomaticComplexitySeverity(int cc)
{
// 25 <= CC < 50 is not good but not catastrophic either
if (cc < LowThreshold)
return Severity.Low;
// 50 <= CC < 75 this should be refactored asap
if (cc < MediumThreshold)
return Severity.Medium;
// 75 <= CC < 100 this SHOULD be refactored asap
if (cc < HighThreshold)
return Severity.High;
// CC > 100, don't touch it since it may become a classic in textbooks
// anyway probably no one can understand it ;-)
return Severity.Critical;
}
static public int GetCyclomaticComplexity (MethodDefinition method)
{
if ((method == null) || !method.HasBody)
return 1;
if (OpCodeEngine.GetBitmask (method).Get (Code.Switch))
return GetSwitchCyclomaticComplexity (method);
else
return GetFastCyclomaticComplexity (method);
}
// the use of 'switch' requires a bit more code so we avoid it unless there are swicth instructions
static private int GetFastCyclomaticComplexity (MethodDefinition method)
{
int cc = 1;
foreach (Instruction ins in method.Body.Instructions) {
switch (ins.OpCode.FlowControl) {
case FlowControl.Branch:
// detect ternary pattern
Instruction previous = ins.Previous;
if ((previous != null) && ld.Get (previous.OpCode.Code))
cc++;
break;
case FlowControl.Cond_Branch:
cc++;
break;
}
}
return cc;
}
static private int GetSwitchCyclomaticComplexity (MethodDefinition method)
{
Instruction previous = null;
Instruction branch = null;
int cc = 1;
foreach (Instruction ins in method.Body.Instructions) {
switch (ins.OpCode.FlowControl) {
case FlowControl.Branch:
if (previous == null)
continue;
// detect ternary pattern
previous = ins.Previous;
if (ld.Get (previous.OpCode.Code))
cc++;
// or 'default' (xmcs)
if (previous.OpCode.FlowControl == FlowControl.Cond_Branch) {
branch = (previous.Operand as Instruction);
// branch can be null (e.g. switch -> Instruction[])
if ((branch != null) && targets.Contains (branch))
targets.AddIfNew (ins);
}
break;
case FlowControl.Cond_Branch:
// note: a single switch (C#) with sparse values can be broken into several swicth (IL)
// that will use the same 'targets' and must be counted only once
if (ins.OpCode.Code == Code.Switch) {
AccumulateSwitchTargets (ins);
} else {
// some conditional branch can be related to the sparse switch
branch = (ins.Operand as Instruction);
previous = branch.Previous;
if ((previous != null) && !previous.Previous.Is (Code.Switch)) {
if (!targets.Contains (branch))
cc++;
}
}
break;
}
}
// count all unique targets (and default if more than one C# switch is used)
cc += targets.Count;
targets.Clear ();
return cc;
}
static List<Instruction> targets = new List<Instruction> ();
static private void AccumulateSwitchTargets (Instruction ins)
{
Instruction[] cases = (Instruction[]) ins.Operand;
foreach (Instruction target in cases) {
// ignore targets that are the next instructions (xmcs)
if (target != ins.Next)
targets.AddIfNew (target);
}
// add 'default' branch (if one exists)
Instruction next = ins.Next;
if (next.OpCode.FlowControl == FlowControl.Branch) {
Instruction unc = FindFirstUnconditionalBranchTarget (cases [0]);
if (unc != next.Operand)
targets.AddIfNew (next.Operand as Instruction);
}
}
static private Instruction FindFirstUnconditionalBranchTarget (Instruction ins)
{
while (ins != null) {
if (FlowControl.Branch == ins.OpCode.FlowControl)
return ((Instruction) ins.Operand);
ins = ins.Next;
}
return null;
}
#if false
public void Bitmask ()
{
OpCodeBitmask mask = new OpCodeBitmask ();
mask.Set (Code.Ldarg);
mask.Set (Code.Ldarg_0);
mask.Set (Code.Ldarg_1);
mask.Set (Code.Ldarg_2);
mask.Set (Code.Ldarg_3);
mask.Set (Code.Ldarg_S);
mask.Set (Code.Ldarga);
mask.Set (Code.Ldarga_S);
mask.Set (Code.Ldc_I4);
mask.Set (Code.Ldc_I4_0);
mask.Set (Code.Ldc_I4_1);
mask.Set (Code.Ldc_I4_2);
mask.Set (Code.Ldc_I4_3);
mask.Set (Code.Ldc_I4_4);
mask.Set (Code.Ldc_I4_5);
mask.Set (Code.Ldc_I4_6);
mask.Set (Code.Ldc_I4_7);
mask.Set (Code.Ldc_I4_8);
mask.Set (Code.Ldc_I4_M1);
mask.Set (Code.Ldc_I4_S);
mask.Set (Code.Ldc_I8);
mask.Set (Code.Ldc_R4);
mask.Set (Code.Ldc_R8);
mask.Set (Code.Ldelem_Any);
mask.Set (Code.Ldelem_I);
mask.Set (Code.Ldelem_I1);
mask.Set (Code.Ldelem_I2);
mask.Set (Code.Ldelem_I4);
mask.Set (Code.Ldelem_I8);
mask.Set (Code.Ldelem_R4);
mask.Set (Code.Ldelem_R8);
mask.Set (Code.Ldelem_Ref);
mask.Set (Code.Ldelem_U1);
mask.Set (Code.Ldelem_U2);
mask.Set (Code.Ldelem_U4);
mask.Set (Code.Ldelema);
mask.Set (Code.Ldfld);
mask.Set (Code.Ldflda);
mask.Set (Code.Ldftn);
mask.Set (Code.Ldind_I);
mask.Set (Code.Ldind_I1);
mask.Set (Code.Ldind_I2);
mask.Set (Code.Ldind_I4);
mask.Set (Code.Ldind_I8);
mask.Set (Code.Ldind_R4);
mask.Set (Code.Ldind_R8);
mask.Set (Code.Ldind_Ref);
mask.Set (Code.Ldind_U1);
mask.Set (Code.Ldind_U2);
mask.Set (Code.Ldind_U4);
mask.Set (Code.Ldlen);
mask.Set (Code.Ldloc);
mask.Set (Code.Ldloc_0);
mask.Set (Code.Ldloc_1);
mask.Set (Code.Ldloc_2);
mask.Set (Code.Ldloc_3);
mask.Set (Code.Ldloc_S);
mask.Set (Code.Ldloca);
mask.Set (Code.Ldloca_S);
mask.Set (Code.Ldnull);
mask.Set (Code.Ldobj);
mask.Set (Code.Ldsfld);
mask.Set (Code.Ldsflda);
mask.Set (Code.Ldstr);
mask.Set (Code.Ldtoken);
mask.Set (Code.Ldvirtftn);
Console.WriteLine (mask);
}
#endif
}
}