Search code examples
c#stylecop

StyleCop Custom Rule: Get the Type of a variable when checking assignments


I'm writing a custom StyleCop rule to prevent String variables being assigned null, and am encountering a problem!

I can easily prevent a String variable being assigned null during the declaration with the following code:

if (expression.ExpressionType == ExpressionType.VariableDeclarator)
{
    VariableDeclaratorExpression variableDeclarator = ((VariableDeclaratorExpression)expression);

    if (variableDeclarator.Initializer == null)
    {
        if ((parentStatement.StatementType != StatementType.Catch) &&
            (parentStatement.StatementType != StatementType.Foreach))
        {
            this.AddViolation(parentElement, expression.LineNumber, "InitialiseVariablesOnDeclaration");
        }
    }
    else
    {
        Boolean isString = false;

        foreach (CsToken token in variableDeclarator.ParentVariable.Tokens)
        {
            if ((token.Text.Equals("String")) || (token.Text.Equals("string")))
            {
                isString = true;
                break;
            }
        }

        if (isString)
        {
            foreach (CsToken token in variableDeclarator.Initializer.Tokens)
            {
                if (token.CsTokenType == CsTokenType.Null)
                {
                    this.AddViolation(parentElement, expression.LineNumber, "DoNotAssignStringsToNull");
                    break;
                }
            }
        }
    }
}

(Note that this code also verifies that variables are explicitly assigned when they are declared).

I'm having trouble checking for String variables being assigned null after their declarations, The StyleCop API doesn't seem to expose any mechanism to find the type of a variable on the left side of an assignment statement.

Therefore, this code triggers the rule I have just now:

String someString = null;

But this code doesn't:

String someOtherString = String.Empty;
someOtherString = null;

I'm currently using StyleCop version 4.7.19.0. Any pointers in the right direction would be gratefully received!


Solution

  • StyleCop rules are meant to enforce proper source code formatting standards. They are only interested in your source code as text: punctuation, spacing, spelling, etc. StyleCop rules have access to your source code as it exists before the compiler gets to it. In some ways this is good, because it allowed StyleCop to enforce things that are meaningless to the compiler, such as the placement of curly braces, commas, or spaces, the order of namespaces, or the presence of comments.

    What you are asking for, however, requires a deeper form of analysis that understands the semantic meaning of tokens, and can track that meaning for a given token as it appears through your code. That is the domain of static code analysis (formerly "FxCop"), which happens after the compiler has processed your source code into IL. Static code analysis knows about language elements: types, operators, identifiers, etc. It can perform program flow analysis, type validation, and other operations that rely on the compiler already having processed your source code text into elements of the language.

    In this case, the question you are trying to ask is this:

    Are there any instances where an identifier of type System.String is assigned a null value?

    That question requires knowing the types of each identifier, and being able to follow that type as flow proceeds through your function. That's a Code Analysis rule, not a Style rule, so you would need to build a custom CA rule to handle that.