예제 #1
0
        private static ExpressionSyntax InvertConditionInternal(ExpressionSyntax condition)
        {
            if (condition is ParenthesizedExpressionSyntax)
            {
                return(SyntaxFactory.ParenthesizedExpression(InvertCondition(((ParenthesizedExpressionSyntax)condition).Expression)));
            }

            if (condition is PrefixUnaryExpressionSyntax)
            {
                var uOp = (PrefixUnaryExpressionSyntax)condition;
                if (uOp.IsKind(SyntaxKind.LogicalNotExpression))
                {
                    if (!(uOp.Parent is ExpressionSyntax))
                    {
                        return(uOp.Operand.SkipParens());
                    }
                    return(uOp.Operand);
                }
                return(SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, uOp));
            }

            if (condition is BinaryExpressionSyntax)
            {
                var bOp = (BinaryExpressionSyntax)condition;

                if (bOp.IsKind(SyntaxKind.LogicalAndExpression) || bOp.IsKind(SyntaxKind.LogicalOrExpression))
                {
                    return(SyntaxFactory.BinaryExpression(NegateConditionOperator(bOp.Kind()), InvertCondition(bOp.Left), InvertCondition(bOp.Right)));
                }

                if (bOp.IsKind(SyntaxKind.EqualsExpression) ||
                    bOp.IsKind(SyntaxKind.NotEqualsExpression) ||
                    bOp.IsKind(SyntaxKind.GreaterThanExpression) ||
                    bOp.IsKind(SyntaxKind.GreaterThanOrEqualExpression) ||
                    bOp.IsKind(SyntaxKind.LessThanExpression) ||
                    bOp.IsKind(SyntaxKind.LessThanOrEqualExpression))
                {
                    return(SyntaxFactory.BinaryExpression(NegateRelationalOperator(bOp.Kind()), bOp.Left, bOp.Right));
                }

                return(SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, SyntaxFactory.ParenthesizedExpression(condition)));
            }

            if (condition is ConditionalExpressionSyntax cEx)
            {
                return(cEx.WithCondition(InvertCondition(cEx.Condition)));
            }

            if (condition is LiteralExpressionSyntax)
            {
                if (condition.Kind() == SyntaxKind.TrueLiteralExpression)
                {
                    return(SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression));
                }
                if (condition.Kind() == SyntaxKind.FalseLiteralExpression)
                {
                    return(SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression));
                }
            }

            return(SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, condition.AddParensIfRequired()));
        }