endless loop on code analysis with FxCop Introspection

338 views Asked by At

I'm trying to write a custom FxCop code analysis rule that will warn developers from methods containing too deeply nested code blocks, and will urge them to re-factor out the mess.

ex. I'm trying to avoid the following situation:

if(condition)
{
   foreach(var item in items)
   {
       if(anotherCondition)
       {
           for(var product in item.Products)
           {
               // even more nested statement blocks...
           }
       }
   }
}

I get a stackoverflow when I override the VisitBlock(Block block) method
that counts the block's depth, because apparently, there is a cyclic reference from one of the properties of the block to the block itself. i.e. the following is true for some i: block.Statements[i] == block

Why does such a cyclic reference exist? How to avoid it? Thanks!

1

There are 1 answers

0
Paul On BEST ANSWER

after some more research, I've figured out I had actually TWO main problems

  1. The VisitXXX methods are not visiting nodes in an abstract syntax tree of the source code but actually visit nodes in the generated IL. Just compare the generated IL instructions per method and the generated statements per method.Body.
    I wonder what we could have achieved if FxCop could provide us with a true AST visitor?
  2. To answer my initial question, to prevent developers of writing too many nested code blocks, we should just scan the method code by ourselves, I mean, take out the start line and the end line inside the SourceContext property of the method.Body and keep track of every '{' and '}' we find. Increment counter for '{' and decrement counter for '}'. That should work, right?