简体   繁体   中英

How to find out if a variable is in the scope of a specific source location in clang AST?

I am using clang to write an automatic repairing program. Sometimes the program needs to generate some code by means of the variables that are in the scope of the faulty section. First of all it gathers all the variables in the method (containing the faulty section) and then it should check which ones belong to the scope of the faulty section. How can I find out if a variable belongs to the scope of some source location? For example I have a code like this:

int a = 12;
{
    int b = 77;
}

if (i > 0 //FAULTY SECTION) 
{
 //do something 
}

now the program needs to generate some code and change the above to something like this one:

int a = 12;
{
    int b = 77;
}

if (i > 0 && a > 0) 
{
 //do something 
}

It is obvious that b does not belong to the scope of the faulty section and my program should not try something like the one below because syntactically it is wrong:

if (i > 0 && b > 0) 
{
 //do something 
}

How can the program find out that b does not exist in the scope of the faulty section and not try the last code?

So you are trying to figure out programmatically whether two variables share the same scope or not. You have your scope operators { and }. So what you can do is while you are parsing the source, create a tree that keeps track of the scopes of variables, like:

tree scopes // variable
list current_branch // variable pointing to current branch

current_branch = scopes.addRoot() // root or main scope

start parsing {
    if scope start operator met:
        current_branch = current_branch.addNewBranch() // branch down
    if variable met:
        current_branch.addVariable(theVariable) // variables in the same scope will be added to the same branch
    if scope end operator met:
        current_branch = current_branch.parent // go up a branch
}

Then, you will have a tree of scopes with your variables, you can check if they share the same scope by looking for one variable in the tree and checking if the other variable is in the same branch.

Don't forget that if a variable foo is in any parent branch of where an other variable bar is, then foo will be still in scope in bar 's scope.

Example:

int foo;
{
    int bar; // foo still in scope
}

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