[cfe-dev] looking "up" the tree in RecursiveASTVisitor?

Mikhail Ramalho via cfe-dev cfe-dev at lists.llvm.org
Thu Jan 28 08:27:03 PST 2016


Hi Noel,

This is common question, I've seen it a couple of times here in the mailing
list.

Here's the solution a use. However, you do need the ASTContext, which you
can get from any Decl object by calling the getASTContext() method.

2016-01-04 7:28 GMT+00:00 Mikhail Ramalho <mikhail.ramalho at gmail.com>:

> Hello,
>
> You can use the following code to walk through the parents of a stmt/expr:
>
> const clang::Decl* get_DeclContext_from_Stmt(const clang::Stmt& stmt)
> {
>   auto it = ASTContext->getParents(stmt).begin();
>
>   if(it == ASTContext->getParents(stmt).end())
>     return nullptr;
>
>   const clang::Decl *aDecl = it->get<clang::Decl>();
>   if(aDecl)
>     return aDecl;
>
>   const clang::Stmt *aStmt = it->get<clang::Stmt>();
>   if(aStmt)
>     return get_DeclContext_from_Stmt(*aStmt);
>
>   return nullptr;
> }
>
> It tries to find a declaration, but you can change it to find any
> stmt/expr.
>
> Best regards,
>

To get the FunctionDecl, I use the following code:

const clang::FunctionDecl* get_top_FunctionDecl_from_Stmt(
  const clang::Stmt& stmt)
{
  const clang::Decl *decl = get_DeclContext_from_Stmt(stmt);
  if(decl)
    return static_cast<const
clang::FunctionDecl*>(decl->getNonClosureContext());

  return nullptr;
}

I don't know if there is some weird corner case in which it won't work but
it's working so far (I tried in about 7000 different programs, from simple
programs to some weird preprocessed device drivers).

Thank you,


2016-01-28 14:01 GMT+00:00 Noel Grandin via cfe-dev <cfe-dev at lists.llvm.org>
:

> Hi
>
> Is there a straightforward way to look "up" the tree when implementing
> a clang plugin using RecursiveASTVisitor ?
>
> I've bumped into this a couple of times and never found a "nice" answer.
>
> For example, I have overridden
>
>        VisitCallExpr(const CallExpr* expr)
>
> and I want to know in which context the call is happening i.e. from
> which FunctionDecl the call is being made.
>
> It seems like there should be an easy way to walk back up the tree?
>
> Thanks, Noel Grandin
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at lists.llvm.org
> http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev
>



-- 

Mikhail Ramalho.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20160128/5ff5f100/attachment.html>


More information about the cfe-dev mailing list