Attach additional information to AST nodes

Hi Clang list,

I am implementing a RecursiveASTVisitor so I can rely on a preorder traversal.
In some of the Visit* callbacks I would like to pass some information downwards
and do something like this:

bool VisitFunctionDecl(const FunctionDecl *d) {

d->getBody()->attachToContext(myAdditionalData);

}

So that I can access it when the callback for the body is called:

bool VisitCompoundStmt(const CompoundStmt *n) {

MyAdditionalData *myData = n->getFromContext();

}

Right now I am using a std::map with the pointer as key, i.e.

bool VisitFunctionDecl(const FunctionDecl *d) {

myMap[d->getBody()] = myAdditionalData;

}

and then

bool VisitCompoundStmt(const CompoundStmt *n) {

MyAdditionalData *myData = myMap[n];

}

That works, but it does not seem to be the right thing.
Is there a way to attach additional information to AST nodes?
Or should I approach that in a completely different way?

Thank you and best regards,
Benedikt

Hey Benedict,

Depending on where you want to actually "read" the additional
information, you might be better off creating the extra information in
the Traverse* functions (and don't forget to call
Base::TraverseWhatever(ptr); to do the traversal as the base class
would!), and read them in the "Visit" ones.

The hierarchy is that... because types can have subtypes, from what
I've seen, the TraverseWhatever methods are called for nodes that are
EXACTLY Whatever types. But for each node the full hierarchy of Visit*
methods are called... e.g. for a CXXConstructorDecl, VisitDecl,
VisitFunctionDecl, VisitCXXMemberDecl are called, in inheritance
order.

Also, use map::at() for reading from a map, gives better errors. :wink:

Regards,
Whisperity.