How to programmatically alter source code in C++ file?

273 Views Asked by At

I need a way to take a C/C++ source code file, inspect and perform some modifications to it, and then write the modified variant back to disk. Possible use cases that I have for it are:

  1. Mutation testing, such as intentionally corrupting calculation in order to check if tests can catch it.
  2. Altering visibility scope or annotating functions and methods. In order to split a large file into several smaller files but still being able to link them together, I want to turn some static functions into external functions so that the linker can find them later.
  3. Generation of mock implementations of existing functions methods. For all externally visible functions, create a function with identical prototype but with empty/dummy body so that other code can link against it.

Are there existing solutions for such workflow?

I am mostly interested in dealing with functions/methods. The rest of information contained in a file, such as includes, type definitions etc. are less important for me, but they must be preserved in the output so that the end result remains syntactically correct.

A straightforward approach of applying a bunch of regular expressions to extract/modify the text is possible. But it is obviously not reliable in a any way. I would like to avoid writing a full-blown C++ parser. Even having such a parser does not solve the follow-up task of saving the modified parse tree back to a file.

1

There are 1 best solutions below

0
On

LibTooling and libclang are commonly used to develop such refactoring tools (clang-format, clang-tidy, etc.).