开发者

endless loop on code analysis with FxCop Introspection

开发者 https://www.devze.com 2023-02-09 08:25 出处:网络
I\'m trying to write a custom FxCop code analysis rule that will warn developers from methods containing too deeply nested code blocks,

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 t开发者_运维技巧rue for some i: block.Statements[i] == block

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


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?
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号