开发者_StackOverflowHi i want to develop static code analysis rule so that local variables do not shadow a name in its outer scope. can you help me hou to identify the if blocks/nested classes using the same names as in its outer scope.and also how to avoid method hiding of the parents' member methods.
Please help me creating an algorithm so that i can develop a static code analysis rule.
(EDIT: OP wasn't originally clear about the target language)
Assuming Java, use a Java parser that builds an AST. Implement the following algorithm:
for all Java source files F of interest
parse F
for all nodes N of F
if N is a "class declaration" for a class C
for all methods M under N
for all nodes m in M
if m is a declaration with name C
report "found " m " in " M " shadowing " C
endif
endfor
endfor
endif
endfor
endfor
This is a little inefficient in that it might scan some subtrees more than once.
Namespaces make this more complex for C# and C++. If you want to do this for those languages, I think you will need a full parser along with name resolution (symbol table). There's no gaurantee that a method is declared "under" the class declaration in those langauges, so a simple tree search won't do the trick. In that case, you'll have to add an additional syntax check for a namespace declaration, and verify that the namespace refers to a declared class by checking the symbol table.
For C++, you might use Clang or our C++ Front End.
I'm not sure what you can use to this for C#, since you need the symbol table. Perhaps Mono offers you sufficent access, but I didn't think they handled C# 3.0 or 4.0.
精彩评论