2
// DuplicateBodyMethodIssue.cs
5
// Ciprian Khlud <ciprian.mustiata@yahoo.com>
7
// Copyright (c) 2013 Ciprian Khlud
9
// Permission is hereby granted, free of charge, to any person obtaining a copy
10
// of this software and associated documentation files (the "Software"), to deal
11
// in the Software without restriction, including without limitation the rights
12
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
// copies of the Software, and to permit persons to whom the Software is
14
// furnished to do so, subject to the following conditions:
16
// The above copyright notice and this permission notice shall be included in
17
// all copies or substantial portions of the Software.
19
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27
using System.Collections.Generic;
29
using ICSharpCode.NRefactory.PatternMatching;
30
using ICSharpCode.NRefactory.Semantics;
33
namespace ICSharpCode.NRefactory.CSharp.Refactoring
35
[IssueDescription("Methods have duplicate body",
36
Description = "One method has the same body as other method",
37
Severity = Severity.Hint,
38
IssueMarker = IssueMarker.Underline)]
39
public class DuplicateBodyMethodIssue : ICodeIssueProvider
41
#region ICodeIssueProvider implementation
43
public IEnumerable<CodeIssue> GetIssues(BaseRefactoringContext context)
45
var visitor = new GatherVisitor(context);
47
visitor.ComputeConflicts();
48
return visitor.GetIssues();
53
private class GatherVisitor : GatherVisitorBase<DuplicateBodyMethodIssue>
55
public List<MethodDeclaration> DeclaredMethods;
57
public GatherVisitor(BaseRefactoringContext context)
60
DeclaredMethods = new List<MethodDeclaration>();
64
static string GetMethodDescriptor(MethodDeclaration methodDeclaration) {
65
var sb = new StringBuilder();
66
sb.Append(methodDeclaration.ReturnType);
68
foreach (var parameter in methodDeclaration.Parameters) {
69
sb.AppendFormat("{0}:{1};", parameter.Name, parameter.Type);
71
sb.Append(methodDeclaration.Modifiers);
75
public void GetMethods()
77
ctx.RootNode.AcceptVisitor(this);
80
internal void ComputeConflicts()
82
var dict = new Dictionary<string, List<MethodDeclaration>>();
83
foreach (var declaredMethod in DeclaredMethods)
85
var methodDescriptor = GetMethodDescriptor(declaredMethod);
86
List<MethodDeclaration> listMethods;
87
if (!dict.TryGetValue(methodDescriptor, out listMethods))
89
listMethods = new List<MethodDeclaration>();
90
dict[methodDescriptor] = listMethods;
92
listMethods.Add(declaredMethod);
94
DeclaredMethods.Clear();
96
foreach (var list in dict.Values.Where(list => list.Count >= 2))
98
for (var i = 0; i < list.Count - 1; i++)
100
var firstMethod = list[i];
101
for (var j = i + 1; j < list.Count; j++)
103
var secondMethod = list[j];
104
if (firstMethod.Body.IsMatch(secondMethod.Body))
106
AddIssue(secondMethod.NameToken,
107
string.Format("Method '{0}' has the same with '{1}' ", secondMethod.Name,
109
script => { InvokeMethod(script, firstMethod, secondMethod); }
117
readonly InsertParenthesesVisitor _insertParenthesesVisitor = new InsertParenthesesVisitor();
118
private TypeDeclaration _parentType;
120
private void InvokeMethod(Script script, MethodDeclaration firstMethod, MethodDeclaration secondMethod)
123
new ExpressionStatement(new InvocationExpression(new IdentifierExpression(firstMethod.Name),
124
firstMethod.Parameters.Select(
126
GetArgumentExpression(declaration).Clone())));
127
statement.AcceptVisitor(_insertParenthesesVisitor);
128
if(firstMethod.ReturnType.ToString()!="System.Void"){
129
var returnStatement = new ReturnStatement(statement.Expression.Clone());
131
script.Replace(secondMethod.Body, new BlockStatement { returnStatement });
134
script.Replace(secondMethod.Body, new BlockStatement { statement });
138
static Expression GetArgumentExpression(ParameterDeclaration parameter)
140
var identifierExpr = new IdentifierExpression(parameter.Name);
141
switch (parameter.ParameterModifier)
143
case ParameterModifier.Out:
144
return new DirectionExpression(FieldDirection.Out, identifierExpr);
145
case ParameterModifier.Ref:
146
return new DirectionExpression(FieldDirection.Ref, identifierExpr);
148
return identifierExpr;
151
public override void VisitMethodDeclaration(MethodDeclaration declaration)
154
var methodDeclaration = declaration;
156
var resolved = context.Resolve(methodDeclaration) as MemberResolveResult;
157
if (resolved == null)
159
var isImplementingInterface = resolved.Member.ImplementedInterfaceMembers.Any();
161
if (isImplementingInterface)
163
if (declaration.Body.IsNull)
166
var parentType = declaration.Parent as TypeDeclaration;
167
if (parentType == null)
169
if (_parentType == null)
170
_parentType = parentType;
173
//if we are here, it means that we switched from one class to another, so it means that we should compute
174
//the duplicates up-to now, then reset the list of methods
175
if (parentType != _parentType)
178
DeclaredMethods.Add(declaration);
179
_parentType = parentType;
184
DeclaredMethods.Add(declaration);