File: DeclareLocalVariableAction.cs

package info (click to toggle)
nrefactory 5.3.0%2B20130718.73b6d0f-4.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 15,720 kB
  • sloc: cs: 296,018; makefile: 24; ansic: 7; sh: 2
file content (188 lines) | stat: -rw-r--r-- 6,968 bytes parent folder | download | duplicates (4)
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
// 
// DeclareLocalVariableAction.cs
//  
// Author:
//       Mike Krüger <mkrueger@xamarin.com>
// 
// Copyright (c) 2012 Xamarin Inc. (http://xamarin.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.Threading;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.PatternMatching;

namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
	[ContextAction("Declare local variable", Description = "Declare a local variable out of a selected expression.")]
	public class DeclareLocalVariableAction : ICodeActionProvider
	{
		public IEnumerable<CodeAction> GetActions(RefactoringContext context)
		{
			if (!context.IsSomethingSelected) {
				yield break;
			}
			var selected = new List<AstNode>(context.GetSelectedNodes());

			if (selected.Count != 1 || !(selected [0] is Expression)) {
				yield break;
			}

			var expr = selected [0] as Expression;
			if (expr is ArrayInitializerExpression) {
				var arr = (ArrayInitializerExpression)expr;
				if (arr.IsSingleElement) {
					expr = arr.Elements.First();
				} else {
					yield break;
				}
			}

			var visitor = new SearchNodeVisitior(expr);
			
			var node = context.GetNode <BlockStatement>();
			if (node != null) {
				node.AcceptVisitor(visitor);
			}

			yield return new CodeAction(context.TranslateString("Declare local variable"), script => {
				var resolveResult = context.Resolve(expr);
				var guessedType = resolveResult.Type;
				if (resolveResult is MethodGroupResolveResult) {
					guessedType = GetDelegateType(context, ((MethodGroupResolveResult)resolveResult).Methods.First(), expr);
				}
				var name = CreateMethodDeclarationAction.CreateBaseName(expr, guessedType);
				var type = context.UseExplicitTypes ? context.CreateShortType(guessedType) : new SimpleType("var");
				var varDecl = new VariableDeclarationStatement(type, name, expr.Clone());
				var replaceNode = visitor.Matches.First () as Expression;
				if (replaceNode.Parent is ExpressionStatement) {
					script.Replace(replaceNode.Parent, varDecl);
					script.Select(varDecl.Variables.First().NameToken);
				} else {
					var containing = replaceNode.Parent;
					while (!(containing.Parent is BlockStatement)) {
						containing = containing.Parent;
					}

					script.InsertBefore(containing, varDecl);
					var identifierExpression = new IdentifierExpression(name);
					script.Replace(replaceNode, identifierExpression);
					script.Link(varDecl.Variables.First().NameToken, identifierExpression);
				}
			}, expr);

			if (visitor.Matches.Count > 1) {
				yield return new CodeAction(string.Format(context.TranslateString("Declare local variable (replace '{0}' occurrences)"), visitor.Matches.Count), script => {
					var resolveResult = context.Resolve(expr);
					var guessedType = resolveResult.Type;
					if (resolveResult is MethodGroupResolveResult) {
						guessedType = GetDelegateType(context, ((MethodGroupResolveResult)resolveResult).Methods.First(), expr);
					}
					var linkedNodes = new List<AstNode>();
					var name = CreateMethodDeclarationAction.CreateBaseName(expr, guessedType);
					var type = context.UseExplicitTypes ? context.CreateShortType(guessedType) : new SimpleType("var");
					var varDecl = new VariableDeclarationStatement(type, name, expr.Clone());
					linkedNodes.Add(varDecl.Variables.First().NameToken);
					var first = visitor.Matches [0];
					if (first.Parent is ExpressionStatement) {
						script.Replace(first.Parent, varDecl);
					} else {
						var containing = first.Parent;
						while (!(containing.Parent is BlockStatement)) {
							containing = containing.Parent;
						}

						script.InsertBefore(containing, varDecl);
						var identifierExpression = new IdentifierExpression(name);
						linkedNodes.Add(identifierExpression);
						script.Replace(first, identifierExpression);
					}
					for (int i = 1; i < visitor.Matches.Count; i++) {
						var identifierExpression = new IdentifierExpression(name);
						linkedNodes.Add(identifierExpression);
						script.Replace(visitor.Matches [i], identifierExpression);
					}
					script.Link(linkedNodes.ToArray ());
				}, expr);
			}
		}

		// Gets Action/Func delegate types for a given method.
		IType GetDelegateType(RefactoringContext context, IMethod method, Expression expr)
		{
			var parameters = new List<IType>();
			var invoke = expr.Parent as InvocationExpression;
			if (invoke == null) {
				return null;
			}
			foreach (var arg in invoke.Arguments) {
				parameters.Add(context.Resolve(arg).Type);
			}

			ITypeDefinition genericType;
			if (method.ReturnType.FullName == "System.Void") {
				genericType = context.Compilation.GetAllTypeDefinitions().FirstOrDefault(t => t.FullName == "System.Action" && t.TypeParameterCount == parameters.Count);
			} else {
				parameters.Add(method.ReturnType);
				genericType = context.Compilation.GetAllTypeDefinitions().FirstOrDefault(t => t.FullName == "System.Func" && t.TypeParameterCount == parameters.Count);
			}
			if (genericType == null) {
				return null;
			}
			return new ParameterizedType(genericType, parameters);
		}

				
		internal class SearchNodeVisitior : DepthFirstAstVisitor
		{
			readonly AstNode searchForNode;
			public readonly List<AstNode> Matches = new List<AstNode> ();
			
			public SearchNodeVisitior (AstNode searchForNode)
			{
				this.searchForNode = searchForNode;
				AddNode (searchForNode);
			}

			void AddNode(AstNode node)
			{
				if (node.Parent is ParenthesizedExpression) {
					Matches.Add(node.Parent);
				} else {
					Matches.Add(node);
				}
			}
			
			protected override void VisitChildren(AstNode node)
			{
				if (node.StartLocation > searchForNode.StartLocation && node.IsMatch(searchForNode)) {
					AddNode(node);
					return;
				} 
				base.VisitChildren (node);
			}
		}


	}
}