File: MultipleEnumerationIssue.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 (366 lines) | stat: -rw-r--r-- 12,807 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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// 
// MultipleEnumerationIssue.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;
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.Refactoring;

namespace ICSharpCode.NRefactory.CSharp.Refactoring
{
	[IssueDescription ("Possible multiple enumeration of IEnumerable",
					   Description = "Possible multiple enumeration of IEnumerable.",
					   Category = IssueCategories.CodeQualityIssues,
					   Severity = Severity.Warning,
					   IssueMarker = IssueMarker.Underline,
                       ResharperDisableKeyword = "PossibleNullReferenceException")]
	public class MultipleEnumerationIssue : ICodeIssueProvider
	{
		public IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context)
		{
			return new GatherVisitor (context).GetIssues ();
		}

		class AnalysisStatementCollector : DepthFirstAstVisitor
		{
			List<Statement> statements;
			AstNode variableDecl;

			AnalysisStatementCollector (AstNode variableDecl)
			{
				this.variableDecl = variableDecl;
			}

			IList<Statement> GetStatements ()
			{
				if (statements != null)
					return statements;

				statements = new List<Statement> ();
				var parent = variableDecl.Parent;
				while (parent != null) {
					if (parent is BlockStatement || parent is MethodDeclaration ||
						parent is AnonymousMethodExpression || parent is LambdaExpression) {
						parent.AcceptVisitor (this);
						if (parent is BlockStatement)
							statements.Add ((BlockStatement)parent);
						break;
					}
					parent = parent.Parent;
				}
				return statements;
			}

			public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration)
			{
				statements.Add (methodDeclaration.Body);

				base.VisitMethodDeclaration (methodDeclaration);
			}

			public override void VisitAnonymousMethodExpression (AnonymousMethodExpression anonymousMethodExpression)
			{
				statements.Add (anonymousMethodExpression.Body);

				base.VisitAnonymousMethodExpression (anonymousMethodExpression);
			}

			public override void VisitLambdaExpression (LambdaExpression lambdaExpression)
			{
				var body = lambdaExpression.Body as BlockStatement;
				if (body != null)
					statements.Add (body);

				base.VisitLambdaExpression (lambdaExpression);
			}

