214 lines · plain
1==========2LibTooling3==========4 5LibTooling is a library to support writing standalone tools based on Clang.6This document will provide a basic walkthrough of how to write a tool using7LibTooling.8 9For the information on how to setup Clang Tooling for LLVM see10:doc:`HowToSetupToolingForLLVM`11 12Introduction13------------14 15Tools built with LibTooling, like Clang Plugins, run ``FrontendActions`` over16code.17 18.. See FIXME for a tutorial on how to write FrontendActions.19 20In this tutorial, we'll demonstrate the different ways of running Clang's21``SyntaxOnlyAction``, which runs a quick syntax check, over a bunch of code.22 23Parsing a code snippet in memory24--------------------------------25 26If you ever wanted to run a ``FrontendAction`` over some sample code, for27example to unit test parts of the Clang AST, ``runToolOnCode`` is what you28looked for. Let me give you an example:29 30.. code-block:: c++31 32 #include "clang/Tooling/Tooling.h"33 34 TEST(runToolOnCode, CanSyntaxCheckCode) {35 // runToolOnCode returns whether the action was correctly run over the36 // given code.37 EXPECT_TRUE(runToolOnCode(std::make_unique<clang::SyntaxOnlyAction>(), "class X {};"));38 }39 40Writing a standalone tool41-------------------------42 43Once you unit tested your ``FrontendAction`` to the point where it cannot44possibly break, it's time to create a standalone tool. For a standalone tool45to run clang, it first needs to figure out what command line arguments to use46for a specified file. To that end we create a ``CompilationDatabase``. There47are different ways to create a compilation database, and we need to support all48of them depending on command-line options. There's the ``CommonOptionsParser``49class that takes the responsibility to parse command-line parameters related to50compilation databases and inputs, so that all tools share the implementation.51 52Parsing common tools options53^^^^^^^^^^^^^^^^^^^^^^^^^^^^54 55``CompilationDatabase`` can be read from a build directory or the command line.56Using ``CommonOptionsParser`` allows for explicit specification of a compile57command line, specification of build path using the ``-p`` command-line option,58and automatic location of the compilation database using source files paths.59 60.. code-block:: c++61 62 #include "clang/Tooling/CommonOptionsParser.h"63 #include "llvm/Support/CommandLine.h"64 65 using namespace clang::tooling;66 using namespace llvm;67 68 // Apply a custom category to all command-line options so that they are the69 // only ones displayed.70 static cl::OptionCategory MyToolCategory("my-tool options");71 72 int main(int argc, const char **argv) {73 // CommonOptionsParser::create will parse arguments and create a74 // CompilationDatabase.75 auto ExpectedParser = CommonOptionsParser::create(argc, argv, MyToolCategory);76 if (!ExpectedParser) {77 // Fail gracefully for unsupported options.78 llvm::errs() << ExpectedParser.takeError();79 return 1;80 }81 CommonOptionsParser& OptionsParser = ExpectedParser.get();82 83 // Use OptionsParser.getCompilations() and OptionsParser.getSourcePathList()84 // to retrieve CompilationDatabase and the list of input file paths.85 }86 87Creating and running a ClangTool88^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^89 90Once we have a ``CompilationDatabase``, we can create a ``ClangTool`` and run91our ``FrontendAction`` over some code. For example, to run the92``SyntaxOnlyAction`` over the files "a.cc" and "b.cc" one would write:93 94.. code-block:: c++95 96 // A clang tool can run over a number of sources in the same process...97 std::vector<std::string> Sources;98 Sources.push_back("a.cc");99 Sources.push_back("b.cc");100 101 // We hand the CompilationDatabase we created and the sources to run over into102 // the tool constructor.103 ClangTool Tool(OptionsParser.getCompilations(), Sources);104 105 // The ClangTool needs a new FrontendAction for each translation unit we run106 // on. Thus, it takes a FrontendActionFactory as parameter. To create a107 // FrontendActionFactory from a given FrontendAction type, we call108 // newFrontendActionFactory<clang::SyntaxOnlyAction>().109 int result = Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>().get());110 111Putting it together --- the first tool112^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^113 114Now we combine the two previous steps into our first real tool. A more advanced115version of this example tool is also checked into the clang tree at116``tools/clang-check/ClangCheck.cpp``.117 118.. code-block:: c++119 120 // Declares clang::SyntaxOnlyAction.121 #include "clang/Frontend/FrontendActions.h"122 #include "clang/Tooling/CommonOptionsParser.h"123 #include "clang/Tooling/Tooling.h"124 // Declares llvm::cl::extrahelp.125 #include "llvm/Support/CommandLine.h"126 127 using namespace clang::tooling;128 using namespace llvm;129 130 // Apply a custom category to all command-line options so that they are the131 // only ones displayed.132 static cl::OptionCategory MyToolCategory("my-tool options");133 134 // CommonOptionsParser declares HelpMessage with a description of the common135 // command-line options related to the compilation database and input files.136 // It's nice to have this help message in all tools.137 static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);138 139 // A help message for this specific tool can be added afterwards.140 static cl::extrahelp MoreHelp("\nMore help text...\n");141 142 int main(int argc, const char **argv) {143 auto ExpectedParser = CommonOptionsParser::create(argc, argv, MyToolCategory);144 if (!ExpectedParser) {145 llvm::errs() << ExpectedParser.takeError();146 return 1;147 }148 CommonOptionsParser& OptionsParser = ExpectedParser.get();149 ClangTool Tool(OptionsParser.getCompilations(),150 OptionsParser.getSourcePathList());151 return Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>().get());152 }153 154Running the tool on some code155^^^^^^^^^^^^^^^^^^^^^^^^^^^^^156 157When you check out and build clang, clang-check is already built and available158to you in bin/clang-check inside your build directory.159 160You can run clang-check on a file in the llvm repository by specifying all the161needed parameters after a "``--``" separator:162 163.. code-block:: bash164 165 $ cd /path/to/source/llvm166 $ export BD=/path/to/build/llvm167 $ $BD/bin/clang-check tools/clang/tools/clang-check/ClangCheck.cpp -- \168 clang++ -D__STDC_CONSTANT_MACROS -D__STDC_LIMIT_MACROS \169 -Itools/clang/include -I$BD/include -Iinclude \170 -Itools/clang/lib/Headers -c171 172As an alternative, you can also configure cmake to output a compile command173database into its build directory:174 175.. code-block:: bash176 177 # Alternatively to calling cmake, use ccmake, toggle to advanced mode and178 # set the parameter CMAKE_EXPORT_COMPILE_COMMANDS from the UI.179 $ cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON .180 181This creates a file called ``compile_commands.json`` in the build directory.182Now you can run :program:`clang-check` over files in the project by specifying183the build path as first argument and some source files as further positional184arguments:185 186.. code-block:: bash187 188 $ cd /path/to/source/llvm189 $ export BD=/path/to/build/llvm190 $ $BD/bin/clang-check -p $BD tools/clang/tools/clang-check/ClangCheck.cpp191 192 193.. _libtooling_builtin_includes:194 195Builtin includes196^^^^^^^^^^^^^^^^197 198Clang tools need their builtin headers and search for them the same way Clang199does. Thus, the default location to look for builtin headers is in a path200``$(dirname /path/to/tool)/../lib/clang/3.3/include`` relative to the tool201binary. This works out-of-the-box for tools running from llvm's toplevel202binary directory after building clang-resource-headers, or if the tool is203running from the binary directory of a clang install next to the clang binary.204 205Tips: if your tool fails to find ``stddef.h`` or similar headers, call the tool206with ``-v`` and look at the search paths it looks through.207 208Linking209^^^^^^^210 211For a list of libraries to link, look at one of the tools' CMake files (for212example `clang-check/CMakeList.txt213<https://github.com/llvm/llvm-project/blob/main/clang/tools/clang-check/CMakeLists.txt>`_).214