Browse Source

Add LetIdentifierAnnotation to allow linking of let variables.

pull/1405/head
Siegfried Pammer 7 years ago
parent
commit
1d2cd930de
  1. 35
      ICSharpCode.Decompiler/CSharp/Transforms/CombineQueryExpressions.cs
  2. 109
      ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs
  3. 10
      ICSharpCode.Decompiler/Output/TextTokenWriter.cs

35
ICSharpCode.Decompiler/CSharp/Transforms/CombineQueryExpressions.cs

@ -17,6 +17,7 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using ICSharpCode.Decompiler.CSharp.Syntax; using ICSharpCode.Decompiler.CSharp.Syntax;
using ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching; using ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching;
@ -32,7 +33,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
{ {
if (!context.Settings.QueryExpressions) if (!context.Settings.QueryExpressions)
return; return;
CombineQueries(rootNode); CombineQueries(rootNode, new Dictionary<string, object>());
} }
static readonly InvocationExpression castPattern = new InvocationExpression { static readonly InvocationExpression castPattern = new InvocationExpression {
@ -42,18 +43,18 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
TypeArguments = { new AnyNode("targetType") } TypeArguments = { new AnyNode("targetType") }
}}; }};
void CombineQueries(AstNode node) void CombineQueries(AstNode node, Dictionary<string, object> letIdentifiers)
{ {
for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) { for (AstNode child = node.FirstChild; child != null; child = child.NextSibling) {
CombineQueries(child); CombineQueries(child, letIdentifiers);
} }
QueryExpression query = node as QueryExpression; QueryExpression query = node as QueryExpression;
if (query != null) { if (query != null) {
QueryFromClause fromClause = (QueryFromClause)query.Clauses.First(); QueryFromClause fromClause = (QueryFromClause)query.Clauses.First();
QueryExpression innerQuery = fromClause.Expression as QueryExpression; QueryExpression innerQuery = fromClause.Expression as QueryExpression;
if (innerQuery != null) { if (innerQuery != null) {
if (TryRemoveTransparentIdentifier(query, fromClause, innerQuery)) { if (TryRemoveTransparentIdentifier(query, fromClause, innerQuery, letIdentifiers)) {
RemoveTransparentIdentifierReferences(query); RemoveTransparentIdentifierReferences(query, letIdentifiers);
} else { } else {
QueryContinuationClause continuation = new QueryContinuationClause(); QueryContinuationClause continuation = new QueryContinuationClause();
continuation.PrecedingQuery = innerQuery.Detach(); continuation.PrecedingQuery = innerQuery.Detach();
@ -91,7 +92,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
return identifier.StartsWith("<>", StringComparison.Ordinal) && (identifier.Contains("TransparentIdentifier") || identifier.Contains("TranspIdent")); return identifier.StartsWith("<>", StringComparison.Ordinal) && (identifier.Contains("TransparentIdentifier") || identifier.Contains("TranspIdent"));
} }
bool TryRemoveTransparentIdentifier(QueryExpression query, QueryFromClause fromClause, QueryExpression innerQuery) bool TryRemoveTransparentIdentifier(QueryExpression query, QueryFromClause fromClause, QueryExpression innerQuery, Dictionary<string, object> letClauses)
{ {
if (!IsTransparentIdentifier(fromClause.Identifier)) if (!IsTransparentIdentifier(fromClause.Identifier))
return false; return false;
@ -117,9 +118,15 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
// nothing to add // nothing to add
continue; continue;
case NamedExpression namedExpression: case NamedExpression namedExpression:
if (namedExpression.Expression is IdentifierExpression identifierExpression && namedExpression.Name == identifierExpression.Identifier) if (namedExpression.Expression is IdentifierExpression identifierExpression && namedExpression.Name == identifierExpression.Identifier) {
letClauses[namedExpression.Name] = identifierExpression.Annotation<ILVariableResolveResult>();
continue; continue;
query.Clauses.InsertAfter(insertionPos, new QueryLetClause { Identifier = namedExpression.Name, Expression = namedExpression.Expression.Detach() }); }
QueryLetClause letClause = new QueryLetClause { Identifier = namedExpression.Name, Expression = namedExpression.Expression.Detach() };
var annotation = new LetIdentifierAnnotation();
letClause.AddAnnotation(annotation);
letClauses[namedExpression.Name] = annotation;
query.Clauses.InsertAfter(insertionPos, letClause);
break; break;
} }
} }
@ -129,10 +136,10 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
/// <summary> /// <summary>
/// Removes all occurrences of transparent identifiers /// Removes all occurrences of transparent identifiers
/// </summary> /// </summary>
void RemoveTransparentIdentifierReferences(AstNode node) void RemoveTransparentIdentifierReferences(AstNode node, Dictionary<string, object> letClauses)
{ {
foreach (AstNode child in node.Children) { foreach (AstNode child in node.Children) {
RemoveTransparentIdentifierReferences(child); RemoveTransparentIdentifierReferences(child, letClauses);
} }
MemberReferenceExpression mre = node as MemberReferenceExpression; MemberReferenceExpression mre = node as MemberReferenceExpression;
if (mre != null) { if (mre != null) {
@ -141,11 +148,17 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
IdentifierExpression newIdent = new IdentifierExpression(mre.MemberName); IdentifierExpression newIdent = new IdentifierExpression(mre.MemberName);
mre.TypeArguments.MoveTo(newIdent.TypeArguments); mre.TypeArguments.MoveTo(newIdent.TypeArguments);
newIdent.CopyAnnotationsFrom(mre); newIdent.CopyAnnotationsFrom(mre);
newIdent.RemoveAnnotations<PropertyDeclaration>(); // remove the reference to the property of the anonymous type newIdent.RemoveAnnotations<Semantics.MemberResolveResult>(); // remove the reference to the property of the anonymous type
if (letClauses.TryGetValue(mre.MemberName, out var annotation))
newIdent.AddAnnotation(annotation);
mre.ReplaceWith(newIdent); mre.ReplaceWith(newIdent);
return; return;
} }
} }
} }
} }
public class LetIdentifierAnnotation
{
}
} }

