Welcome to mirror list, hosted at ThFree Co, Russian Federation.

AvoidComplexMethodsRule.cs « Gendarme.Rules.Maintainability « rules « gendarme - github.com/mono/mono-tools.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 68a5ace16aa5cdbaa995b1b820476b73cdeaf28d (plain)
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
//
// Gendarme.Rules.Maintainability.AvoidComplexMethodsRule class
//
// Authors:
//	Cedric Vivier <cedricv@neonux.com>
//
// 	(C) 2008 Cedric Vivier
//
// 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 Mono.Cecil;
using Mono.Cecil.Cil;

using Gendarme.Framework;
using Gendarme.Framework.Rocks;

namespace Gendarme.Rules.Maintainability {

	// TODO: Is this really configureable? It would be nice if this rule did check anonymous methods.

	/// <summary>
	/// This rule compute 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 would 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 cyclomatic complexity equal or greater than 25 are harder to understand and maintain.")]
	[Solution ("Simplify the method using refactors like Extract Method.")]
	[FxCopCompatibility ("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
	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
		public AvoidComplexMethodsRule ()
		{
			SuccessThreshold = 25;
		}

		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;
		}

		public int SuccessThreshold { get; set; }

		public int LowThreshold { get; set; }

		public int MediumThreshold { get; set; }

		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 = GetCyclomaticComplexityForMethod(method);
			if (cc < SuccessThreshold)
				return RuleResult.Success;

			//how's severity?
			Severity sev = GetCyclomaticComplexitySeverity(cc);

			Runner.Report (method, sev, Confidence.High, String.Format ("Method's cyclomatic complexity : {0}.", cc));
			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;
		}

		public int GetCyclomaticComplexityForMethod (MethodDefinition method)
		{
			if ((method == null) || !method.HasBody)
				return 1;

			int cc = 1;

			foreach (Instruction inst in method.Body.Instructions)
			{
				if (FlowControl.Branch == inst.OpCode.FlowControl)
				{
					//detect ternary pattern
					// FIXME: nice case to look if using a OpCodeBitmask would be faster
					if (null != inst && null != inst.Previous && inst.Previous.OpCode.Name.StartsWith ("ld", StringComparison.Ordinal))
						cc++;
				}
				if (FlowControl.Cond_Branch != inst.OpCode.FlowControl)
				{
					continue;
				}

				if (inst.OpCode.Code == Code.Switch)
				{
					cc += GetNumberOfSwitchTargets(inst);
				}
				else //'normal' conditional branch
				{
					cc++;
				}
			}

			return cc;
		}

		List<Instruction> targets = new List<Instruction> ();

		private int GetNumberOfSwitchTargets (Instruction inst)
		{
			targets.Clear ();
			foreach (Instruction target in ((Instruction[]) inst.Operand))
			{
				if (!targets.Contains (target))
				{
					targets.Add (target);
				}
			}
			int nTargets = targets.Count;
			//detect 'default' branch
			if (FlowControl.Branch == inst.Next.OpCode.FlowControl)
			{
				if (inst.Next.Operand != FindFirstUnconditionalBranchTarget (targets[0]))
				{
					nTargets++;
				}
			}
			return nTargets;
		}

		private static Instruction FindFirstUnconditionalBranchTarget(Instruction inst)
		{
			while (null != inst)
			{
				if (FlowControl.Branch == inst.OpCode.FlowControl)
				{
					return ((Instruction) inst.Operand);
				}
				inst = inst.Next;
			}
			return null;
		}

	}

}