Rewriting AST through Clang's LibTooling APIs

Hi All,

I am exploring the LibTooling APIs to parse and perform targeted modifications to the AST.
I see that Rewriter interface allows to insert or replace text, however the writing remains in terms of text.
May I know if rewriting the AST itself by means of inserting or modifying AST nodes, is supported?

Thank you.

Regards,
Koustubha

Hi All,

I am exploring the LibTooling APIs to parse and perform targeted modifications to the AST.
I see that Rewriter interface allows to insert or replace text, however the writing remains in terms of text.
May I know if rewriting the AST itself by means of inserting or modifying AST nodes, is supported?

To the best of my knowledge, not really.
There are a couple of places which do that: BodyFarm.cpp file in the static analyzer, and ASTImporter,
used in LLDB and the static analyzer.
Both usages are very often broken: the main problem is that once you start modifying the AST,
the chances of violating some internal invariants is pretty high,
and there’s no way to “check” that the modified AST is correct.

Just to summarize:
- Yes, modifying AST is possible, albeit difficult to do correctly.
- No, squeezing the modified AST back into source code in order to modify the source code is definitely not supported. Replacing text with the help of the AST's source locations information is the intended way of writing tools that modify source code with clang.

Thank you for clarifying.

Regards,
Koustubha

    Just to summarize:
    - Yes, modifying AST is possible, albeit difficult to do correctly.
    - No, squeezing the modified AST back into source code in order to
    modify the source code is definitely not supported. Replacing text with
    the help of the AST's source locations information is the intended way
    of writing tools that modify source code with clang.
    
    >
    > Hi All,
    >
    > I am exploring the LibTooling APIs to parse and perform targeted modifications to the AST.
    > I see that Rewriter interface allows to insert or replace text, however the writing remains in terms of text.
    > May I know if rewriting the AST itself by means of inserting or modifying AST nodes, is supported?
    
    To the best of my knowledge, not really.
    There are a couple of places which do that: BodyFarm.cpp file in the static analyzer, and ASTImporter,
    used in LLDB and the static analyzer.
    Both usages are very often broken: the main problem is that once you start modifying the AST,
    the chances of violating some internal invariants is pretty high,
    and there’s no way to “check” that the modified AST is correct.