Getting the functionDecl of a compound statement

Viewed 48

I am doing source to source translation using Clang. I have a implemented a compound statement visitor (MyASTVisitor::TraverseCompoundStmt). I need to get the functionDecl of the visited compound statement, If the compound statement is a nested one, I am able to get the functionDecl using the get parents method using the following code:

bool MyASTVisitor::TraverseCompoundStmt(CompoundStmt* CS) {
    clang::DynTypedNodeList parentsNodes = Ctx->getParents(*CS);
    for (const auto &parentNode : parentsNodes)
    {
        StringRef ParentNodeKind = parentNode.getNodeKind().asStringRef();
        std:string nodeKindstr = ParentNodeKind.str();
        if (nodeKindstr.find("FunctionDecl") != std::string::npos)
        {
            const clang::FunctionDecl* f = parentNode.get<clang::FunctionDecl>();
            if (f)
            {
              //Do something....
            }
        }
    }
}

However, if the compound statement is not a nested one, for example a code that looks like this:

void foo()
{
 printf("Hi");
}

then Ctx->getParents(*CS) returns a nullptr (as there are no parents) and I cannot get the functionDecl (I did not find in the documentation how to do it).

I would appreciate help in getting the functionDecl.

0 Answers
Related