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!
after some more research, I've figured out I had actually TWO main problems
I wonder what we could have achieved if FxCop could provide us with a true AST visitor?
SourceContext
property of themethod.Body
and keep track of every '{' and '}' we find. Increment counter for '{' and decrement counter for '}'. That should work, right?