简体   繁体   中英

how to identify local variable with same name as its parent/Container class

Hi 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM