Modifying source code with clang plugin

I have an existing and working tool for modifying code from source to source using libtooling. Now I want to integrate this tool into clang so that users can compile the modified source without saving it somewhere.

The modification part is not problematic, Matchers + Rewriters work the same with clang, my problem is how to tell the compiler to reuse the source code after my changes.

My progress:

  • I found a conversation on cve-dev , but no specific information on how to do it
  • I also found clang :: ASTUnit :: Reparse , but I couldn't figure out how to call it. Nothing in clang sources uses it, and every attempt I've tried has been rewarded with crashes.
  • There was a similar question on StackOverflow but without a good answer
  • There are several plugins like traces that do the same modification to the source code, but it just calls the compiler twice.

I hope that based on the first two, I eventually find a working solution, but maybe someone already knows the answer and can help me with an example, or at least more specific instructions on how to implement it?

0


source to share


1 answer


You can wrap the EmitObjAction that generates the object file with WrapperFrontendAction . In the shell action, you can override the BeginInvocation () function. In this function, you can create your own ASTFrontendAction that crosses the AST and makes text changes using the Rewriter class.

When your action is complete, you can access the buffers in the Rewriter class. You can make a copy of these buffers and add them to PreprocessorOptions using addRemappedFile () . Since the PreprocessorOptions are connected to CompilerInstance, they are also used by the following EmitObjAction that you wrapped.



This means that EmitObjAction will actually read the modified source files.

You can get some inspiration from how the FixItRecompile class is used in Clang.

0


source







All Articles