File: AccessToClosureIssue.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 (319 lines) | stat: -rw-r--r-- 10,265 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
// 
// AccessToClosureIssue.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.Analysis;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;

namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
	public abstract class AccessToClosureIssue : ICodeIssueProvider
	{
		ControlFlowGraphBuilder cfgBuilder = new ControlFlowGraphBuilder ();

		public string Title
		{ get; private set; }

		protected AccessToClosureIssue (string title)
		{
			Title = title;
		}

		public IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
		{
			var unit = context.RootNode as SyntaxTree;
			if (unit == null)
				return Enumerable.Empty<CodeIssue> ();
			return new GatherVisitor (context, unit, this).GetIssues ();
		}

		protected virtual bool IsTargetVariable (IVariable variable)
		{
			return true;
		}

		protected abstract NodeKind GetNodeKind (AstNode node);

		protected virtual bool CanReachModification (ControlFlowNode node, Statement start,
												     IDictionary<Statement, IList<Node>> modifications)
		{
			return node.NextStatement != null && node.NextStatement != start &&
				   modifications.ContainsKey (node.NextStatement);
		}

		protected abstract IEnumerable<CodeAction> GetFixes (BaseRefactoringContext context, Node env, 
															 string variableName);

		#region GatherVisitor

		class GatherVisitor : GatherVisitorBase<AccessToClosureIssue>
		{
			string title;

			public GatherVisitor (BaseRefactoringContext context, SyntaxTree unit,
								  AccessToClosureIssue qualifierDirectiveEvidentIssueProvider)
				: base (context, qualifierDirectiveEvidentIssueProvider)
			{
				this.title = context.TranslateString (qualifierDirectiveEvidentIssueProvider.Title);
			}

			public override void VisitVariableInitializer (VariableInitializer variableInitializer)
			{
				var variableDecl = variableInitializer.Parent as VariableDeclarationStatement;
				if (variableDecl != null)
					CheckVariable (((LocalResolveResult)ctx.Resolve (variableInitializer)).Variable, 
								   variableDecl.GetParent<Statement> ());
				base.VisitVariableInitializer (variableInitializer);
			}

			public override void VisitForeachStatement (ForeachStatement foreachStatement)
			{
				CheckVariable (((LocalResolveResult)ctx.Resolve (foreachStatement.VariableNameToken)).Variable,
							   foreachStatement);
				base.VisitForeachStatement (foreachStatement);
			}

			public override void VisitParameterDeclaration (ParameterDeclaration parameterDeclaration)
			{
				var parent = parameterDeclaration.Parent;
				Statement body = null;
				if (parent is MethodDeclaration) {
					body = ((MethodDeclaration)parent).Body;
				} else if (parent is AnonymousMethodExpression) {
					body = ((AnonymousMethodExpression)parent).Body;
				} else if (parent is LambdaExpression) {
					body = ((LambdaExpression)parent).Body as Statement;
				} else if (parent is ConstructorDeclaration) {
					body = ((ConstructorDeclaration)parent).Body;
				} else if (parent is OperatorDeclaration) {
					body = ((OperatorDeclaration)parent).Body;
				}
				if (body != null) {
					var lrr = ctx.Resolve (parameterDeclaration) as LocalResolveResult;
					if (lrr != null)
						CheckVariable (lrr.Variable, body);
				}
				base.VisitParameterDeclaration (parameterDeclaration);
			}

			void CheckVariable(IVariable variable, Statement env)
			{
				if (!QualifierDirectiveEvidentIssueProvider.IsTargetVariable(variable))
					return;

				var root = new Environment (env, env);
				var envLookup = new Dictionary<AstNode, Environment> ();
				envLookup [env] = root;

				foreach (var result in ctx.FindReferences(env, variable)) {
					AddNode(envLookup, new Node(result.Node, QualifierDirectiveEvidentIssueProvider.GetNodeKind(result.Node)));
				}

				root.SortChildren ();
				CollectIssues (root, variable.Name);
			}

			void CollectIssues (Environment env, string variableName)
			{
				IList<ControlFlowNode> cfg = null;
				IDictionary<Statement, IList<Node>> modifications = null;

				if (env.Body != null) {
					cfg = QualifierDirectiveEvidentIssueProvider.cfgBuilder.BuildControlFlowGraph (env.Body);
					modifications = new Dictionary<Statement, IList<Node>> ();
					foreach (var node in env.Children) {
						if (node.Kind == NodeKind.Modification || node.Kind == NodeKind.ReferenceAndModification) {
							IList<Node> nodes;
							if (!modifications.TryGetValue (node.ContainingStatement, out nodes))
								modifications [node.ContainingStatement] = nodes = new List<Node> ();
							nodes.Add (node);
						}
					}
				}

				foreach (var child in env.GetChildEnvironments ()) {
					if (!child.IssueCollected && cfg != null && 
						CanReachModification (cfg, child, modifications))
						CollectAllIssues (child, variableName);

					CollectIssues (child, variableName);
				}
			}

			void CollectAllIssues (Environment env, string variableName)
			{
				var fixes = QualifierDirectiveEvidentIssueProvider.GetFixes (ctx, env, variableName).ToArray ();
				env.IssueCollected = true;

				foreach (var child in env.Children) {
					if (child is Environment) {
						CollectAllIssues ((Environment)child, variableName);
					} else {
						if (child.Kind != NodeKind.Modification)
							AddIssue (child.AstNode, title, fixes);
						// stop marking references after the variable is modified in current environment
						if (child.Kind != NodeKind.Reference)
							break;
					}
				}
			}

			void AddNode (IDictionary<AstNode, Environment> envLookup, Node node)
			{
				var astParent = node.AstNode.Parent;
				var path = new List<AstNode> ();
				while (astParent != null) {
					Environment parent;
					if (envLookup.TryGetValue (astParent, out parent)) {
						parent.Children.Add (node);
						return;
					}

					if (astParent is LambdaExpression) {
						parent = new Environment (astParent, ((LambdaExpression)astParent).Body as Statement);
					} else if (astParent is AnonymousMethodExpression) {
						parent = new Environment (astParent, ((AnonymousMethodExpression)astParent).Body);
					}

					path.Add (astParent);
					if (parent != null) {
						foreach (var astNode in path)
							envLookup [astNode] = parent;
						path.Clear ();

						parent.Children.Add (node);
						node = parent;
					}
					astParent = astParent.Parent;
				}
			}

			bool CanReachModification (IEnumerable<ControlFlowNode> cfg, Environment env,
									   IDictionary<Statement, IList<Node>> modifications)
			{
				if (modifications.Count == 0)
					return false;

				var start = env.ContainingStatement;
				if (modifications.ContainsKey (start) &&
					modifications [start].Any (v => v.AstNode.StartLocation > env.AstNode.EndLocation))
					return true;

				var stack = new Stack<ControlFlowNode> (cfg.Where (node => node.NextStatement == start));
				var visitedNodes = new HashSet<ControlFlowNode> (stack);
				while (stack.Count > 0) {
					var node = stack.Pop ();
					if (QualifierDirectiveEvidentIssueProvider.CanReachModification (node, start, modifications))
						return true;
					foreach (var edge in node.Outgoing) {
						if (visitedNodes.Add (edge.To))
							stack.Push (edge.To);
					}
				}
				return false;
			}

		}

		#endregion

		#region Node

		protected enum NodeKind
		{
			Reference,
			Modification,
			ReferenceAndModification,
			Environment,
		}

		protected class Node
		{
			public AstNode AstNode
			{ get; private set; }

			public NodeKind Kind
			{ get; private set; }

			public Statement ContainingStatement
			{ get; private set; }

			public Node (AstNode astNode, NodeKind kind)
			{
				AstNode = astNode;
				Kind = kind;
				ContainingStatement = astNode.GetParent<Statement> ();
			}

			public virtual IEnumerable<Node> GetAllReferences ()
			{
				yield return this;
			}
		}

		protected class Environment : Node
		{
			public Statement Body
			{ get; private set; }

			public bool IssueCollected
			{ get; set; }

			public List<Node> Children
			{ get; private set; }

			public Environment (AstNode astNode, Statement body)
				: base (astNode, NodeKind.Environment)
			{
				Body = body;
				Children = new List<Node> ();
			}

			public override IEnumerable<Node> GetAllReferences ()
			{
				return Children.SelectMany (child => child.GetAllReferences ());
			}

			public IEnumerable<Environment> GetChildEnvironments ()
			{
				return from child in Children
					   where child is Environment
					   select (Environment)child;
			}

			public void SortChildren ()
			{
				Children.Sort ((x, y) => x.AstNode.StartLocation.CompareTo(y.AstNode.StartLocation));
				foreach (var env in GetChildEnvironments ())
					env.SortChildren ();
			}
		}

		#endregion
	}
}