Search code examples
c#roslynexpression-treescode-analysis

Using Roslyn to determine if a BinaryExpression is an arithmetic expression


Using a CSharpSyntaxRewriter I'd like to determine if a a particular BinaryExpression is an Artihmetic expression. Is there a simpler way to determine this than to code snippet below.

private static bool IsArithmeticOperator(BinaryExpressionSyntax node)
{
    return node.IsKind(SyntaxKind.AddExpression) ||
        node.IsKind(SyntaxKind.MultiplyExpression) ||
        node.IsKind(SyntaxKind.DivideExpression) ||
        node.IsKind(SyntaxKind.SubtractExpression) ||
        node.IsKind(SyntaxKind.ModuloExpression);
}

Just feels a little clunky.


Solution

  • I am not sure this is possible, but there is something in the enum that maybe can help you, the arithmetic expression are in order inside the enum SyntaxKind except ModuloExpression which you can check separately.

    maybe other SyntaxKind in this range will also be good for your needs.

    AddExpression = 307,
    SubtractExpression = 308,
    MultiplyExpression = 309,
    DivideExpression = 310,
    IntegerDivideExpression = 311,
    ExponentiateExpression = 314,
    LeftShiftExpression = 315,
    RightShiftExpression = 316,
    ConcatenateExpression = 317,
    ModuloExpression = 318,
    

    So you can do something like this :

    private static bool IsArithmeticOperator(BinaryExpressionSyntax node)
    {
        SyntaxKind expressionKind = node.Kind();
        return (expressionKind >= SyntaxKind.AddExpression && expressionKind <= SyntaxKind.DivideExpression)
        || expressionKind == SyntaxKind.ModuloExpression;
    }
    

    Update

    This will work only for Microsoft.CodeAnalysis.VisualBasic

    and wont work for Microsoft.CodeAnalysis.CSharp