File: PutInsideUsingAction.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 (160 lines) | stat: -rw-r--r-- 6,170 bytes parent folder | download | duplicates (5)
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
// 
// PutInsideUsingAction.cs
//  
// Author:
//       Mansheng Yang <lightyang0@gmail.com>
// 
// Copyright (c) 2012 Mansheng Yang <lightyang0@gmail.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.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.PatternMatching;

namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
	[ContextAction ("put inside 'using'", Description = "put IDisposable inside 'using' construct")]
	public class PutInsideUsingAction : SpecializedCodeAction <VariableInitializer>
	{
		static readonly FindReferences refFinder = new FindReferences ();
		protected override CodeAction GetAction (RefactoringContext context, VariableInitializer node)
		{
			if (node.Initializer.IsNull)
				return null;

			var variableDecl = node.Parent as VariableDeclarationStatement;
			if (variableDecl == null || !(variableDecl.Parent is BlockStatement))
				return null;

			var type = context.ResolveType (variableDecl.Type);
			if (!IsIDisposable (type))
				return null;

			var unit = context.RootNode as SyntaxTree;
			if (unit == null)
				return null;

			var resolveResult = (LocalResolveResult)context.Resolve (node);

			return new CodeAction (context.TranslateString ("put inside 'using'"),
				script =>
				{
					var lastReference = GetLastReference (resolveResult.Variable, context, unit);

					var body = new BlockStatement ();
					var variableToMoveOutside = new List<VariableDeclarationStatement> ();

					if (lastReference != node) {
						var statements = CollectStatements (variableDecl.GetNextSibling (n => n is Statement) as Statement, 
															lastReference.EndLocation).ToArray();

						// collect statements to put inside 'using' and variable declaration to move outside 'using'
						foreach (var statement in statements) {
							script.Remove (statement);

							var decl = statement as VariableDeclarationStatement;
							if (decl == null) {
								body.Statements.Add (statement.Clone ());
								continue;
							}

							var outsideDecl = (VariableDeclarationStatement)decl.Clone ();
							outsideDecl.Variables.Clear ();
							var insideDecl = (VariableDeclarationStatement)outsideDecl.Clone ();

							foreach (var variable in decl.Variables) {
								var reference = GetLastReference (
									((LocalResolveResult)context.Resolve (variable)).Variable, context, unit);
								if (reference.StartLocation > lastReference.EndLocation)
									outsideDecl.Variables.Add ((VariableInitializer)variable.Clone ());
								else
									insideDecl.Variables.Add ((VariableInitializer)variable.Clone ());
							}
							if (outsideDecl.Variables.Count > 0)
								variableToMoveOutside.Add (outsideDecl);
							if (insideDecl.Variables.Count > 0)
								body.Statements.Add (insideDecl);
						}
					}

					foreach (var decl in variableToMoveOutside)
						script.InsertBefore (variableDecl, decl);

					if (body.Statements.Count > 0) {
						var lastStatement = body.Statements.Last ();
						if (IsDisposeInvocation (resolveResult.Variable.Name, lastStatement))
							lastStatement.Remove ();
					}
					var usingStatement = new UsingStatement
					{
						ResourceAcquisition = new VariableDeclarationStatement (variableDecl.Type.Clone (), node.Name,
																				node.Initializer.Clone ()),
						EmbeddedStatement = body
					};
					script.Replace (variableDecl, usingStatement);

					if (variableDecl.Variables.Count == 1)
						return;
					// other variables in the same declaration statement
					var remainingVariables = (VariableDeclarationStatement)variableDecl.Clone ();
					remainingVariables.Variables.Remove (
						remainingVariables.Variables.FirstOrDefault (v => v.Name == node.Name));
					script.InsertBefore (usingStatement, remainingVariables);
				}, node.NameToken);
		}

		static bool IsIDisposable (IType type)
		{
			return type.GetAllBaseTypeDefinitions ().Any (t => t.KnownTypeCode == KnownTypeCode.IDisposable);
		}
	
		static IEnumerable<Statement> CollectStatements (Statement statement, TextLocation end)
		{
			while (statement != null) {
				yield return statement;
				if (statement.Contains (end))
					break;
				statement = statement.GetNextSibling (n => n is Statement) as Statement;
			}
		}

		static AstNode GetLastReference (IVariable variable, RefactoringContext context, SyntaxTree unit)
		{
			AstNode lastReference = null;
			refFinder.FindLocalReferences (variable, context.UnresolvedFile, unit, context.Compilation,
				(v, r) =>
				{
					if (lastReference == null || v.EndLocation > lastReference.EndLocation)
						lastReference = v;
				}, context.CancellationToken);
			return lastReference;
		}

		static bool IsDisposeInvocation (string variableName, Statement statement)
		{
			var memberReferenceExpr = new MemberReferenceExpression (new IdentifierExpression (variableName), "Dispose");
			var pattern = new ExpressionStatement (new InvocationExpression (memberReferenceExpr));
			return pattern.Match (statement).Success;
		}
	}
}