Insertion one AST node into another at particular location

Can I use ASTImporter for add some loop into function CompoundStatement node exactly in particular source location (or after some AST node between left bracket and right bracket)?

Importer(ToUnit->getASTContext(), ToUnit->getFileManager(), FromUnit->getASTContext(), FromUnit->getFileManager(),

It seems, I need to get ASTContext object from node "to", because ASTImporter constructor takes ASTContext "from" and "to"? But how can I do it having only "from" and "to" nodes ?


Do you need to use ASTImporter, or was that just a starting point? LibTooling has a lot of support for editing code. clang-tidy tends to be the easiest place to start. Additionally, clang transformer can simplify the code editing parts with “rewrite rules”:

To your example, you’d write a matcher which identifies the node of interest and then edit the code with something like insertAfter(node(IdBoundToInterestingNode), cat(...))

ASTImporter was a starting point. I realized rewritings at text level at particular position after some node was matched. Now I need to modify AST at tree (node) level:

  • add some statements to function compound stmt, and after match new AST again
  • perform another AST changing and so on and so on yet another.

This way is more preferable, because I not need load source code many times.

I have already found that it’s possible:


The similar thing was realized in project Scout

Unfortunately these projects and tips are outdated. Maybe there is some general solution in modern (9-11 versions) llvm/clang.
In sum I need mechanism for development own source-to-source translator but changes must be in AST (not at textual) level

Perhaps, you could do this with the RecursiveASTVisitor, by overriding the VisitCompoundStmt method. In the method you should be able to add the desired new AST nodes. But keep in mind that the Clang AST is designed to be immutable, so this classifies this approach as a hack, you have to be very careful. When you create a new node, you have to make sure that the node is wired in the existing tree properly. And that can have many corner cases and that is why ASTImporter and ASTReader are so complex.

Note, the ASTImporter is based on visitors as well, but it does not modify the visited AST, it copies the nodes from the source AST to the destination AST.

Hope this helps,