109
ICSharpCode.Decompiler/CSharp/Transforms/IntroduceQueryExpressions.cs

@ -40,7 +40,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
QueryFromClause fromClause = (QueryFromClause)query.Clauses.First(); QueryFromClause fromClause = (QueryFromClause)query.Clauses.First();
if (IsDegenerateQuery(query)) { if (IsDegenerateQuery(query)) {
// introduce select for degenerate query // introduce select for degenerate query
query.Clauses.Add(new QuerySelectClause { Expression = new IdentifierExpression(fromClause.Identifier) }); query.Clauses.Add(new QuerySelectClause { Expression = new IdentifierExpression(fromClause.Identifier).CopyAnnotationsFrom(fromClause) });
} }
// See if the data source of this query is a degenerate query, // See if the data source of this query is a degenerate query,
// and combine the queries if possible. // and combine the queries if possible.
@ -94,12 +94,12 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
{ {
if (invocation.Arguments.Count != 1) if (invocation.Arguments.Count != 1)
return null; return null;
string parameterName; ParameterDeclaration parameter;
Expression body; Expression body;
if (MatchSimpleLambda(invocation.Arguments.Single(), out parameterName, out body)) { if (MatchSimpleLambda(invocation.Arguments.Single(), out parameter, out body)) {
QueryExpression query = new QueryExpression(); QueryExpression query = new QueryExpression();
query.Clauses.Add(new QueryFromClause { Identifier = parameterName, Expression = mre.Target.Detach() }); query.Clauses.Add(MakeFromClause(parameter, mre.Target.Detach()));
query.Clauses.Add(new QuerySelectClause { Expression = WrapExpressionInParenthesesIfNecessary(body.Detach(), parameterName) }); query.Clauses.Add(new QuerySelectClause { Expression = WrapExpressionInParenthesesIfNecessary(body.Detach(), parameter.Name) });
return query; return query;
} }
return null; return null;
@ -107,24 +107,24 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
case "GroupBy": case "GroupBy":
{ {
if (invocation.Arguments.Count == 2) { if (invocation.Arguments.Count == 2) {
string parameterName1, parameterName2; ParameterDeclaration parameter1, parameter2;
Expression keySelector, elementSelector; Expression keySelector, elementSelector;
if (MatchSimpleLambda(invocation.Arguments.ElementAt(0), out parameterName1, out keySelector) if (MatchSimpleLambda(invocation.Arguments.ElementAt(0), out parameter1, out keySelector)
&& MatchSimpleLambda(invocation.Arguments.ElementAt(1), out parameterName2, out elementSelector) && MatchSimpleLambda(invocation.Arguments.ElementAt(1), out parameter2, out elementSelector)
&& parameterName1 == parameterName2) && parameter1.Name == parameter2.Name)
{ {
QueryExpression query = new QueryExpression(); QueryExpression query = new QueryExpression();
query.Clauses.Add(new QueryFromClause { Identifier = parameterName1, Expression = mre.Target.Detach() }); query.Clauses.Add(MakeFromClause(parameter1, mre.Target.Detach()));
query.Clauses.Add(new QueryGroupClause { Projection = elementSelector.Detach(), Key = keySelector.Detach() }); query.Clauses.Add(new QueryGroupClause { Projection = elementSelector.Detach(), Key = keySelector.Detach() });
return query; return query;
} }
} else if (invocation.Arguments.Count == 1) { } else if (invocation.Arguments.Count == 1) {
string parameterName; ParameterDeclaration parameter;
Expression keySelector; Expression keySelector;
if (MatchSimpleLambda(invocation.Arguments.Single(), out parameterName, out keySelector)) { if (MatchSimpleLambda(invocation.Arguments.Single(), out parameter, out keySelector)) {
QueryExpression query = new QueryExpression(); QueryExpression query = new QueryExpression();
query.Clauses.Add(new QueryFromClause { Identifier = parameterName, Expression = mre.Target.Detach() }); query.Clauses.Add(MakeFromClause(parameter, mre.Target.Detach()));
query.Clauses.Add(new QueryGroupClause { Projection = new IdentifierExpression(parameterName), Key = keySelector.Detach() }); query.Clauses.Add(new QueryGroupClause { Projection = new IdentifierExpression(parameter.Name).CopyAnnotationsFrom(parameter), Key = keySelector.Detach() });
return query; return query;
} }
} }
@ -134,9 +134,9 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
{ {
if (invocation.Arguments.Count != 2) if (invocation.Arguments.Count != 2)
return null; return null;
string parameterName; ParameterDeclaration parameter;
Expression collectionSelector; Expression collectionSelector;
if (!MatchSimpleLambda(invocation.Arguments.ElementAt(0), out parameterName, out collectionSelector)) if (!MatchSimpleLambda(invocation.Arguments.ElementAt(0), out parameter, out collectionSelector))
return null; return null;
if (IsNullConditional(collectionSelector)) if (IsNullConditional(collectionSelector))
return null; return null;
@ -144,11 +144,11 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
if (lambda != null && lambda.Parameters.Count == 2 && lambda.Body is Expression) { if (lambda != null && lambda.Parameters.Count == 2 && lambda.Body is Expression) {
ParameterDeclaration p1 = lambda.Parameters.ElementAt(0); ParameterDeclaration p1 = lambda.Parameters.ElementAt(0);
ParameterDeclaration p2 = lambda.Parameters.ElementAt(1); ParameterDeclaration p2 = lambda.Parameters.ElementAt(1);
if (p1.Name == parameterName) { if (p1.Name == parameter.Name) {
QueryExpression query = new QueryExpression(); QueryExpression query = new QueryExpression();
query.Clauses.Add(new QueryFromClause { Identifier = p1.Name, Expression = mre.Target.Detach() }); query.Clauses.Add(MakeFromClause(p1, mre.Target.Detach()));
query.Clauses.Add(new QueryFromClause { Identifier = p2.Name, Expression = collectionSelector.Detach() }); query.Clauses.Add(MakeFromClause(p2, collectionSelector.Detach()));
query.Clauses.Add(new QuerySelectClause { Expression = WrapExpressionInParenthesesIfNecessary(((Expression)lambda.Body).Detach(), parameterName) }); query.Clauses.Add(new QuerySelectClause { Expression = WrapExpressionInParenthesesIfNecessary(((Expression)lambda.Body).Detach(), parameter.Name) });
return query; return query;
} }
} }
@ -158,11 +158,11 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
{ {
if (invocation.Arguments.Count != 1) if (invocation.Arguments.Count != 1)
return null; return null;
string parameterName; ParameterDeclaration parameter;
Expression body; Expression body;
if (MatchSimpleLambda(invocation.Arguments.Single(), out parameterName, out body)) { if (MatchSimpleLambda(invocation.Arguments.Single(), out parameter, out body)) {
QueryExpression query = new QueryExpression(); QueryExpression query = new QueryExpression();
query.Clauses.Add(new QueryFromClause { Identifier = parameterName, Expression = mre.Target.Detach() }); query.Clauses.Add(MakeFromClause(parameter, mre.Target.Detach()));
query.Clauses.Add(new QueryWhereClause { Condition = body.Detach() }); query.Clauses.Add(new QueryWhereClause { Condition = body.Detach() });
return query; return query;
} }
@ -175,10 +175,10 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
{ {
if (invocation.Arguments.Count != 1) if (invocation.Arguments.Count != 1)
return null; return null;
string parameterName; ParameterDeclaration parameter;
Expression orderExpression; Expression orderExpression;
if (MatchSimpleLambda(invocation.Arguments.Single(), out parameterName, out orderExpression)) { if (MatchSimpleLambda(invocation.Arguments.Single(), out parameter, out orderExpression)) {
if (ValidateThenByChain(invocation, parameterName)) { if (ValidateThenByChain(invocation, parameter.Name)) {
QueryOrderClause orderClause = new QueryOrderClause(); QueryOrderClause orderClause = new QueryOrderClause();
InvocationExpression tmp = invocation; InvocationExpression tmp = invocation;
while (mre.MemberName == "ThenBy" || mre.MemberName == "ThenByDescending") { while (mre.MemberName == "ThenBy" || mre.MemberName == "ThenByDescending") {
@ -191,7 +191,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
tmp = (InvocationExpression)mre.Target; tmp = (InvocationExpression)mre.Target;
mre = (MemberReferenceExpression)tmp.Target; mre = (MemberReferenceExpression)tmp.Target;
MatchSimpleLambda(tmp.Arguments.Single(), out parameterName, out orderExpression); MatchSimpleLambda(tmp.Arguments.Single(), out parameter, out orderExpression);
} }
// insert new ordering at beginning // insert new ordering at beginning
orderClause.Orderings.InsertAfter( orderClause.Orderings.InsertAfter(
@ -201,7 +201,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
}); });
QueryExpression query = new QueryExpression(); QueryExpression query = new QueryExpression();
query.Clauses.Add(new QueryFromClause { Identifier = parameterName, Expression = mre.Target.Detach() }); query.Clauses.Add(MakeFromClause(parameter, mre.Target.Detach()));
query.Clauses.Add(orderClause); query.Clauses.Add(orderClause);
return query; return query;
} }
@ -217,21 +217,21 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
Expression source2 = invocation.Arguments.ElementAt(0); Expression source2 = invocation.Arguments.ElementAt(0);
if (IsNullConditional(source2)) if (IsNullConditional(source2))
return null; return null;
string elementName1, elementName2; ParameterDeclaration element1, element2;
Expression key1, key2; Expression key1, key2;
if (!MatchSimpleLambda(invocation.Arguments.ElementAt(1), out elementName1, out key1)) if (!MatchSimpleLambda(invocation.Arguments.ElementAt(1), out element1, out key1))
return null; return null;
if (!MatchSimpleLambda(invocation.Arguments.ElementAt(2), out elementName2, out key2)) if (!MatchSimpleLambda(invocation.Arguments.ElementAt(2), out element2, out key2))
return null; return null;
LambdaExpression lambda = invocation.Arguments.ElementAt(3) as LambdaExpression; LambdaExpression lambda = invocation.Arguments.ElementAt(3) as LambdaExpression;
if (lambda != null && lambda.Parameters.Count == 2 && lambda.Body is Expression) { if (lambda != null && lambda.Parameters.Count == 2 && lambda.Body is Expression) {
ParameterDeclaration p1 = lambda.Parameters.ElementAt(0); ParameterDeclaration p1 = lambda.Parameters.ElementAt(0);
ParameterDeclaration p2 = lambda.Parameters.ElementAt(1); ParameterDeclaration p2 = lambda.Parameters.ElementAt(1);
if (p1.Name == elementName1 && (p2.Name == elementName2 || mre.MemberName == "GroupJoin")) { if (p1.Name == element1.Name && (p2.Name == element2.Name || mre.MemberName == "GroupJoin")) {
QueryExpression query = new QueryExpression(); QueryExpression query = new QueryExpression();
query.Clauses.Add(new QueryFromClause { Identifier = elementName1, Expression = source1.Detach() }); query.Clauses.Add(MakeFromClause(element1, source1.Detach()));
QueryJoinClause joinClause = new QueryJoinClause(); QueryJoinClause joinClause = new QueryJoinClause();
joinClause.JoinIdentifier = elementName2; // join elementName2 joinClause.JoinIdentifier = element2.Name; // join elementName2
joinClause.InExpression = source2.Detach(); // in source2 joinClause.InExpression = source2.Detach(); // in source2
joinClause.OnExpression = key1.Detach(); // on key1 joinClause.OnExpression = key1.Detach(); // on key1
joinClause.EqualsExpression = key2.Detach(); // equals key2 joinClause.EqualsExpression = key2.Detach(); // equals key2
@ -250,6 +250,35 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
} }
} }
QueryFromClause MakeFromClause(ParameterDeclaration parameter, Expression body)
{
QueryFromClause fromClause = new QueryFromClause {
Identifier = parameter.Name,
Expression = body
};
fromClause.CopyAnnotationsFrom(parameter);
return fromClause;
}
class ApplyAnnotationVisitor : DepthFirstAstVisitor<AstNode>
{
private LetIdentifierAnnotation annotation;
private string identifier;
public ApplyAnnotationVisitor(LetIdentifierAnnotation annotation, string identifier)
{
this.annotation = annotation;
this.identifier = identifier;
}
public override AstNode VisitIdentifier(Identifier identifier)
{
if (identifier.Name == this.identifier)
identifier.AddAnnotation(annotation);
return identifier;
}
}
bool IsNullConditional(Expression target) bool IsNullConditional(Expression target)
{ {
return target is UnaryOperatorExpression uoe && uoe.Operator == UnaryOperatorType.NullConditional; return target is UnaryOperatorExpression uoe && uoe.Operator == UnaryOperatorType.NullConditional;
@ -278,11 +307,11 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
MemberReferenceExpression mre = invocation.Target as MemberReferenceExpression; MemberReferenceExpression mre = invocation.Target as MemberReferenceExpression;
if (mre == null) if (mre == null)
return false; return false;
string parameterName; ParameterDeclaration parameter;
Expression body; Expression body;
if (!MatchSimpleLambda(invocation.Arguments.Single(), out parameterName, out body)) if (!MatchSimpleLambda(invocation.Arguments.Single(), out parameter, out body))
return false; return false;
if (parameterName != expectedParameterName) if (parameter.Name != expectedParameterName)
return false; return false;
if (mre.MemberName == "OrderBy" || mre.MemberName == "OrderByDescending") if (mre.MemberName == "OrderBy" || mre.MemberName == "OrderByDescending")
@ -294,7 +323,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
} }
/// <summary>Matches simple lambdas of the form "a => b"</summary> /// <summary>Matches simple lambdas of the form "a => b"</summary>
bool MatchSimpleLambda(Expression expr, out string parameterName, out Expression body) bool MatchSimpleLambda(Expression expr, out ParameterDeclaration parameter, out Expression body)
{ {
// HACK : remove workaround after all unnecessary casts are eliminated. // HACK : remove workaround after all unnecessary casts are eliminated.
LambdaExpression lambda; LambdaExpression lambda;
@ -305,12 +334,12 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
if (lambda != null && lambda.Parameters.Count == 1 && lambda.Body is Expression) { if (lambda != null && lambda.Parameters.Count == 1 && lambda.Body is Expression) {
ParameterDeclaration p = lambda.Parameters.Single(); ParameterDeclaration p = lambda.Parameters.Single();
if (p.ParameterModifier == ParameterModifier.None) { if (p.ParameterModifier == ParameterModifier.None) {
parameterName = p.Name; parameter = p;
body = (Expression)lambda.Body; body = (Expression)lambda.Body;
return true; return true;
} }
} }
parameterName = null; parameter = null;
body = null; body = null;
return false; return false;
} }

10
ICSharpCode.Decompiler/Output/TextTokenWriter.cs

@ -140,6 +140,10 @@ namespace ICSharpCode.Decompiler
if (variable != null) if (variable != null)
return variable; return variable;
var letClauseVariable = node.Annotation<CSharp.Transforms.LetIdentifierAnnotation>();
if (letClauseVariable != null)
return letClauseVariable;
var gotoStatement = node as GotoStatement; var gotoStatement = node as GotoStatement;
if (gotoStatement != null) if (gotoStatement != null)
{ {
@ -163,6 +167,12 @@ namespace ICSharpCode.Decompiler
return variable; return variable;
} }
if (node is QueryLetClause) {
var variable = node.Annotation<CSharp.Transforms.LetIdentifierAnnotation>();
if (variable != null)
return variable;
}
var label = node as LabelStatement; var label = node as LabelStatement;
if (label != null) { if (label != null) {
var method = nodeStack.Select(nd => nd.GetSymbol() as IMethod).FirstOrDefault(mr => mr != null); var method = nodeStack.Select(nd => nd.GetSymbol() as IMethod).FirstOrDefault(mr => mr != null);

Loading…
Cancel
Save