~ubuntu-branches/ubuntu/trusty/monodevelop/trusty-proposed

« back to all changes in this revision

Viewing changes to contrib/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ExtractMethod/ExtractMethodAction.cs

  • Committer: Package Import Robot
  • Author(s): Jo Shields
  • Date: 2013-05-12 09:46:03 UTC
  • mto: This revision was merged to the branch mainline in revision 29.
  • Revision ID: package-import@ubuntu.com-20130512094603-mad323bzcxvmcam0
Tags: upstream-4.0.5+dfsg
ImportĀ upstreamĀ versionĀ 4.0.5+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
// 
2
 
// ExtractMethodAction.cs
3
 
//  
4
 
// Author:
5
 
//       Mike KrĆ¼ger <mkrueger@xamarin.com>
6
 
// 
7
 
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.com)
8
 
// 
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:
15
 
// 
16
 
// The above copyright notice and this permission notice shall be included in
17
 
// all copies or substantial portions of the Software.
18
 
// 
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
25
 
// THE SOFTWARE.
26
 
using System;
27
 
using System.Collections.Generic;
28
 
using ICSharpCode.NRefactory.Semantics;
29
 
using System.Linq;
30
 
using ICSharpCode.NRefactory.CSharp.Resolver;
31
 
using ICSharpCode.NRefactory.CSharp.Analysis;
32
 
using System.Threading;
33
 
using ICSharpCode.NRefactory.TypeSystem;
34
 
 
35
 
namespace ICSharpCode.NRefactory.CSharp.Refactoring.ExtractMethod
36
 
