[cfe-dev] Chaining ASTConsumers
Vlad
vlad at demoninsight.com
Fri May 7 08:10:53 PDT 2010
I've been successful with the following approach:
- use an ASTConsumer implementation that can delegate to yet another instance of an ASTConsumer
- the first consumer performs its ASTConsumer callbacks (and, if necessary, node transformations) *before* the delegate consumer:
ASTConsumer * m_delegate;
void HandleTopLevelDecl (DeclGroupRef group)
{
for (DeclGroupRef::iterator node = group.begin(), n_limit = group.end (); n != n_lmit; ++ n)
{
// [do whatever you want with 'node', including AST transforms: this will typically use DeclVisitor and StmtVisitor to handle just the decls and expressions of interest]
}
m_delegate-> HandleTopLevelDecl (visit); // now let the "real" consumer see what we've done
}
// forward other ASTConsumer methods to 'm_delegate' as well so it knowns when a translation unit is done, etc
So, when my ASTConsumer is an AST transformer and m_delegate is, say, a CodeGenerator instance, I get to modify AST just before it gets compiled into native code. It works because the "real" AST consumer (CodeGenerator) only sees the nodes that I want it to see, possibly after a transformation.
Of course, not every AST transform can be done this way, but for additive/substitutive tree transformations this works well and does not require a pretty-printing pass. It is easy to imagine this working for an entire chain/pipeline of AST manipulators.
HTH,
Vlad
On May 7, 2010, at 7:22 AM, Mohamed Yousef wrote:
> Hello ,
>
> I'm writing a source to source tool, according to list prefred way is Rewriter class , but also i can modify list by a series of traversals
>
> the problem is Rewriter class method is really primitive,, isn't suitable for big changes (esp. in structure )
>
> what i'm asking for is, can i chain ASTConsumer's ,,so i can progressively modify AST and pretty-print it finally
> but it looks like (from ParseAST) i would have to Parser -> ASTConsumer -> pretty-print ->Parser ->ASTConsumer -> .. and so on
> which is very tedious
>
> is the there an explicit AST data structure ? can i just parse once and modify resulting AST many times (traverse,add/delete nodes it not re-parse source) ?
>
> Thanks,
> Mohamed Yousef
> _______________________________________________
> cfe-dev mailing list
> cfe-dev at cs.uiuc.edu
> http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev
More information about the cfe-dev
mailing list