			public static IList<Statement> Collect (AstNode variableDecl)
			{
				return new AnalysisStatementCollector (variableDecl).GetStatements ();
			}
		}

		class GatherVisitor : GatherVisitorBase<MultipleEnumerationIssue>
		{
			HashSet<AstNode> collectedAstNodes;

			public GatherVisitor (BaseRefactoringContext ctx)
				: base (ctx)
			{
				this.collectedAstNodes = new HashSet<AstNode> ();
			}

			void AddIssue (AstNode node)
			{
				if (collectedAstNodes.Add (node))
					AddIssue (node, ctx.TranslateString ("Possible multiple enumeration of IEnumerable"));
			}

			void AddIssues (IEnumerable<AstNode> nodes)
			{
				foreach (var node in nodes)
					AddIssue (node);
			}

			public override void VisitParameterDeclaration (ParameterDeclaration parameterDeclaration)
			{
				base.VisitParameterDeclaration (parameterDeclaration);

				var resolveResult = ctx.Resolve (parameterDeclaration) as LocalResolveResult;
				CollectIssues (parameterDeclaration, parameterDeclaration.Parent, resolveResult);
			}

			public override void VisitVariableInitializer (VariableInitializer variableInitializer)
			{
				base.VisitVariableInitializer (variableInitializer);

				var resolveResult = ctx.Resolve (variableInitializer) as LocalResolveResult;
				CollectIssues (variableInitializer, variableInitializer.Parent.Parent, resolveResult);
			}

			static bool IsAssignment (AstNode node)
			{
				var assignment = node.Parent as AssignmentExpression;
				if (assignment != null)
					return assignment.Left == node;

				var direction = node.Parent as DirectionExpression;
				if (direction != null)
					return direction.FieldDirection == FieldDirection.Out && direction.Expression == node;

				return false;
			}

			bool IsEnumeration (AstNode node)
			{
				var foreachStatement = node.Parent as ForeachStatement;
				if (foreachStatement != null && foreachStatement.InExpression == node) {
					return true;
				}

				var memberRef = node.Parent as MemberReferenceExpression;
				if (memberRef != null && memberRef.Target == node) {
					var invocation = memberRef.Parent as InvocationExpression;
					if (invocation == null || invocation.Target != memberRef)
						return false;

					var methodGroup = ctx.Resolve (memberRef) as MethodGroupResolveResult;
					if (methodGroup == null)
						return false;

					var method = methodGroup.Methods.FirstOrDefault ();
					if (method != null) {
						var declaringTypeDef = method.DeclaringTypeDefinition;
						if (declaringTypeDef != null && declaringTypeDef.KnownTypeCode == KnownTypeCode.Object)
							return false;
					}
					return true;
				}

				return false;
			}

			HashSet<AstNode> references;
			HashSet<Statement> refStatements;
			HashSet<LambdaExpression> lambdaExpressions;

			HashSet<VariableReferenceNode> visitedNodes;
			HashSet<VariableReferenceNode> collectedNodes;
			Dictionary<VariableReferenceNode, int> nodeDegree; // number of enumerations a node can reach

			void FindReferences (AstNode variableDecl, AstNode rootNode, IVariable variable)
			{
				references = new HashSet<AstNode> ();
				refStatements = new HashSet<Statement> ();
				lambdaExpressions = new HashSet<LambdaExpression> ();

				foreach (var result in ctx.FindReferences (rootNode, variable)) {
					var astNode = result.Node;
					if (astNode == variableDecl)
						continue;

					var parent = astNode.Parent;
					while (!(parent == null || parent is Statement || parent is LambdaExpression))
						parent = parent.Parent;
					if (parent == null)
						continue;

					// lambda expression with expression body, should be analyzed separately
					var expr = parent as LambdaExpression;
					if (expr != null) {
						if (IsAssignment (astNode) || IsEnumeration (astNode)) {
							references.Add (astNode);
							lambdaExpressions.Add (expr);
						}
						continue;
					}

					if (IsAssignment (astNode) || IsEnumeration (astNode)) {
						references.Add (astNode);
						var statement = (Statement)parent;
						refStatements.Add (statement);
					}
				}
			}

			void CollectIssues (AstNode variableDecl, AstNode rootNode, LocalResolveResult resolveResult)
			{
				if (resolveResult == null)
					return;
				var type = resolveResult.Type;
				var typeDef = type.GetDefinition ();
				if (typeDef == null ||
				    (typeDef.KnownTypeCode != KnownTypeCode.IEnumerable &&
				     typeDef.KnownTypeCode != KnownTypeCode.IEnumerableOfT))
					return;

				FindReferences (variableDecl, rootNode, resolveResult.Variable);

				var statements = AnalysisStatementCollector.Collect (variableDecl);
				var builder = new VariableReferenceGraphBuilder (ctx);
				foreach (var statement in statements) {
					var vrNode = builder.Build (statement, references, refStatements, ctx);
					FindMultipleEnumeration (vrNode);
				}
				foreach (var lambda in lambdaExpressions) {
					var vrNode = builder.Build (references, ctx.Resolver, (Expression)lambda.Body);
					FindMultipleEnumeration (vrNode);
				}
			}

			/// <summary>
			/// split references in the specified node into sub nodes according to the value they uses
			/// </summary>
			/// <param name="node">node to split</param>
			/// <returns>list of sub nodes</returns>
			static IList<VariableReferenceNode> SplitNode (VariableReferenceNode node)
			{
				var subNodes = new List<VariableReferenceNode> ();
				// find indices of all assignments in node and use them to split references
				var assignmentIndices = new List<int> { -1 };
				for (int i = 0; i < node.References.Count; i++) {
					if (IsAssignment (node.References [i]))
						assignmentIndices.Add (i);
				}
				assignmentIndices.Add (node.References.Count);
				for (int i = 0; i < assignmentIndices.Count - 1; i++) {
					var index1 = assignmentIndices [i];
					var index2 = assignmentIndices [i + 1];
					if (index1 + 1 >= index2)
						continue;
					var subNode = new VariableReferenceNode ();
					for (int refIndex = index1 + 1; refIndex < index2; refIndex++)
						subNode.References.Add (node.References [refIndex]);
					subNodes.Add (subNode);
				}
				if (subNodes.Count == 0)
					subNodes.Add (new VariableReferenceNode ());

				var firstNode = subNodes [0];
				foreach (var prevNode in node.PreviousNodes) {
					prevNode.NextNodes.Remove (node);
					// connect two nodes if the first ref is not an assignment
					if (firstNode.References.FirstOrDefault () == node.References.FirstOrDefault ())
						prevNode.NextNodes.Add (firstNode);
				}

				var lastNode = subNodes [subNodes.Count - 1];
				foreach (var nextNode in node.NextNodes) {
					nextNode.PreviousNodes.Remove (node);
					lastNode.AddNextNode (nextNode);
				}

				return subNodes;
			}

			/// <summary>
			/// convert a variable reference graph starting from the specified node to an assignment usage graph,
			/// in which nodes are connect if and only if they contains references using the same assigned value
			/// </summary>
			/// <param name="startNode">starting node of the variable reference graph</param>
			/// <returns>
			/// list of VariableReferenceNode, each of which is a starting node of a sub-graph in which references all
			/// use the same assigned value
			/// </returns>
			static IEnumerable<VariableReferenceNode> GetAssignmentUsageGraph (VariableReferenceNode startNode)
			{
				var graph = new List<VariableReferenceNode> ();
				var visited = new HashSet<VariableReferenceNode> ();
				var stack = new Stack<VariableReferenceNode> ();
				stack.Push (startNode);
				while (stack.Count > 0) {
					var node = stack.Pop ();
					if (!visited.Add (node))
						continue;

					var nodes = SplitNode (node);
					graph.AddRange (nodes);
					foreach (var addedNode in nodes)
						visited.Add (addedNode);

					foreach (var nextNode in nodes.Last ().NextNodes)
						stack.Push (nextNode);
				}
				return graph;
			}

			void FindMultipleEnumeration (VariableReferenceNode startNode)
			{
				var vrg = GetAssignmentUsageGraph (startNode);
				visitedNodes = new HashSet<VariableReferenceNode> ();
				collectedNodes = new HashSet<VariableReferenceNode> ();

				// degree of a node is the number of references that can be reached by the node
				nodeDegree = new Dictionary<VariableReferenceNode, int> ();

				foreach (var node in vrg) {
					if (node.References.Count == 0 || !visitedNodes.Add (node))
						continue;
					ProcessNode (node);
					if (nodeDegree [node] > 1)
						collectedNodes.Add (node);
				}
				foreach (var node in collectedNodes)
					AddIssues (node.References);
			}

			void ProcessNode (VariableReferenceNode node)
			{
				var degree = nodeDegree [node] = 0;
				foreach (var nextNode in node.NextNodes) {
					collectedNodes.Add (nextNode);
					if (visitedNodes.Add (nextNode))
						ProcessNode (nextNode);
					degree = Math.Max (degree, nodeDegree [nextNode]);
				}
				nodeDegree [node] = degree + node.References.Count;
			}
		}
	}
}