endless loop on code analysis with FxCop Introspection
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
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
- 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? - 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 themethod.Body
and keep track of every '{' and '}' we find. Increment counter for '{' and decrement counter for '}'. That should work, right?
精彩评论