-
Notifications
You must be signed in to change notification settings - Fork 30
Refactor ExpressionSyntaxRewriter into focused partial class files #163
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
155 changes: 155 additions & 0 deletions
155
...ntityFrameworkCore.Projectables.Generator/ExpressionSyntaxRewriter.EnumMethodExpansion.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
|
|
||
| namespace EntityFrameworkCore.Projectables.Generator; | ||
|
|
||
| public partial class ExpressionSyntaxRewriter | ||
| { | ||
| private bool TryExpandEnumMethodCall(InvocationExpressionSyntax node, MemberAccessExpressionSyntax memberAccess, IMethodSymbol methodSymbol, out ExpressionSyntax? expandedExpression) | ||
| { | ||
| expandedExpression = null; | ||
|
|
||
| // Get the receiver expression (the enum instance or variable) | ||
| var receiverExpression = memberAccess.Expression; | ||
| var receiverTypeInfo = _semanticModel.GetTypeInfo(receiverExpression); | ||
| var receiverType = receiverTypeInfo.Type; | ||
|
|
||
| // Handle nullable enum types | ||
| ITypeSymbol enumType; | ||
| var isNullable = false; | ||
| if (receiverType is INamedTypeSymbol { IsGenericType: true, Name: "Nullable" } nullableType && | ||
| nullableType.TypeArguments.Length == 1 && | ||
| nullableType.TypeArguments[0].TypeKind == TypeKind.Enum) | ||
| { | ||
| enumType = nullableType.TypeArguments[0]; | ||
| isNullable = true; | ||
| } | ||
| else if (receiverType?.TypeKind == TypeKind.Enum) | ||
| { | ||
| enumType = receiverType; | ||
| } | ||
| else | ||
| { | ||
| // Not an enum type | ||
| return false; | ||
| } | ||
|
|
||
| // Get all enum members | ||
| var enumMembers = enumType.GetMembers() | ||
| .OfType<IFieldSymbol>() | ||
| .Where(f => f.HasConstantValue) | ||
| .ToList(); | ||
|
|
||
| if (enumMembers.Count == 0) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| // Visit the receiver expression to transform it (e.g., @this.MyProperty) | ||
| var visitedReceiver = (ExpressionSyntax)Visit(receiverExpression); | ||
|
|
||
| // Get the original method (in case of reduced extension method) | ||
| var originalMethod = methodSymbol.ReducedFrom ?? methodSymbol; | ||
|
|
||
| // Get the return type of the method to determine the default value | ||
| var returnType = methodSymbol.ReturnType; | ||
|
|
||
| // Build a chain of ternary expressions for each enum value | ||
| // Start with default(T) as the fallback for non-nullable types, or null for nullable/reference types | ||
| ExpressionSyntax defaultExpression; | ||
| if (returnType.IsReferenceType || returnType.NullableAnnotation == NullableAnnotation.Annotated || | ||
| returnType is INamedTypeSymbol { OriginalDefinition.SpecialType: SpecialType.System_Nullable_T }) | ||
| { | ||
| defaultExpression = SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression); | ||
| } | ||
| else | ||
| { | ||
| // Use default(T) for value types | ||
| defaultExpression = SyntaxFactory.DefaultExpression( | ||
| SyntaxFactory.ParseTypeName(returnType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat))); | ||
| } | ||
|
|
||
| var currentExpression = defaultExpression; | ||
|
|
||
| // Create the enum value access: EnumType.Value | ||
| var enumAccessValues = enumMembers | ||
| .AsEnumerable() | ||
| .Reverse() | ||
| .Select(m => | ||
| SyntaxFactory.MemberAccessExpression( | ||
| SyntaxKind.SimpleMemberAccessExpression, | ||
| SyntaxFactory.ParseTypeName(enumType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)), | ||
| SyntaxFactory.IdentifierName(m.Name) | ||
| ) | ||
| ); | ||
|
|
||
| // Build the ternary chain, calling the method on each enum value | ||
| foreach (var enumValueAccess in enumAccessValues) | ||
| { | ||
| // Create the method call on the enum value: ExtensionClass.Method(EnumType.Value) | ||
| var methodCall = CreateMethodCallOnEnumValue(originalMethod, enumValueAccess, node.ArgumentList); | ||
|
|
||
| // Create condition: receiver == EnumType.Value | ||
| var condition = SyntaxFactory.BinaryExpression( | ||
| SyntaxKind.EqualsExpression, | ||
| visitedReceiver, | ||
| enumValueAccess | ||
| ); | ||
|
|
||
| // Create conditional expression: condition ? methodCall : previousExpression | ||
| currentExpression = SyntaxFactory.ConditionalExpression( | ||
| condition, | ||
| methodCall, | ||
| currentExpression | ||
| ); | ||
| } | ||
|
|
||
| // If nullable, wrap in null check | ||
| if (isNullable) | ||
| { | ||
| var nullCheck = SyntaxFactory.BinaryExpression( | ||
| SyntaxKind.EqualsExpression, | ||
| visitedReceiver, | ||
| SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression) | ||
| ); | ||
|
|
||
| currentExpression = SyntaxFactory.ConditionalExpression( | ||
| nullCheck, | ||
| defaultExpression, | ||
| currentExpression | ||
| ); | ||
| } | ||
|
|
||
| expandedExpression = SyntaxFactory.ParenthesizedExpression(currentExpression); | ||
| return true; | ||
| } | ||
|
|
||
| private ExpressionSyntax CreateMethodCallOnEnumValue(IMethodSymbol methodSymbol, ExpressionSyntax enumValueExpression, ArgumentListSyntax originalArguments) | ||
| { | ||
| // Get the fully qualified containing type name | ||
| var containingTypeName = methodSymbol.ContainingType.ToDisplayString(NullableFlowState.None, SymbolDisplayFormat.FullyQualifiedFormat); | ||
|
|
||
| // Create the method access expression: ContainingType.MethodName | ||
| var methodAccess = SyntaxFactory.MemberAccessExpression( | ||
| SyntaxKind.SimpleMemberAccessExpression, | ||
| SyntaxFactory.ParseName(containingTypeName), | ||
| SyntaxFactory.IdentifierName(methodSymbol.Name) | ||
| ); | ||
|
|
||
| // Build arguments: the enum value as the first argument (for extension methods), followed by any additional arguments | ||
| var arguments = SyntaxFactory.SeparatedList<ArgumentSyntax>(); | ||
| arguments = arguments.Add(SyntaxFactory.Argument(enumValueExpression)); | ||
|
|
||
| // Add any additional arguments from the original call | ||
| foreach (var arg in originalArguments.Arguments) | ||
| { | ||
| arguments = arguments.Add((ArgumentSyntax)Visit(arg)); | ||
| } | ||
|
|
||
| return SyntaxFactory.InvocationExpression( | ||
| methodAccess, | ||
| SyntaxFactory.ArgumentList(arguments) | ||
| ); | ||
| } | ||
| } |
90 changes: 90 additions & 0 deletions
90
...tyFrameworkCore.Projectables.Generator/ExpressionSyntaxRewriter.NullConditionalRewrite.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
|
|
||
| namespace EntityFrameworkCore.Projectables.Generator; | ||
|
|
||
| public partial class ExpressionSyntaxRewriter | ||
| { | ||
| public override SyntaxNode? VisitConditionalAccessExpression(ConditionalAccessExpressionSyntax node) | ||
| { | ||
| var targetExpression = (ExpressionSyntax)Visit(node.Expression); | ||
|
|
||
| _conditionalAccessExpressionsStack.Push(targetExpression); | ||
|
|
||
| if (_nullConditionalRewriteSupport == NullConditionalRewriteSupport.None) | ||
| { | ||
| var diagnostic = Diagnostic.Create(Diagnostics.NullConditionalRewriteUnsupported, node.GetLocation(), node); | ||
| _context.ReportDiagnostic(diagnostic); | ||
|
|
||
| // Return the original node, do not attempt further rewrites | ||
| return node; | ||
| } | ||
|
|
||
| else if (_nullConditionalRewriteSupport is NullConditionalRewriteSupport.Ignore) | ||
| { | ||
| // Ignore the conditional access and simply visit the WhenNotNull expression | ||
| return Visit(node.WhenNotNull); | ||
| } | ||
|
|
||
| else if (_nullConditionalRewriteSupport is NullConditionalRewriteSupport.Rewrite) | ||
| { | ||
| var typeInfo = _semanticModel.GetTypeInfo(node); | ||
|
|
||
| // Do not translate until we can resolve the target type | ||
| if (typeInfo.ConvertedType is not null) | ||
| { | ||
| // Translate null-conditional into a conditional expression, wrapped inside parenthesis | ||
| return SyntaxFactory.ParenthesizedExpression( | ||
| SyntaxFactory.ConditionalExpression( | ||
| SyntaxFactory.BinaryExpression( | ||
| SyntaxKind.NotEqualsExpression, | ||
| targetExpression.WithTrailingTrivia(SyntaxFactory.Whitespace(" ")), | ||
| SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression).WithLeadingTrivia(SyntaxFactory.Whitespace(" ")) | ||
| ).WithTrailingTrivia(SyntaxFactory.Whitespace(" ")), | ||
| SyntaxFactory.ParenthesizedExpression( | ||
| (ExpressionSyntax)Visit(node.WhenNotNull) | ||
| ).WithLeadingTrivia(SyntaxFactory.Whitespace(" ")).WithTrailingTrivia(SyntaxFactory.Whitespace(" ")), | ||
| SyntaxFactory.CastExpression( | ||
| SyntaxFactory.ParseName(typeInfo.ConvertedType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)), | ||
| SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression) | ||
| ).WithLeadingTrivia(SyntaxFactory.Whitespace(" ")) | ||
| ).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia())); | ||
| } | ||
| } | ||
|
|
||
| return base.VisitConditionalAccessExpression(node); | ||
| } | ||
|
|
||
| public override SyntaxNode? VisitMemberBindingExpression(MemberBindingExpressionSyntax node) | ||
| { | ||
| if (_conditionalAccessExpressionsStack.Count > 0) | ||
| { | ||
| var targetExpression = _conditionalAccessExpressionsStack.Pop(); | ||
|
|
||
| return _nullConditionalRewriteSupport switch { | ||
| NullConditionalRewriteSupport.Ignore => SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, targetExpression, node.Name), | ||
| NullConditionalRewriteSupport.Rewrite => SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, targetExpression, node.Name), | ||
| _ => node | ||
| }; | ||
| } | ||
|
|
||
| return base.VisitMemberBindingExpression(node); | ||
| } | ||
|
|
||
| public override SyntaxNode? VisitElementBindingExpression(ElementBindingExpressionSyntax node) | ||
| { | ||
| if (_conditionalAccessExpressionsStack.Count > 0) | ||
| { | ||
| var targetExpression = _conditionalAccessExpressionsStack.Pop(); | ||
|
|
||
| return _nullConditionalRewriteSupport switch { | ||
| NullConditionalRewriteSupport.Ignore => SyntaxFactory.ElementAccessExpression(targetExpression, node.ArgumentList), | ||
| NullConditionalRewriteSupport.Rewrite => SyntaxFactory.ElementAccessExpression(targetExpression, node.ArgumentList), | ||
| _ => Visit(node) | ||
| }; | ||
| } | ||
|
|
||
| return base.VisitElementBindingExpression(node); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
VisitConditionalAccessExpressionpushes onto_conditionalAccessExpressionsStackbefore checking_nullConditionalRewriteSupport. In theNonebranch it returns the original node without popping, leaving the stack unbalanced for the rest of the traversal and potentially growing without bound when multiple conditional accesses are present. Consider popping before returning (or restructuring with atry/finallyso every push is matched with a pop).