A project template for building standalone Clang-based tools using LibTooling. It helps getting started writing tools for refactoring, static code analysis, auto-completion, and more.
- LLVM and Clang development headers and libraries (tested with LLVM 21)
- CMake 3.20+
git clone https://github.com/firolino/clang-tool
cd clang-tool
mkdir build && cd build
cmake ..
makeThe included FunctionCallTransformer (src/transformer/functioncalltransformer.cc) rewrites all function calls from functionName() to fn_functionName():
bin/clang-tool ../examples/simple.cc -- -std=c++17Output:
print(..)
#include <iostream>
using namespace std;
int bad_global = -1;
void fn_print()
{
cout << "hallo" << endl;
int variable = 0;
}
int main()
{
fn_print();
fn_print();
...
}
Multiple source files are supported:
bin/clang-tool s1.cc s2.cc -- -std=c++17There are multiple ways to provide compiler arguments:
-
Direct — place them after
--, as shown above. -
Compilation Database — if your project uses CMake, pass
-DCMAKE_EXPORT_COMPILE_COMMANDS=ONto generate acompile_commands.json. With this file present,--is not needed — clang-tool picks it up automatically. -
Makefiles — use Bear to generate a
compile_commands.jsonfrom a Makefile project:bear -- makeon a clean build.
The processing pipeline: main.cc → FrontendAction → Consumer → Transformer / Finder
src/main.cc— Parses CLI args, creates aClangTool, and runs it.src/consumer/consumer.cc—XConsumer::HandleTranslationUnit()wires up which transformers and finders run on each AST.src/transformer/— Base classTransformerwrapsASTContext+Rewriter. Subclasses implementstart()(register AST matchers) andrun()(match callback).src/finder/— Base classFinderwrapsASTContext(read-only, no rewriting). Samestart()/run()pattern.
- Create a class inheriting from
Transformer(rewriting) orFinder(read-only analysis). - Implement
start()to register AST matchers andrun()as the match callback. - Instantiate it in
XConsumer::HandleTranslationUnit()insrc/consumer/consumer.cc.
Example — to also print all integer variable declarations, uncomment in consumer.cc:
IntegerVariableFinder intFinder(context);
intFinder.start();MIT