{
37
 
        [ContextAction("Extract method", Description = "Creates a new method out of selected text.")]
38
 
        public class ExtractMethodAction : ICodeActionProvider
39
 
        {
40
 
                public IEnumerable<CodeAction> GetActions(RefactoringContext context)
41
 
                {
42
 
                        if (!context.IsSomethingSelected)
43
 
                                yield break;
44
 
                        var selected = new List<AstNode>(context.GetSelectedNodes());
45
 
                        if (selected.Count == 0)
46
 
                                yield break;
47
 
 
48
 
                        if (selected.Count == 1 && selected [0] is Expression) {
49
 
                                var codeAction = CreateFromExpression(context, (Expression)selected [0]);
50
 
                                if (codeAction == null)
51
 
                                        yield break;
52
 
                                yield return codeAction;
53
 
                        }
54
 
 
55
 
                        foreach (var node in selected) {
56
 
                                if (!(node is Statement))
57
 
                                        yield break;
58
 
                        }
59
 
                        var action = CreateFromStatements (context, new List<Statement> (selected.OfType<Statement> ()));
60
 
                        if (action != null)
61
 
                                yield return action;
62
 
                }
63
 
 
64
 
                CodeAction CreateFromExpression(RefactoringContext context, Expression expression)
65
 
                {
66
 
                        var resolveResult = context.Resolve(expression);
67
 
                        if (resolveResult.IsError)
68
 
                                return null;
69
 
 
70
 
                        return new CodeAction(context.TranslateString("Extract method"), script => {
71
 
                                string methodName = "NewMethod";
72
 
                                var method = new MethodDeclaration() {
73
 
                                        ReturnType = context.CreateShortType(resolveResult.Type),
74
 
                                        Name = methodName,
75
 
                                        Body = new BlockStatement() {
76
 
                                                new ReturnStatement(expression.Clone())
77
 
                                        }
78
 
                                };
79
 
                                if (!StaticVisitor.UsesNotStaticMember(context, expression))
80
 
                                        method.Modifiers |= Modifiers.Static;
81
 
                                script.InsertWithCursor(context.TranslateString("Extract method"), Script.InsertPosition.Before, method);
82
 
                                var target = new IdentifierExpression(methodName);
83
 
                                script.Replace(expression, new InvocationExpression(target));
84
 
//                              script.Link(target, method.NameToken);
85
 
                        });
86
 
                }
87
 
 
88
 
                CodeAction CreateFromStatements(RefactoringContext context, List<Statement> statements)
89
 
                {
90
 
                        if (!(statements [0].Parent is Statement))
91
 
                                return null;
92
 
 
93
 
                        return new CodeAction(context.TranslateString("Extract method"), script => {
94
 
                                string methodName = "NewMethod";
95
 
                                var method = new MethodDeclaration() {
96
 
                                        ReturnType = new PrimitiveType("void"),
97
 
                                        Name = methodName,
98
 
                                        Body = new BlockStatement()
99
 
                                };
100
 
                                bool usesNonStaticMember = false;
101
 
                                foreach (Statement node in statements) {
102
 
                                        usesNonStaticMember |= StaticVisitor.UsesNotStaticMember(context, node);
103
 
                                        method.Body.Add(node.Clone());
104
 
                                }
105
 
                                if (!usesNonStaticMember)
106
 
                                        method.Modifiers |= Modifiers.Static;
107
 
                                
108
 
                                var target = new IdentifierExpression(methodName);
109
 
                                var invocation = new InvocationExpression(target);
110
 
 
111
 
                                var usedVariables = VariableLookupVisitor.Analyze(context, statements);
112
 
 
113
 
                                var extractedCodeAnalysis = new DefiniteAssignmentAnalysis(
114
 
                                        (Statement)statements [0].Parent,
115
 
                                        context.Resolver,
116
 
                                        context.CancellationToken);
117
 
                                var lastStatement = statements [statements.Count - 1];
118
 
                                extractedCodeAnalysis.SetAnalyzedRange(statements [0], lastStatement);
119
 
                                var statusAfterMethod = new List<Tuple<IVariable, DefiniteAssignmentStatus>>();
120
 
                                
121
 
                                foreach (var variable in usedVariables) {
122
 
                                        extractedCodeAnalysis.Analyze(
123
 
                                                variable.Name,
124
 
                                                DefiniteAssignmentStatus.PotentiallyAssigned,
125
 
                                                context.CancellationToken);
126
 
                                        statusAfterMethod.Add(Tuple.Create(variable, extractedCodeAnalysis.GetStatusAfter(lastStatement)));
127
 
                                }
128
 
                                var stmt = statements [0].GetParent<BlockStatement>();
129
 
                                while (stmt.GetParent<BlockStatement> () != null) {
130
 
                                        stmt = stmt.GetParent<BlockStatement>();
131
 
                                }
132
 
                                
133
 
                                var wholeCodeAnalysis = new DefiniteAssignmentAnalysis(stmt, context.Resolver, context.CancellationToken);
134
 
                                var statusBeforeMethod = new Dictionary<IVariable, DefiniteAssignmentStatus>();
135
 
                                foreach (var variable in usedVariables) {
136
 
                                        wholeCodeAnalysis.Analyze(variable.Name, DefiniteAssignmentStatus.PotentiallyAssigned, context.CancellationToken);
137
 
                                        statusBeforeMethod [variable] = extractedCodeAnalysis.GetStatusBefore(statements [0]);
138
 
                                }
139
 
 
140
 
                                var afterCodeAnalysis = new DefiniteAssignmentAnalysis(stmt, context.Resolver, context.CancellationToken);
141
 
                                var statusAtEnd = new Dictionary<IVariable, DefiniteAssignmentStatus>();
142
 
                                afterCodeAnalysis.SetAnalyzedRange(lastStatement, stmt.Statements.Last(), false, true);
143
 
 
144
 
                                foreach (var variable in usedVariables) {
145
 
                                        afterCodeAnalysis.Analyze(variable.Name, DefiniteAssignmentStatus.PotentiallyAssigned, context.CancellationToken);
146
 
                                        statusBeforeMethod [variable] = extractedCodeAnalysis.GetStatusBefore(statements [0]);
147
 
                                }
148
 
                                var beforeVisitor = new VariableLookupVisitor(context);
149
 
                                beforeVisitor.SetAnalyzedRange(stmt, statements [0], true, false);
150
 
                                stmt.AcceptVisitor(beforeVisitor);
151
 
                                var afterVisitor = new VariableLookupVisitor(context);
152
 
                                afterVisitor.SetAnalyzedRange(lastStatement, stmt, false, true);
153
 
                                stmt.AcceptVisitor(afterVisitor);
154
 
 
155
 
                                foreach (var status in statusAfterMethod) {
156
 
                                        if (!beforeVisitor.UsedVariables.Contains(status.Item1) && !afterVisitor.UsedVariables.Contains(status.Item1))
157
 
                                                continue;
158
 
                                        Expression argumentExpression = new IdentifierExpression(status.Item1.Name); 
159
 
                                        
160
 
                                        ParameterModifier mod;
161
 
                                        switch (status.Item2) {
162
 
                                                case DefiniteAssignmentStatus.AssignedAfterTrueExpression:
163
 
                                                case DefiniteAssignmentStatus.AssignedAfterFalseExpression:
164
 
                                                case DefiniteAssignmentStatus.PotentiallyAssigned:
165
 
                                                        mod = ParameterModifier.Ref;
166
 
                                                        argumentExpression = new DirectionExpression(FieldDirection.Ref, argumentExpression);
167
 
                                                        break;
168
 
                                                case DefiniteAssignmentStatus.DefinitelyAssigned:
169
 
                                                        if (statusBeforeMethod [status.Item1] != DefiniteAssignmentStatus.PotentiallyAssigned)
170
 
                                                                goto case DefiniteAssignmentStatus.PotentiallyAssigned;
171
 
                                                        mod = ParameterModifier.Out;
172
 
                                                        argumentExpression = new DirectionExpression(FieldDirection.Out, argumentExpression);
173
 
                                                        break;
174
 
//                                              case DefiniteAssignmentStatus.Unassigned:
175
 
                                                default:
176
 
                                                        mod = ParameterModifier.None;
177
 
                                                        break;
178
 
                                        }
179
 
                                        method.Parameters.Add(
180
 
                                                new ParameterDeclaration(context.CreateShortType(status.Item1.Type), status.Item1.Name, mod));
181
 
                                        invocation.Arguments.Add(argumentExpression);
182
 
                                }
183
 
 
184
 
                                foreach (var node in statements.Skip (1)) {
185
 
                                        script.Remove(node);
186
 
                                }
187
 
                                script.Replace(statements [0], new ExpressionStatement(invocation));
188
 
                                script.InsertWithCursor(context.TranslateString("Extract method"), Script.InsertPosition.Before, method);
189
 
                                //script.Link(target, method.NameToken);
190
 
                        });
191
 
                }
192
 
        }
193
 
}