PageRenderTime 52ms CodeModel.GetById 13ms app.highlight 32ms RepoModel.GetById 2ms app.codeStats 0ms

/ICSharpCode.Decompiler/Ast/Transforms/IntroduceQueryExpressions.cs

http://github.com/icsharpcode/ILSpy
C# | 295 lines | 250 code | 12 blank | 33 comment | 95 complexity | 19e523c64e1e36642cf90aaaf9b3cbe6 MD5 | raw file
  1// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
  2// 
  3// Permission is hereby granted, free of charge, to any person obtaining a copy of this
  4// software and associated documentation files (the "Software"), to deal in the Software
  5// without restriction, including without limitation the rights to use, copy, modify, merge,
  6// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
  7// to whom the Software is furnished to do so, subject to the following conditions:
  8// 
  9// The above copyright notice and this permission notice shall be included in all copies or
 10// substantial portions of the Software.
 11// 
 12// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 13// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 14// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
 15// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 16// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 17// DEALINGS IN THE SOFTWARE.
 18
 19using System;
 20using System.Diagnostics;
 21using System.Linq;
 22using ICSharpCode.NRefactory.CSharp;
 23
 24namespace ICSharpCode.Decompiler.Ast.Transforms
 25{
 26	/// <summary>
 27	/// Decompiles query expressions.
 28	/// Based on C# 4.0 spec, ยง7.16.2 Query expression translation
 29	/// </summary>
 30	public class IntroduceQueryExpressions : IAstTransform
 31	{
 32		readonly DecompilerContext context;
 33		
 34		public IntroduceQueryExpressions(DecompilerContext context)
 35		{
 36			this.context = context;
 37		}
 38		
 39		public void Run(AstNode compilationUnit)
 40		{
 41			if (!context.Settings.QueryExpressions)
 42				return;
 43			DecompileQueries(compilationUnit);
 44			// After all queries were decompiled, detect degenerate queries (queries not property terminated with 'select' or 'group')
 45			// and fix them, either by adding a degenerate select, or by combining them with another query.
 46			foreach (QueryExpression query in compilationUnit.Descendants.OfType<QueryExpression>()) {
 47				QueryFromClause fromClause = (QueryFromClause)query.Clauses.First();
 48				if (IsDegenerateQuery(query)) {
 49					// introduce select for degenerate query
 50					query.Clauses.Add(new QuerySelectClause { Expression = new IdentifierExpression(fromClause.Identifier) });
 51				}
 52				// See if the data source of this query is a degenerate query,
 53				// and combine the queries if possible.
 54				QueryExpression innerQuery = fromClause.Expression as QueryExpression;
 55				while (IsDegenerateQuery(innerQuery)) {
 56					QueryFromClause innerFromClause = (QueryFromClause)innerQuery.Clauses.First();
 57					if (fromClause.Identifier != innerFromClause.Identifier)
 58						break;
 59					// Replace the fromClause with all clauses from the inner query
 60					fromClause.Remove();
 61					QueryClause insertionPos = null;
 62					foreach (var clause in innerQuery.Clauses) {
 63						query.Clauses.InsertAfter(insertionPos, insertionPos = clause.Detach());
 64					}
 65					fromClause = innerFromClause;
 66					innerQuery = fromClause.Expression as QueryExpression;
 67				}
 68			}
 69		}
 70		
 71		bool IsDegenerateQuery(QueryExpression query)
 72		{
 73			if (query == null)
 74				return false;
 75			var lastClause = query.Clauses.LastOrDefault();
 76			return !(lastClause is QuerySelectClause || lastClause is QueryGroupClause);
 77		}
 78		
 79		void DecompileQueries(AstNode node)
 80		{
 81			QueryExpression query = DecompileQuery(node as InvocationExpression);
 82			if (query != null)
 83				node.ReplaceWith(query);
 84			for (AstNode child = (query ?? node).FirstChild; child != null; child = child.NextSibling) {
 85				DecompileQueries(child);
 86			}
 87		}
 88		
 89		QueryExpression DecompileQuery(InvocationExpression invocation)
 90		{
 91			if (invocation == null)
 92				return null;
 93			MemberReferenceExpression mre = invocation.Target as MemberReferenceExpression;
 94			if (mre == null)
 95				return null;
 96			switch (mre.MemberName) {
 97				case "Select":
 98					{
 99						if (invocation.Arguments.Count != 1)
100							return null;
101						string parameterName;
102						Expression body;
103						if (MatchSimpleLambda(invocation.Arguments.Single(), out parameterName, out body)) {
104							QueryExpression query = new QueryExpression();
105							query.Clauses.Add(new QueryFromClause { Identifier = parameterName, Expression = mre.Target.Detach() });
106							query.Clauses.Add(new QuerySelectClause { Expression = body.Detach() });
107							return query;
108						}
109						return null;
110					}
111				case "GroupBy":
112					{
113						if (invocation.Arguments.Count == 2) {
114							string parameterName1, parameterName2;
115							Expression keySelector, elementSelector;
116							if (MatchSimpleLambda(invocation.Arguments.ElementAt(0), out parameterName1, out keySelector)
117							    && MatchSimpleLambda(invocation.Arguments.ElementAt(1), out parameterName2, out elementSelector)
118							    && parameterName1 == parameterName2)
119							{
120								QueryExpression query = new QueryExpression();
121								query.Clauses.Add(new QueryFromClause { Identifier = parameterName1, Expression = mre.Target.Detach() });
122								query.Clauses.Add(new QueryGroupClause { Projection = elementSelector.Detach(), Key = keySelector.Detach() });
123								return query;
124							}
125						} else if (invocation.Arguments.Count == 1) {
126							string parameterName;
127							Expression keySelector;
128							if (MatchSimpleLambda(invocation.Arguments.Single(), out parameterName, out keySelector)) {
129								QueryExpression query = new QueryExpression();
130								query.Clauses.Add(new QueryFromClause { Identifier = parameterName, Expression = mre.Target.Detach() });
131								query.Clauses.Add(new QueryGroupClause { Projection = new IdentifierExpression(parameterName), Key = keySelector.Detach() });
132								return query;
133							}
134						}
135						return null;
136					}
137				case "SelectMany":
138					{
139						if (invocation.Arguments.Count != 2)
140							return null;
141						string parameterName;
142						Expression collectionSelector;
143						if (!MatchSimpleLambda(invocation.Arguments.ElementAt(0), out parameterName, out collectionSelector))
144							return null;
145						LambdaExpression lambda = invocation.Arguments.ElementAt(1) as LambdaExpression;
146						if (lambda != null && lambda.Parameters.Count == 2 && lambda.Body is Expression) {
147							ParameterDeclaration p1 = lambda.Parameters.ElementAt(0);
148							ParameterDeclaration p2 = lambda.Parameters.ElementAt(1);
149							if (p1.Name == parameterName) {
150								QueryExpression query = new QueryExpression();
151								query.Clauses.Add(new QueryFromClause { Identifier = p1.Name, Expression = mre.Target.Detach() });
152								query.Clauses.Add(new QueryFromClause { Identifier = p2.Name, Expression = collectionSelector.Detach() });
153								query.Clauses.Add(new QuerySelectClause { Expression = ((Expression)lambda.Body).Detach() });
154								return query;
155							}
156						}
157						return null;
158					}
159				case "Where":
160					{
161						if (invocation.Arguments.Count != 1)
162							return null;
163						string parameterName;
164						Expression body;
165						if (MatchSimpleLambda(invocation.Arguments.Single(), out parameterName, out body)) {
166							QueryExpression query = new QueryExpression();
167							query.Clauses.Add(new QueryFromClause { Identifier = parameterName, Expression = mre.Target.Detach() });
168							query.Clauses.Add(new QueryWhereClause { Condition = body.Detach() });
169							return query;
170						}
171						return null;
172					}
173				case "OrderBy":
174				case "OrderByDescending":
175				case "ThenBy":
176				case "ThenByDescending":
177					{
178						if (invocation.Arguments.Count != 1)
179							return null;
180						string parameterName;
181						Expression orderExpression;
182						if (MatchSimpleLambda(invocation.Arguments.Single(), out parameterName, out orderExpression)) {
183							if (ValidateThenByChain(invocation, parameterName)) {
184								QueryOrderClause orderClause = new QueryOrderClause();
185								InvocationExpression tmp = invocation;
186								while (mre.MemberName == "ThenBy" || mre.MemberName == "ThenByDescending") {
187									// insert new ordering at beginning
188									orderClause.Orderings.InsertAfter(
189										null, new QueryOrdering {
190											Expression = orderExpression.Detach(),
191											Direction = (mre.MemberName == "ThenBy" ? QueryOrderingDirection.None : QueryOrderingDirection.Descending)
192										});
193									
194									tmp = (InvocationExpression)mre.Target;
195									mre = (MemberReferenceExpression)tmp.Target;
196									MatchSimpleLambda(tmp.Arguments.Single(), out parameterName, out orderExpression);
197								}
198								// insert new ordering at beginning
199								orderClause.Orderings.InsertAfter(
200									null, new QueryOrdering {
201										Expression = orderExpression.Detach(),
202										Direction = (mre.MemberName == "OrderBy" ? QueryOrderingDirection.None : QueryOrderingDirection.Descending)
203									});
204								
205								QueryExpression query = new QueryExpression();
206								query.Clauses.Add(new QueryFromClause { Identifier = parameterName, Expression = mre.Target.Detach() });
207								query.Clauses.Add(orderClause);
208								return query;
209							}
210						}
211						return null;
212					}
213				case "Join":
214				case "GroupJoin":
215					{
216						if (invocation.Arguments.Count != 4)
217							return null;
218						Expression source1 = mre.Target;
219						Expression source2 = invocation.Arguments.ElementAt(0);
220						string elementName1, elementName2;
221						Expression key1, key2;
222						if (!MatchSimpleLambda(invocation.Arguments.ElementAt(1), out elementName1, out key1))
223							return null;
224						if (!MatchSimpleLambda(invocation.Arguments.ElementAt(2), out elementName2, out key2))
225							return null;
226						LambdaExpression lambda = invocation.Arguments.ElementAt(3) as LambdaExpression;
227						if (lambda != null && lambda.Parameters.Count == 2 && lambda.Body is Expression) {
228							ParameterDeclaration p1 = lambda.Parameters.ElementAt(0);
229							ParameterDeclaration p2 = lambda.Parameters.ElementAt(1);
230							if (p1.Name == elementName1 && (p2.Name == elementName2 || mre.MemberName == "GroupJoin")) {
231								QueryExpression query = new QueryExpression();
232								query.Clauses.Add(new QueryFromClause { Identifier = elementName1, Expression = source1.Detach() });
233								QueryJoinClause joinClause = new QueryJoinClause();
234								joinClause.JoinIdentifier = elementName2;    // join elementName2
235								joinClause.InExpression = source2.Detach();  // in source2
236								joinClause.OnExpression = key1.Detach();     // on key1
237								joinClause.EqualsExpression = key2.Detach(); // equals key2
238								if (mre.MemberName == "GroupJoin") {
239									joinClause.IntoIdentifier = p2.Name; // into p2.Name
240								}
241								query.Clauses.Add(joinClause);
242								query.Clauses.Add(new QuerySelectClause { Expression = ((Expression)lambda.Body).Detach() });
243								return query;
244							}
245						}
246						return null;
247					}
248				default:
249					return null;
250			}
251		}
252		
253		/// <summary>
254		/// Ensure that all ThenBy's are correct, and that the list of ThenBy's is terminated by an 'OrderBy' invocation.
255		/// </summary>
256		bool ValidateThenByChain(InvocationExpression invocation, string expectedParameterName)
257		{
258			if (invocation == null || invocation.Arguments.Count != 1)
259				return false;
260			MemberReferenceExpression mre = invocation.Target as MemberReferenceExpression;
261			if (mre == null)
262				return false;
263			string parameterName;
264			Expression body;
265			if (!MatchSimpleLambda(invocation.Arguments.Single(), out parameterName, out body))
266				return false;
267			if (parameterName != expectedParameterName)
268				return false;
269			
270			if (mre.MemberName == "OrderBy" || mre.MemberName == "OrderByDescending")
271				return true;
272			else if (mre.MemberName == "ThenBy" || mre.MemberName == "ThenByDescending")
273				return ValidateThenByChain(mre.Target as InvocationExpression, expectedParameterName);
274			else
275				return false;
276		}
277		
278		/// <summary>Matches simple lambdas of the form "a => b"</summary>
279		bool MatchSimpleLambda(Expression expr, out string parameterName, out Expression body)
280		{
281			LambdaExpression lambda = expr as LambdaExpression;
282			if (lambda != null && lambda.Parameters.Count == 1 && lambda.Body is Expression) {
283				ParameterDeclaration p = lambda.Parameters.Single();
284				if (p.ParameterModifier == ParameterModifier.None) {
285					parameterName = p.Name;
286					body = (Expression)lambda.Body;
287					return true;
288				}
289			}
290			parameterName = null;
291			body = null;
292			return false;
293		}
294	}
295}