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

CodeDuplicatedLocator.cs « Gendarme.Rules.Smells « rules « gendarme - github.com/mono/mono-tools.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0085166a53f50b6235896d65aa95d0942ec8a745 (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
//
// Gendarme.Rules.Smells.CodeDuplicatedLocator class
//
// Authors:
//	Néstor Salceda <nestor.salceda@gmail.com>
//
// 	(C) 2007-2008 Néstor Salceda
//
// 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.Diagnostics;

using Mono.Cecil;
using Mono.Cecil.Cil;
using Gendarme.Framework;
using Gendarme.Framework.Helpers;
using Gendarme.Framework.Rocks;

namespace Gendarme.Rules.Smells {

	internal sealed class CodeDuplicatedLocator {
		HashSet<string> methods = new HashSet<string> ();
		HashSet<string> types = new HashSet<string> ();
		Dictionary<MethodDefinition, IList<Pattern>> patternsCached = new Dictionary<MethodDefinition, IList<Pattern>> ();
		IRule rule;

		internal CodeDuplicatedLocator (IRule rule) 
		{
			this.rule = rule;
		}

		internal ICollection<string> CheckedMethods {
			get {
				return methods;
			}
		}

		internal ICollection<string> CheckedTypes {
			get {
				return types;
			}
		}

		internal void Clear ()
		{
			methods.Clear ();
			types.Clear ();
		}

		internal void CompareMethodAgainstTypeMethods (MethodDefinition current, TypeDefinition targetType)
		{
			if (CheckedTypes.Contains (targetType.Name)) 
				return;
			
			foreach (MethodDefinition target in targetType.AllMethods()) {
				Pattern duplicated = GetDuplicatedCode (current, target);
				if (duplicated != null && duplicated.Count > 0)
					rule.Runner.Report (current, duplicated[0], Severity.High, Confidence.Normal, String.Format ("Duplicated code with {0}", target));
			}
		}

		bool CanCompareMethods (MethodDefinition current, MethodDefinition target)
		{
			return current.HasBody && target.HasBody &&
				!CheckedMethods.Contains (target.Name) &&
				current != target;
		}

		[Conditional ("DEBUG")]
		void WriteToOutput (MethodDefinition current, MethodDefinition target, Pattern found) 
		{
			Log.WriteLine (this, "Found pattern in {0} and {1}", current, target);
			Log.WriteLine (this, "\t Pattern");
			for (int index = 0; index < found.Count; index++) 
				Log.WriteLine (this, "\t\t{0} - {1}",
					found[index].OpCode.Code,
					found[index].Operand != null? found[index].Operand : "No operator");
		}

		Pattern GetDuplicatedCode (MethodDefinition current, MethodDefinition target)
		{
			if (!CanCompareMethods (current, target))
				return null;
			
			InstructionMatcher.Current = current;
			InstructionMatcher.Target = target;

			foreach (Pattern pattern in GetPatterns (current)) {
				if (pattern.IsCompilerGeneratedBlock || !pattern.IsExtractableToMethodBlock)
					continue;

				if (InstructionMatcher.Match (pattern, target.Body.Instructions)) {
					WriteToOutput (current, target, pattern);
					return pattern;
				}
			}

			return null;
		}
		

		IList<Pattern> GetPatterns (MethodDefinition method) 
		{
			IList<Pattern> patterns = null;
			if (!patternsCached.TryGetValue(method, out patterns)) {
				patterns = GeneratePatterns (method);
				patternsCached.Add (method, patterns);
			}
			return patterns;
		}

		//TODO: Still needs some testing in order to get the best size
		//for every case:
		//  The idea is get two overlapped statements in high level language
		static IList<Pattern> GeneratePatterns (MethodDefinition method) 
		{
			Stack<Stack<Instruction>> result = new Stack<Stack<Instruction>> ();
			Stack<Instruction> current = new Stack<Instruction> ();
			int stackCounter = 0;
			
			for (int index = method.Body.Instructions.Count - 1; index >= 0; index--) {
				Instruction currentInstruction = method.Body.Instructions[index];
				stackCounter += currentInstruction.GetPushCount ();
				stackCounter -= currentInstruction.GetPopCount (method);	
				
				if (result.Count != 0)
					result.Peek ().Push (currentInstruction);

				current.Push (currentInstruction);

				if (stackCounter == 0 && current.Count > 1) {//&& currentInstruction.OpCode.FlowControl != FlowControl.Branch) {  
					result.Push (current);
					current = new Stack<Instruction> ();
				}
			}

			//We can remove the first ocurrence
			if (result.Count != 0)
				result.Pop ();

			IList<Pattern> res = new List<Pattern> ();
			foreach (Stack<Instruction> stack in result) 
				res.Add (new Pattern (stack.ToArray ()));

			return res;
		}
	}
}