Source implementation available for FxCop rule CA2241 (Provide correct arguments to formatting methods)?

StackOverflow https://stackoverflow.com/questions/12431609

  •  02-07-2021
  •  | 
  •  

Domanda

I'm attempting to implement my own version of CA2241 using the VisitMethodCall override.

It works if the number of arguments to String.Format are 5 or fewer, but always shows only 2 arguments if there are 6 or more arguments (including the format string).

For example (MethodCall)call.Operands.Count is correct in these cases:

Console.WriteLine( String.Format( "{0} {1}", 1, 2 ) );
Console.WriteLine( String.Format( "{0} {1} {2}", 1, 2, 3 ) );

...but always returns only '2' in this case:

Console.WriteLine( String.Format( "{0} {1} {2} {3}", 1, 2, 3, 4 ) );
Console.WriteLine( String.Format( "{0} {1} {2} {3} {4}", 1, 2, 3, 4, 5 ) );

Here is my abbreviated current override for VisitMethodCall. When expression.NodeType is not Literal, or Call it is always Pop with only two parameters. And this situation only occurs when the number of arguments to String.Format is 6 or more.

public override void VisitMethodCall( MethodCall call )
{
    MemberBinding mb = call.Callee as MemberBinding;
    if ( mb.BoundMember.FullName.StartsWith( "System.String.Format(" ) )
    {
        Expression expression = call.Operands[ 0 ];
        switch ( expression.NodeType )
        {
        case NodeType.Literal:
            // ...
            break;
        case NodeType.Call:
            // ...
            break;
        default: // always NodeType.Pop with two parameters
            // ...
        break;
        }
    }
    base.VisitMethodCall( call );
}

So, what am I doing wrong? Also, is source available for the CA2241 rule?

Thanks in advance.

EDIT: I've discovered this article: http://blogs.msdn.com/b/codeanalysis/archive/2010/04/14/data-flow-analysis-rules-in-visual-studio-2010.aspx which explains that CC2241 has been reimplemented using the new Data Flow Analysis engine (Pheonix), and sure enough I was able to find the method with dotPeek. Unfortunately, there's no documentation for the new DFA engine that I can find.

È stato utile?

Soluzione

The reason that you're only seeing two operands once you get past 3 substitute values is that the target is invoking the Format(string format, params object[] args) overload of String.Format. If you want to know how many substitute values are being passed, you will need to examine the size of the args parameter array.

There is no source code available for the Microsoft-provided FxCop rules, and there is no rule SDK available. If you want to learn about how they are built, you'll need to use a decompiler (like pretty much every single other person who writes custom rules).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top