1================ 2Getting Involved 3================ 4 5:program:`clang-tidy` has several own checks and can run Clang static analyzer 6checks, but its power is in the ability to easily write custom checks. 7 8Checks are organized in modules, which can be linked into :program:`clang-tidy` 9with minimal or no code changes in :program:`clang-tidy`. 10 11Checks can plug into the analysis on the preprocessor level using `PPCallbacks`_ 12or on the AST level using `AST Matchers`_. When an error is found, checks can 13report them in a way similar to how Clang diagnostics work. A fix-it hint can be 14attached to a diagnostic message. 15 16The interface provided by :program:`clang-tidy` makes it easy to write useful 17and precise checks in just a few lines of code. If you have an idea for a good 18check, the rest of this document explains how to do this. 19 20There are a few tools particularly useful when developing clang-tidy checks: 21 * ``add_new_check.py`` is a script to automate the process of adding a new 22 check, it will create the check, update the CMake file and create a test; 23 * ``rename_check.py`` does what the script name suggests, renames an existing 24 check; 25 * :program:`clang-query` is invaluable for interactive prototyping of AST 26 matchers and exploration of the Clang AST; 27 * `clang-check`_ with the ``-ast-dump`` (and optionally ``-ast-dump-filter``) 28 provides a convenient way to dump AST of a C++ program. 29 30If CMake is configured with ``CLANG_TIDY_ENABLE_STATIC_ANALYZER=NO``, 31:program:`clang-tidy` will not be built with support for the 32``clang-analyzer-*`` checks or the ``mpi-*`` checks. 33 34 35.. _AST Matchers: https://clang.llvm.org/docs/LibASTMatchers.html 36.. _PPCallbacks: https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html 37.. _clang-check: https://clang.llvm.org/docs/ClangCheck.html 38 39 40Choosing the Right Place for your Check 41--------------------------------------- 42 43If you have an idea of a check, you should decide whether it should be 44implemented as a: 45 46+ *Clang diagnostic*: if the check is generic enough, targets code patterns that 47 most probably are bugs (rather than style or readability issues), can be 48 implemented effectively and with extremely low false positive rate, it may 49 make a good Clang diagnostic. 50 51+ *Clang static analyzer check*: if the check requires some sort of control flow 52 analysis, it should probably be implemented as a static analyzer check. 53 54+ *clang-tidy check* is a good choice for linter-style checks, checks that are 55 related to a certain coding style, checks that address code readability, etc. 56 57 58Preparing your Workspace 59------------------------ 60 61If you are new to LLVM development, you should read the `Getting Started with 62the LLVM System`_, `Using Clang Tools`_ and `How To Setup Clang Tooling For 63LLVM`_ documents to check out and build LLVM, Clang and Clang Extra Tools with 64CMake. 65 66Once you are done, change to the ``llvm/clang-tools-extra`` directory, and 67let's start! 68 69.. _Getting Started with the LLVM System: https://llvm.org/docs/GettingStarted.html 70.. _Using Clang Tools: https://clang.llvm.org/docs/ClangTools.html 71.. _How To Setup Clang Tooling For LLVM: https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html 72 73 74The Directory Structure 75----------------------- 76 77:program:`clang-tidy` source code resides in the 78``llvm/clang-tools-extra`` directory and is structured as follows: 79 80:: 81 82 clang-tidy/ # Clang-tidy core. 83 |-- ClangTidy.h # Interfaces for users. 84 |-- ClangTidyCheck.h # Interfaces for checks. 85 |-- ClangTidyModule.h # Interface for clang-tidy modules. 86 |-- ClangTidyModuleRegistry.h # Interface for registering of modules. 87 ... 88 |-- google/ # Google clang-tidy module. 89 |-+ 90 |-- GoogleTidyModule.cpp 91 |-- GoogleTidyModule.h 92 ... 93 |-- llvm/ # LLVM clang-tidy module. 94 |-+ 95 |-- LLVMTidyModule.cpp 96 |-- LLVMTidyModule.h 97 ... 98 |-- objc/ # Objective-C clang-tidy module. 99 |-+ 100 |-- ObjCTidyModule.cpp 101 |-- ObjCTidyModule.h 102 ... 103 |-- tool/ # Sources of the clang-tidy binary. 104 ... 105 test/clang-tidy/ # Integration tests. 106 ... 107 unittests/clang-tidy/ # Unit tests. 108 |-- ClangTidyTest.h 109 |-- GoogleModuleTest.cpp 110 |-- LLVMModuleTest.cpp 111 |-- ObjCModuleTest.cpp 112 ... 113 114 115Writing a clang-tidy Check 116-------------------------- 117 118So you have an idea of a useful check for :program:`clang-tidy`. 119 120First, if you're not familiar with LLVM development, read through the `Getting 121Started with LLVM`_ document for instructions on setting up your workflow and 122the `LLVM Coding Standards`_ document to familiarize yourself with the coding 123style used in the project. For code reviews we mostly use `LLVM Phabricator`_. 124 125.. _Getting Started with LLVM: https://llvm.org/docs/GettingStarted.html 126.. _LLVM Coding Standards: https://llvm.org/docs/CodingStandards.html 127.. _LLVM Phabricator: https://llvm.org/docs/Phabricator.html 128 129Next, you need to decide which module the check belongs to. Modules 130are located in subdirectories of `clang-tidy/ 131<https://github.com/llvm/llvm-project/tree/master/clang-tools-extra/clang-tidy/>`_ 132and contain checks targeting a certain aspect of code quality (performance, 133readability, etc.), certain coding style or standard (Google, LLVM, CERT, etc.) 134or a widely used API (e.g. MPI). Their names are same as user-facing check 135groups names described :ref:`above <checks-groups-table>`. 136 137After choosing the module and the name for the check, run the 138``clang-tidy/add_new_check.py`` script to create the skeleton of the check and 139plug it to :program:`clang-tidy`. It's the recommended way of adding new checks. 140 141If we want to create a `readability-awesome-function-names`, we would run: 142 143.. code-block:: console 144 145 $ clang-tidy/add_new_check.py readability awesome-function-names 146 147 148The ``add_new_check.py`` script will: 149 * create the class for your check inside the specified module's directory and 150 register it in the module and in the build system; 151 * create a lit test file in the ``test/clang-tidy/`` directory; 152 * create a documentation file and include it into the 153 ``docs/clang-tidy/checks/list.rst``. 154 155Let's see in more detail at the check class definition: 156 157.. code-block:: c++ 158 159 ... 160 161 #include "../ClangTidyCheck.h" 162 163 namespace clang { 164 namespace tidy { 165 namespace readability { 166 167 ... 168 class AwesomeFunctionNamesCheck : public ClangTidyCheck { 169 public: 170 AwesomeFunctionNamesCheck(StringRef Name, ClangTidyContext *Context) 171 : ClangTidyCheck(Name, Context) {} 172 void registerMatchers(ast_matchers::MatchFinder *Finder) override; 173 void check(const ast_matchers::MatchFinder::MatchResult &Result) override; 174 }; 175 176 } // namespace readability 177 } // namespace tidy 178 } // namespace clang 179 180 ... 181 182Constructor of the check receives the ``Name`` and ``Context`` parameters, and 183must forward them to the ``ClangTidyCheck`` constructor. 184 185In our case the check needs to operate on the AST level and it overrides the 186``registerMatchers`` and ``check`` methods. If we wanted to analyze code on the 187preprocessor level, we'd need instead to override the ``registerPPCallbacks`` 188method. 189 190In the ``registerMatchers`` method we create an AST Matcher (see `AST Matchers`_ 191for more information) that will find the pattern in the AST that we want to 192inspect. The results of the matching are passed to the ``check`` method, which 193can further inspect them and report diagnostics. 194 195.. code-block:: c++ 196 197 using namespace ast_matchers; 198 199 void AwesomeFunctionNamesCheck::registerMatchers(MatchFinder *Finder) { 200 Finder->addMatcher(functionDecl().bind("x"), this); 201 } 202 203 void AwesomeFunctionNamesCheck::check(const MatchFinder::MatchResult &Result) { 204 const auto *MatchedDecl = Result.Nodes.getNodeAs<FunctionDecl>("x"); 205 if (!MatchedDecl->getIdentifier() || MatchedDecl->getName().startswith("awesome_")) 206 return; 207 diag(MatchedDecl->getLocation(), "function %0 is insufficiently awesome") 208 << MatchedDecl 209 << FixItHint::CreateInsertion(MatchedDecl->getLocation(), "awesome_"); 210 } 211 212(If you want to see an example of a useful check, look at 213`clang-tidy/google/ExplicitConstructorCheck.h 214<https://github.com/llvm/llvm-project/blob/master/clang-tools-extra/clang-tidy/google/ExplicitConstructorCheck.h>`_ 215and `clang-tidy/google/ExplicitConstructorCheck.cpp 216<https://reviews.llvm.org/diffusion/L/browse/clang-tools-extra/trunk/clang-tidy/google/ExplicitConstructorCheck.cpp>`_). 217 218 219Registering your Check 220---------------------- 221 222(The ``add_new_check.py`` takes care of registering the check in an existing 223module. If you want to create a new module or know the details, read on.) 224 225The check should be registered in the corresponding module with a distinct name: 226 227.. code-block:: c++ 228 229 class MyModule : public ClangTidyModule { 230 public: 231 void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override { 232 CheckFactories.registerCheck<ExplicitConstructorCheck>( 233 "my-explicit-constructor"); 234 } 235 }; 236 237Now we need to register the module in the ``ClangTidyModuleRegistry`` using a 238statically initialized variable: 239 240.. code-block:: c++ 241 242 static ClangTidyModuleRegistry::Add<MyModule> X("my-module", 243 "Adds my lint checks."); 244 245 246When using LLVM build system, we need to use the following hack to ensure the 247module is linked into the :program:`clang-tidy` binary: 248 249Add this near the ``ClangTidyModuleRegistry::Add<MyModule>`` variable: 250 251.. code-block:: c++ 252 253 // This anchor is used to force the linker to link in the generated object file 254 // and thus register the MyModule. 255 volatile int MyModuleAnchorSource = 0; 256 257And this to the main translation unit of the :program:`clang-tidy` binary (or 258the binary you link the ``clang-tidy`` library in) 259``clang-tidy/tool/ClangTidyMain.cpp``: 260 261.. code-block:: c++ 262 263 // This anchor is used to force the linker to link the MyModule. 264 extern volatile int MyModuleAnchorSource; 265 static int MyModuleAnchorDestination = MyModuleAnchorSource; 266 267 268Configuring Checks 269------------------ 270 271If a check needs configuration options, it can access check-specific options 272using the ``Options.get<Type>("SomeOption", DefaultValue)`` call in the check 273constructor. In this case the check should also override the 274``ClangTidyCheck::storeOptions`` method to make the options provided by the 275check discoverable. This method lets :program:`clang-tidy` know which options 276the check implements and what the current values are (e.g. for the 277``-dump-config`` command line option). 278 279.. code-block:: c++ 280 281 class MyCheck : public ClangTidyCheck { 282 const unsigned SomeOption1; 283 const std::string SomeOption2; 284 285 public: 286 MyCheck(StringRef Name, ClangTidyContext *Context) 287 : ClangTidyCheck(Name, Context), 288 SomeOption(Options.get("SomeOption1", -1U)), 289 SomeOption(Options.get("SomeOption2", "some default")) {} 290 291 void storeOptions(ClangTidyOptions::OptionMap &Opts) override { 292 Options.store(Opts, "SomeOption1", SomeOption1); 293 Options.store(Opts, "SomeOption2", SomeOption2); 294 } 295 ... 296 297Assuming the check is registered with the name "my-check", the option can then 298be set in a ``.clang-tidy`` file in the following way: 299 300.. code-block:: yaml 301 302 CheckOptions: 303 - key: my-check.SomeOption1 304 value: 123 305 - key: my-check.SomeOption2 306 value: 'some other value' 307 308If you need to specify check options on a command line, you can use the inline 309YAML format: 310 311.. code-block:: console 312 313 $ clang-tidy -config="{CheckOptions: [{key: a, value: b}, {key: x, value: y}]}" ... 314 315 316Testing Checks 317-------------- 318 319To run tests for :program:`clang-tidy` use the command: 320 321.. code-block:: console 322 323 $ ninja check-clang-tools 324 325:program:`clang-tidy` checks can be tested using either unit tests or 326`lit`_ tests. Unit tests may be more convenient to test complex replacements 327with strict checks. `Lit`_ tests allow using partial text matching and regular 328expressions which makes them more suitable for writing compact tests for 329diagnostic messages. 330 331The ``check_clang_tidy.py`` script provides an easy way to test both 332diagnostic messages and fix-its. It filters out ``CHECK`` lines from the test 333file, runs :program:`clang-tidy` and verifies messages and fixes with two 334separate `FileCheck`_ invocations: once with FileCheck's directive 335prefix set to ``CHECK-MESSAGES``, validating the diagnostic messages, 336and once with the directive prefix set to ``CHECK-FIXES``, running 337against the fixed code (i.e., the code after generated fix-its are 338applied). In particular, ``CHECK-FIXES:`` can be used to check 339that code was not modified by fix-its, by checking that it is present 340unchanged in the fixed code. The full set of `FileCheck`_ directives 341is available (e.g., ``CHECK-MESSAGES-SAME:``, ``CHECK-MESSAGES-NOT:``), though 342typically the basic ``CHECK`` forms (``CHECK-MESSAGES`` and ``CHECK-FIXES``) 343are sufficient for clang-tidy tests. Note that the `FileCheck`_ 344documentation mostly assumes the default prefix (``CHECK``), and hence 345describes the directive as ``CHECK:``, ``CHECK-SAME:``, ``CHECK-NOT:``, etc. 346Replace ``CHECK`` by either ``CHECK-FIXES`` or ``CHECK-MESSAGES`` for 347clang-tidy tests. 348 349An additional check enabled by ``check_clang_tidy.py`` ensures that 350if `CHECK-MESSAGES:` is used in a file then every warning or error 351must have an associated CHECK in that file. Or, you can use ``CHECK-NOTES:`` 352instead, if you want to **also** ensure that all the notes are checked. 353 354To use the ``check_clang_tidy.py`` script, put a .cpp file with the 355appropriate ``RUN`` line in the ``test/clang-tidy`` directory. Use 356``CHECK-MESSAGES:`` and ``CHECK-FIXES:`` lines to write checks against 357diagnostic messages and fixed code. 358 359It's advised to make the checks as specific as possible to avoid checks matching 360to incorrect parts of the input. Use ``[[@LINE+X]]``/``[[@LINE-X]]`` 361substitutions and distinct function and variable names in the test code. 362 363Here's an example of a test using the ``check_clang_tidy.py`` script (the full 364source code is at `test/clang-tidy/google-readability-casting.cpp`_): 365 366.. code-block:: c++ 367 368 // RUN: %check_clang_tidy %s google-readability-casting %t 369 370 void f(int a) { 371 int b = (int)a; 372 // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: redundant cast to the same type [google-readability-casting] 373 // CHECK-FIXES: int b = a; 374 } 375 376To check more than one scenario in the same test file use 377``-check-suffix=SUFFIX-NAME`` on ``check_clang_tidy.py`` command line or 378``-check-suffixes=SUFFIX-NAME-1,SUFFIX-NAME-2,...``. 379With ``-check-suffix[es]=SUFFIX-NAME`` you need to replace your ``CHECK-*`` 380directives with ``CHECK-MESSAGES-SUFFIX-NAME`` and ``CHECK-FIXES-SUFFIX-NAME``. 381 382Here's an example: 383 384.. code-block:: c++ 385 386 // RUN: %check_clang_tidy -check-suffix=USING-A %s misc-unused-using-decls %t -- -- -DUSING_A 387 // RUN: %check_clang_tidy -check-suffix=USING-B %s misc-unused-using-decls %t -- -- -DUSING_B 388 // RUN: %check_clang_tidy %s misc-unused-using-decls %t 389 ... 390 // CHECK-MESSAGES-USING-A: :[[@LINE-8]]:10: warning: using decl 'A' {{.*}} 391 // CHECK-MESSAGES-USING-B: :[[@LINE-7]]:10: warning: using decl 'B' {{.*}} 392 // CHECK-MESSAGES: :[[@LINE-6]]:10: warning: using decl 'C' {{.*}} 393 // CHECK-FIXES-USING-A-NOT: using a::A;$ 394 // CHECK-FIXES-USING-B-NOT: using a::B;$ 395 // CHECK-FIXES-NOT: using a::C;$ 396 397 398There are many dark corners in the C++ language, and it may be difficult to make 399your check work perfectly in all cases, especially if it issues fix-it hints. The 400most frequent pitfalls are macros and templates: 401 4021. code written in a macro body/template definition may have a different meaning 403 depending on the macro expansion/template instantiation; 4042. multiple macro expansions/template instantiations may result in the same code 405 being inspected by the check multiple times (possibly, with different 406 meanings, see 1), and the same warning (or a slightly different one) may be 407 issued by the check multiple times; :program:`clang-tidy` will deduplicate 408 _identical_ warnings, but if the warnings are slightly different, all of them 409 will be shown to the user (and used for applying fixes, if any); 4103. making replacements to a macro body/template definition may be fine for some 411 macro expansions/template instantiations, but easily break some other 412 expansions/instantiations. 413 414.. _lit: https://llvm.org/docs/CommandGuide/lit.html 415.. _FileCheck: https://llvm.org/docs/CommandGuide/FileCheck.html 416.. _test/clang-tidy/google-readability-casting.cpp: https://reviews.llvm.org/diffusion/L/browse/clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.cpp 417 418 419Running clang-tidy on LLVM 420-------------------------- 421 422To test a check it's best to try it out on a larger code base. LLVM and Clang 423are the natural targets as you already have the source code around. The most 424convenient way to run :program:`clang-tidy` is with a compile command database; 425CMake can automatically generate one, for a description of how to enable it see 426`How To Setup Clang Tooling For LLVM`_. Once ``compile_commands.json`` is in 427place and a working version of :program:`clang-tidy` is in ``PATH`` the entire 428code base can be analyzed with ``clang-tidy/tool/run-clang-tidy.py``. The script 429executes :program:`clang-tidy` with the default set of checks on every 430translation unit in the compile command database and displays the resulting 431warnings and errors. The script provides multiple configuration flags. 432 433.. _How To Setup Clang Tooling For LLVM: https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html 434 435 436* The default set of checks can be overridden using the ``-checks`` argument, 437 taking the identical format as :program:`clang-tidy` does. For example 438 ``-checks=-*,modernize-use-override`` will run the ``modernize-use-override`` 439 check only. 440 441* To restrict the files examined you can provide one or more regex arguments 442 that the file names are matched against. 443 ``run-clang-tidy.py clang-tidy/.*Check\.cpp`` will only analyze clang-tidy 444 checks. It may also be necessary to restrict the header files warnings are 445 displayed from using the ``-header-filter`` flag. It has the same behavior 446 as the corresponding :program:`clang-tidy` flag. 447 448* To apply suggested fixes ``-fix`` can be passed as an argument. This gathers 449 all changes in a temporary directory and applies them. Passing ``-format`` 450 will run clang-format over changed lines. 451 452 453On checks profiling 454------------------- 455 456:program:`clang-tidy` can collect per-check profiling info, and output it 457for each processed source file (translation unit). 458 459To enable profiling info collection, use the ``-enable-check-profile`` argument. 460The timings will be output to ``stderr`` as a table. Example output: 461 462.. code-block:: console 463 464 $ clang-tidy -enable-check-profile -checks=-*,readability-function-size source.cpp 465 ===-------------------------------------------------------------------------=== 466 clang-tidy checks profiling 467 ===-------------------------------------------------------------------------=== 468 Total Execution Time: 1.0282 seconds (1.0258 wall clock) 469 470 ---User Time--- --System Time-- --User+System-- ---Wall Time--- --- Name --- 471 0.9136 (100.0%) 0.1146 (100.0%) 1.0282 (100.0%) 1.0258 (100.0%) readability-function-size 472 0.9136 (100.0%) 0.1146 (100.0%) 1.0282 (100.0%) 1.0258 (100.0%) Total 473 474It can also store that data as JSON files for further processing. Example output: 475 476.. code-block:: console 477 478 $ clang-tidy -enable-check-profile -store-check-profile=. -checks=-*,readability-function-size source.cpp 479 $ # Note that there won't be timings table printed to the console. 480 $ ls /tmp/out/ 481 20180516161318717446360-source.cpp.json 482 $ cat 20180516161318717446360-source.cpp.json 483 { 484 "file": "/path/to/source.cpp", 485 "timestamp": "2018-05-16 16:13:18.717446360", 486 "profile": { 487 "time.clang-tidy.readability-function-size.wall": 1.0421266555786133e+00, 488 "time.clang-tidy.readability-function-size.user": 9.2088400000005421e-01, 489 "time.clang-tidy.readability-function-size.sys": 1.2418899999999974e-01 490 } 491 } 492 493There is only one argument that controls profile storage: 494 495* ``-store-check-profile=<prefix>`` 496 497 By default reports are printed in tabulated format to stderr. When this option 498 is passed, these per-TU profiles are instead stored as JSON. 499 If the prefix is not an absolute path, it is considered to be relative to the 500 directory from where you have run :program:`clang-tidy`. All ``.`` and ``..`` 501 patterns in the path are collapsed, and symlinks are resolved. 502 503 Example: 504 Let's suppose you have a source file named ``example.cpp``, located in the 505 ``/source`` directory. Only the input filename is used, not the full path 506 to the source file. Additionally, it is prefixed with the current timestamp. 507 508 * If you specify ``-store-check-profile=/tmp``, then the profile will be saved 509 to ``/tmp/<ISO8601-like timestamp>-example.cpp.json`` 510 511 * If you run :program:`clang-tidy` from within ``/foo`` directory, and specify 512 ``-store-check-profile=.``, then the profile will still be saved to 513 ``/foo/<ISO8601-like timestamp>-example.cpp.json`` 514