admin管理员组

文章数量:1126091

I am writing a test that checks whether a variable already exists in the same scope. There should be a warning if there is already a similar variable in the same scope. For example, an error should be output if an int test is created in a class and an int Test is created in a function in a class. This already works, but the current code does not handle the following case correctly:

class testclass
{
    private:
    int avocado;
    void banana()
    {
        if(avocado == 0)
        {
            int orange = 1;
        }

        if(avocado == 2)
        {
            int Orange = 5;
            // A warning is issued here although none should be
        }
        
    }
};

So far, the checker has assigned the two if-blocks to the same scope, although they should not see each other.

This is my check-method so far:

const DeclContext *Context = nullptr;

const auto *Var = Result.Nodes.getNodeAs<DeclaratorDecl("variable");
//binding all variables from functions here
if(Var)
{
    Context = Var->getDeclContext();
}

const auto *Field = Result.Nodes.getNodeAs<DeclaratorDecl>("field");
//binding all variables from classes here
if(Field)
{
    Context = Field->getDeclContext();
}

while (Context)
{
    for (const auto *Decl : Context->decls())
    {
        // check whether current variable is already declared in the same scope
        if (const auto *PreviousVar = dyn_cast<VarDecl>(Decl))
        {
            if(PreviousVar == Var)
            {
                continue;
            }

            CheckforEquality(Var, PreviousVar);
            CheckforEquality(Field, PreviousVar);
        }

        if (const auto *PreviousField = dyn_cast<FieldDecl>(Decl))
        {
            if(PreviousField == Field)
            {
                continue;
            }

            CheckforEquality(Var, PreviousField);
            CheckforEquality(Field, PreviousField);
        }
    }
    Context = Context->getParent();
}

Unfortunately I don't know how to add that different if-blocks don't see each other. Is there another way to find out if variables are in the same scope?

本文标签: