RecursiveAstVisitor: How to find the open brace of the corresponding function declaration within a VisitCallExpr?

Hi,

I want to retrieve in my RecursiveAstVisitor inside a VisitCallExpr method the open brace of the corresponding function declaration.

The code below does not find anything…

Any idea what I am doing wrong and is there a more elegant way to generate a variable declaration with a Rewriter?

Thanx

Marcel

bool VisitCallExpr(CallExpr *CallExpression) {

if (CallExpression != NULL) {
const auto& parents = TheContext->getParents(CallExpression);

if (parents.empty()) {
llvm::errs() << “**** Can not find parent\n”;
return false;
}

auto parent = parents[0].get();

if (parent != NULL) {
llvm::errs() << “**** FOUND DECL STATEMENT \n";
SourceLocation l1 = parent->getLocStart();
TheRewriter.InsertText(l1, "/
found decl
/”);
}
else
llvm::errs() << “**** DECL STATEMENT NOT FOUND ****\n”;

}

Marcel Schaible via cfe-dev <cfe-dev@lists.llvm.org> writes:

Hi,

I want to retrieve in my RecursiveAstVisitor inside a VisitCallExpr
method the open brace of the corresponding function declaration.

The code below does not find anything..

Any idea what I am doing wrong and is there a more elegant way to
generate a variable declaration with a Rewriter?

To find the opening brace of the enclosing function can store the
current FunctionDecl as class member.

class MyVisitor : RecursiveASTVisitor<MyVisitor> {

FunctionDecl *Func = nullptr;

bool VisitFunctionDecl(FunctionDecl *FD) {
    Func = FD;
    RecursiveASTVisitor<MyVisitor>::VisitFuncionDecl(FD);
}

};

However, if you want the one of the called function, then just use

FunctionDecl *FD = CallExpression->getDirectCallee();
if (FD) {
   ...
}

Thanks for your hint, which solved my problem.

Cheers

Marcel