@@ -190,7 +190,46 @@ public ExpressionSyntaxRewriter(INamedTypeSymbol targetTypeSymbol, NullCondition
190190 continue ;
191191 }
192192
193- throw new InvalidOperationException ( "Switch expressions rewriting is only supported with constant values" ) ;
193+ if ( arm . Pattern is DeclarationPatternSyntax declaration )
194+ {
195+ var getTypeExpression = SyntaxFactory . MemberAccessExpression (
196+ SyntaxKind . SimpleMemberAccessExpression ,
197+ ( ExpressionSyntax ) Visit ( node . GoverningExpression ) ,
198+ SyntaxFactory . IdentifierName ( "GetType" )
199+ ) ;
200+
201+ var getTypeCall = SyntaxFactory . InvocationExpression ( getTypeExpression ) ;
202+ var typeofExpression = SyntaxFactory . TypeOfExpression ( declaration . Type ) ;
203+ var equalsExpression = SyntaxFactory . BinaryExpression (
204+ SyntaxKind . EqualsExpression ,
205+ getTypeCall ,
206+ typeofExpression
207+ ) ;
208+
209+ ExpressionSyntax condition = equalsExpression ;
210+ if ( arm . WhenClause != null )
211+ {
212+ condition = SyntaxFactory . BinaryExpression (
213+ SyntaxKind . LogicalAndExpression ,
214+ equalsExpression ,
215+ ( ExpressionSyntax ) Visit ( arm . WhenClause . Condition )
216+ ) ;
217+ }
218+
219+ var modifiedArmExpression = ReplaceVariableWithCast ( armExpression , declaration , node . GoverningExpression ) ;
220+ currentExpression = SyntaxFactory . ConditionalExpression (
221+ condition ,
222+ modifiedArmExpression ,
223+ currentExpression
224+ ) ;
225+
226+ continue ;
227+ }
228+
229+ throw new InvalidOperationException (
230+ $ "Switch expressions rewriting supports only constant values and declaration patterns (Type var). " +
231+ $ "Unsupported pattern: { arm . Pattern . GetType ( ) . Name } "
232+ ) ;
194233 }
195234
196235 return currentExpression ;
@@ -346,5 +385,25 @@ public ExpressionSyntaxRewriter(INamedTypeSymbol targetTypeSymbol, NullCondition
346385
347386 return base . VisitNullableType ( node ) ;
348387 }
388+
389+ private ExpressionSyntax ReplaceVariableWithCast ( ExpressionSyntax expression , DeclarationPatternSyntax declaration , ExpressionSyntax governingExpression )
390+ {
391+ if ( declaration . Designation is SingleVariableDesignationSyntax variableDesignation )
392+ {
393+ var variableName = variableDesignation . Identifier . ValueText ;
394+
395+ var castExpression = SyntaxFactory . ParenthesizedExpression (
396+ SyntaxFactory . CastExpression (
397+ declaration . Type ,
398+ ( ExpressionSyntax ) Visit ( governingExpression )
399+ )
400+ ) ;
401+
402+ var rewriter = new VariableReplacementRewriter ( variableName , castExpression ) ;
403+ return ( ExpressionSyntax ) rewriter . Visit ( expression ) ;
404+ }
405+
406+ return expression ;
407+ }
349408 }
350409}
0 commit comments