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:`pp-trace` logs method calls on `PPCallbacks` for a source file 26 and is invaluable in understanding the preprocessor mechanism; 27 * :program:`clang-query` is invaluable for interactive prototyping of AST 28 matchers and exploration of the Clang AST; 29 * `clang-check`_ with the ``-ast-dump`` (and optionally ``-ast-dump-filter``) 30 provides a convenient way to dump AST of a C++ program. 31 32If CMake is configured with ``CLANG_TIDY_ENABLE_STATIC_ANALYZER=NO``, 33:program:`clang-tidy` will not be built with support for the 34``clang-analyzer-*`` checks or the ``mpi-*`` checks. 35 36 37.. _AST Matchers: https://clang.llvm.org/docs/LibASTMatchers.html 38.. _PPCallbacks: https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html 39.. _clang-check: https://clang.llvm.org/docs/ClangCheck.html 40 41 42Choosing the Right Place for your Check 43--------------------------------------- 44 45If you have an idea of a check, you should decide whether it should be 46implemented as a: 47 48+ *Clang diagnostic*: if the check is generic enough, targets code patterns that 49 most probably are bugs (rather than style or readability issues), can be 50 implemented effectively and with extremely low false positive rate, it may 51 make a good Clang diagnostic. 52 53+ *Clang static analyzer check*: if the check requires some sort of control flow 54 analysis, it should probably be implemented as a static analyzer check. 55 56+ *clang-tidy check* is a good choice for linter-style checks, checks that are 57 related to a certain coding style, checks that address code readability, etc. 58 59 60Preparing your Workspace 61------------------------ 62 63If you are new to LLVM development, you should read the `Getting Started with 64the LLVM System`_, `Using Clang Tools`_ and `How To Setup Clang Tooling For 65LLVM`_ documents to check out and build LLVM, Clang and Clang Extra Tools with 66CMake. 67 68Once you are done, change to the ``llvm/clang-tools-extra`` directory, and 69let's start! 70 71.. _Getting Started with the LLVM System: https://llvm.org/docs/GettingStarted.html 72.. _Using Clang Tools: https://clang.llvm.org/docs/ClangTools.html 73.. _How To Setup Clang Tooling For LLVM: https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html 74 75When you `configure the CMake build <https://llvm.org/docs/GettingStarted.html#local-llvm-configuration>`_, 76make sure that you enable the ``clang`` and ``clang-tools-extra`` projects to 77build :program:`clang-tidy`. 78Because your new check will have associated documentation, you will also want to install 79`Sphinx <https://www.sphinx-doc.org/en/master/>`_ and enable it in the CMake configuration. 80To save build time of the core Clang libraries you may want to only enable the ``X86`` 81target in the CMake configuration. 82 83 84The Directory Structure 85----------------------- 86 87:program:`clang-tidy` source code resides in the 88``llvm/clang-tools-extra`` directory and is structured as follows: 89 90:: 91 92 clang-tidy/ # Clang-tidy core. 93 |-- ClangTidy.h # Interfaces for users. 94 |-- ClangTidyCheck.h # Interfaces for checks. 95 |-- ClangTidyModule.h # Interface for clang-tidy modules. 96 |-- ClangTidyModuleRegistry.h # Interface for registering of modules. 97 ... 98 |-- google/ # Google clang-tidy module. 99 |-+ 100 |-- GoogleTidyModule.cpp 101 |-- GoogleTidyModule.h 102 ... 103 |-- llvm/ # LLVM clang-tidy module. 104 |-+ 105 |-- LLVMTidyModule.cpp 106 |-- LLVMTidyModule.h 107 ... 108 |-- objc/ # Objective-C clang-tidy module. 109 |-+ 110 |-- ObjCTidyModule.cpp 111 |-- ObjCTidyModule.h 112 ... 113 |-- tool/ # Sources of the clang-tidy binary. 114 ... 115 test/clang-tidy/ # Integration tests. 116 ... 117 unittests/clang-tidy/ # Unit tests. 118 |-- ClangTidyTest.h 119 |-- GoogleModuleTest.cpp 120 |-- LLVMModuleTest.cpp 121 |-- ObjCModuleTest.cpp 122 ... 123 124 125Writing a clang-tidy Check 126-------------------------- 127 128So you have an idea of a useful check for :program:`clang-tidy`. 129 130First, if you're not familiar with LLVM development, read through the `Getting Started 131with the LLVM System`_ document for instructions on setting up your workflow and 132the `LLVM Coding Standards`_ document to familiarize yourself with the coding 133style used in the project. For code reviews we currently use `LLVM Github`_, 134though historically we used Phabricator. 135 136.. _Getting Started with the LLVM System: https://llvm.org/docs/GettingStarted.html 137.. _LLVM Coding Standards: https://llvm.org/docs/CodingStandards.html 138.. _LLVM Github: https://github.com/llvm/llvm-project 139 140Next, you need to decide which module the check belongs to. Modules 141are located in subdirectories of `clang-tidy/ 142<https://github.com/llvm/llvm-project/tree/main/clang-tools-extra/clang-tidy/>`_ 143and contain checks targeting a certain aspect of code quality (performance, 144readability, etc.), certain coding style or standard (Google, LLVM, CERT, etc.) 145or a widely used API (e.g. MPI). Their names are the same as the user-facing 146check group names described :ref:`above <checks-groups-table>`. 147 148After choosing the module and the name for the check, run the 149``clang-tidy/add_new_check.py`` script to create the skeleton of the check and 150plug it to :program:`clang-tidy`. It's the recommended way of adding new checks. 151 152If we want to create a `readability-awesome-function-names`, we would run: 153 154.. code-block:: console 155 156 $ clang-tidy/add_new_check.py readability awesome-function-names 157 158 159The ``add_new_check.py`` script will: 160 * create the class for your check inside the specified module's directory and 161 register it in the module and in the build system; 162 * create a lit test file in the ``test/clang-tidy/`` directory; 163 * create a documentation file and include it into the 164 ``docs/clang-tidy/checks/list.rst``. 165 166Let's see in more detail at the check class definition: 167 168.. code-block:: c++ 169 170 ... 171 172 #include "../ClangTidyCheck.h" 173 174 namespace clang { 175 namespace tidy { 176 namespace readability { 177 178 ... 179 class AwesomeFunctionNamesCheck : public ClangTidyCheck { 180 public: 181 AwesomeFunctionNamesCheck(StringRef Name, ClangTidyContext *Context) 182 : ClangTidyCheck(Name, Context) {} 183 void registerMatchers(ast_matchers::MatchFinder *Finder) override; 184 void check(const ast_matchers::MatchFinder::MatchResult &Result) override; 185 }; 186 187 } // namespace readability 188 } // namespace tidy 189 } // namespace clang 190 191 ... 192 193Constructor of the check receives the ``Name`` and ``Context`` parameters, and 194must forward them to the ``ClangTidyCheck`` constructor. 195 196In our case the check needs to operate on the AST level and it overrides the 197``registerMatchers`` and ``check`` methods. If we wanted to analyze code on the 198preprocessor level, we'd need instead to override the ``registerPPCallbacks`` 199method. 200 201In the ``registerMatchers`` method we create an AST Matcher (see `AST Matchers`_ 202for more information) that will find the pattern in the AST that we want to 203inspect. The results of the matching are passed to the ``check`` method, which 204can further inspect them and report diagnostics. 205 206.. code-block:: c++ 207 208 using namespace ast_matchers; 209 210 void AwesomeFunctionNamesCheck::registerMatchers(MatchFinder *Finder) { 211 Finder->addMatcher(functionDecl().bind("x"), this); 212 } 213 214 void AwesomeFunctionNamesCheck::check(const MatchFinder::MatchResult &Result) { 215 const auto *MatchedDecl = Result.Nodes.getNodeAs<FunctionDecl>("x"); 216 if (!MatchedDecl->getIdentifier() || MatchedDecl->getName().startswith("awesome_")) 217 return; 218 diag(MatchedDecl->getLocation(), "function %0 is insufficiently awesome") 219 << MatchedDecl 220 << FixItHint::CreateInsertion(MatchedDecl->getLocation(), "awesome_"); 221 } 222 223(If you want to see an example of a useful check, look at 224`clang-tidy/google/ExplicitConstructorCheck.h 225<https://github.com/llvm/llvm-project/blob/main/clang-tools-extra/clang-tidy/google/ExplicitConstructorCheck.h>`_ 226and `clang-tidy/google/ExplicitConstructorCheck.cpp 227<https://reviews.llvm.org/diffusion/L/browse/clang-tools-extra/trunk/clang-tidy/google/ExplicitConstructorCheck.cpp>`_). 228 229If you need to interact with macros or preprocessor directives, you will want to 230override the method ``registerPPCallbacks``. The ``add_new_check.py`` script 231does not generate an override for this method in the starting point for your 232new check. 233 234If your check applies only under a specific set of language options, be sure 235to override the method ``isLanguageVersionSupported`` to reflect that. 236 237Check development tips 238---------------------- 239 240Writing your first check can be a daunting task, particularly if you are unfamiliar 241with the LLVM and Clang code bases. Here are some suggestions for orienting yourself 242in the codebase and working on your check incrementally. 243 244Guide to useful documentation 245^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 246 247Many of the support classes created for LLVM are used by Clang, such as `StringRef 248<https://llvm.org/docs/ProgrammersManual.html#the-stringref-class>`_ 249and `SmallVector <https://llvm.org/docs/ProgrammersManual.html#llvm-adt-smallvector-h>`_. 250These and other commonly used classes are described in the `Important and useful LLVM APIs 251<https://llvm.org/docs/ProgrammersManual.html#important-and-useful-llvm-apis>`_ and 252`Picking the Right Data Structure for the Task 253<https://llvm.org/docs/ProgrammersManual.html#picking-the-right-data-structure-for-a-task>`_ 254sections of the `LLVM Programmer's Manual 255<https://llvm.org/docs/ProgrammersManual.html>`_. You don't need to memorize all the 256details of these classes; the generated `doxygen documentation <https://llvm.org/doxygen/>`_ 257has everything if you need it. In the header `LLVM/ADT/STLExtras.h 258<https://llvm.org/doxygen/STLExtras_8h.html>`_ you'll find useful versions of the STL 259algorithms that operate on LLVM containers, such as `llvm::all_of 260<https://llvm.org/doxygen/STLExtras_8h.html#func-members>`_. 261 262Clang is implemented on top of LLVM and introduces its own set of classes that you 263will interact with while writing your check. When a check issues diagnostics and 264fix-its, these are associated with locations in the source code. Source code locations, 265source files, ranges of source locations and the `SourceManager 266<https://clang.llvm.org/doxygen/classclang_1_1SourceManager.html>`_ class provide 267the mechanisms for describing such locations. These and 268other topics are described in the `"Clang" CFE Internals Manual 269<https://clang.llvm.org/docs/InternalsManual.html>`_. Whereas the doxygen generated 270documentation serves as a reference to the internals of Clang, this document serves 271as a guide to other developers. Topics in that manual of interest to a check developer 272are: 273 274- `The Clang "Basic" Library 275 <https://clang.llvm.org/docs/InternalsManual.html#the-clang-basic-library>`_ for 276 information about diagnostics, fix-it hints and source locations. 277- `The Lexer and Preprocessor Library 278 <https://clang.llvm.org/docs/InternalsManual.html#the-lexer-and-preprocessor-library>`_ 279 for information about tokens, lexing (transforming characters into tokens) and the 280 preprocessor. 281- `The AST Library 282 <https://clang.llvm.org/docs/InternalsManual.html#the-ast-library>`_ 283 for information about how C++ source statements are represented as an abstract syntax 284 tree (AST). 285 286Most checks will interact with C++ source code via the AST. Some checks will interact 287with the preprocessor. The input source file is lexed and preprocessed and then parsed 288into the AST. Once the AST is fully constructed, the check is run by applying the check's 289registered AST matchers against the AST and invoking the check with the set of matched 290nodes from the AST. Monitoring the actions of the preprocessor is detached from the 291AST construction, but a check can collect information during preprocessing for later 292use by the check when nodes are matched by the AST. 293 294Every syntactic (and sometimes semantic) element of the C++ source code is represented by 295different classes in the AST. You select the portions of the AST you're interested in 296by composing AST matcher functions. You will want to study carefully the `AST Matcher 297Reference <https://clang.llvm.org/docs/LibASTMatchersReference.html>`_ to understand 298the relationship between the different matcher functions. 299 300Using the Transformer library 301^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 302 303The Transformer library allows you to write a check that transforms source code by 304expressing the transformation as a ``RewriteRule``. The Transformer library provides 305functions for composing edits to source code to create rewrite rules. Unless you need 306to perform low-level source location manipulation, you may want to consider writing your 307check with the Transformer library. The `Clang Transformer Tutorial 308<https://clang.llvm.org/docs/ClangTransformerTutorial.html>`_ describes the Transformer 309library in detail. 310 311To use the Transformer library, make the following changes to the code generated by 312the ``add_new_check.py`` script: 313 314- Include ``../utils/TransformerClangTidyCheck.h`` instead of ``../ClangTidyCheck.h`` 315- Change the base class of your check from ``ClangTidyCheck`` to ``TransformerClangTidyCheck`` 316- Delete the override of the ``registerMatchers`` and ``check`` methods in your check class. 317- Write a function that creates the ``RewriteRule`` for your check. 318- Call the function in your check's constructor to pass the rewrite rule to 319 ``TransformerClangTidyCheck``'s constructor. 320 321Developing your check incrementally 322^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 323 324The best way to develop your check is to start with the simple test cases and increase 325complexity incrementally. The test file created by the ``add_new_check.py`` script is 326a starting point for your test cases. A rough outline of the process looks like this: 327 328- Write a test case for your check. 329- Prototype matchers on the test file using :program:`clang-query`. 330- Capture the working matchers in the ``registerMatchers`` method. 331- Issue the necessary diagnostics and fix-its in the ``check`` method. 332- Add the necessary ``CHECK-MESSAGES`` and ``CHECK-FIXES`` annotations to your 333 test case to validate the diagnostics and fix-its. 334- Build the target ``check-clang-tools`` to confirm the test passes. 335- Repeat the process until all aspects of your check are covered by tests. 336 337The quickest way to prototype your matcher is to use :program:`clang-query` to 338interactively build up your matcher. For complicated matchers, build up a matching 339expression incrementally and use :program:`clang-query`'s ``let`` command to save named 340matching expressions to simplify your matcher. 341 342.. code-block:: console 343 344 clang-query> let c1 cxxRecordDecl() 345 clang-query> match c1 346 347Alternatively, pressing the tab key after a previous matcher's open parentheses 348would also show which matchers can be chained with the previous matcher, 349though some matchers that work may not be listed. Note that tab completion 350does not currently work on Windows. 351 352Just like breaking up a huge function into smaller chunks with 353intention-revealing names can help you understand a complex algorithm, breaking 354up a matcher into smaller matchers with intention-revealing names can help 355you understand a complicated matcher. 356 357Once you have a working :program:`clang-query` matcher, the C++ API matchers 358will be the same or similar to your interactively constructed matcher (there 359can be cases where they differ slightly). You can use local variables to preserve 360your intention-revealing names that you applied to nested matchers. 361 362Creating private matchers 363^^^^^^^^^^^^^^^^^^^^^^^^^ 364 365Sometimes you want to match a specific aspect of the AST that isn't provided by the 366existing AST matchers. You can create your own private matcher using the same 367infrastructure as the public matchers. A private matcher can simplify the processing 368in your ``check`` method by eliminating complex hand-crafted AST traversal of the 369matched nodes. Using the private matcher allows you to select the desired portions 370of the AST directly in the matcher and refer to it by a bound name in the ``check`` 371method. 372 373Unit testing helper code 374^^^^^^^^^^^^^^^^^^^^^^^^ 375 376Private custom matchers are a good example of auxiliary support code for your check 377that can be tested with a unit test. It will be easier to test your matchers or 378other support classes by writing a unit test than by writing a ``FileCheck`` integration 379test. The ``ASTMatchersTests`` target contains unit tests for the public AST matcher 380classes and is a good source of testing idioms for matchers. 381 382You can build the Clang-tidy unit tests by building the ``ClangTidyTests`` target. 383Test targets in LLVM and Clang are excluded from the "build all" style action of 384IDE-based CMake generators, so you need to explicitly build the target for the unit 385tests to be built. 386 387Making your check robust 388^^^^^^^^^^^^^^^^^^^^^^^^ 389 390Once you've covered your check with the basic "happy path" scenarios, you'll want to 391torture your check with as many edge cases as you can cover in order to ensure your 392check is robust. Running your check on a large code base, such as Clang/LLVM, is a 393good way to catch things you forgot to account for in your matchers. However, the 394LLVM code base may be insufficient for testing purposes as it was developed against a 395particular set of coding styles and quality measures. The larger the corpus of code 396the check is tested against, the higher confidence the community will have in the 397check's efficacy and false positive rate. 398 399Some suggestions to ensure your check is robust: 400 401- Create header files that contain code matched by your check. 402- Validate that fix-its are properly applied to test header files with 403 :program:`clang-tidy`. You will need to perform this test manually until 404 automated support for checking messages and fix-its is added to the 405 ``check_clang_tidy.py`` script. 406- Define macros that contain code matched by your check. 407- Define template classes that contain code matched by your check. 408- Define template specializations that contain code matched by your check. 409- Test your check under both Windows and Linux environments. 410- Watch out for high false positive rates. Ideally, a check would have no false 411 positives, but given that matching against an AST is not control- or data flow- 412 sensitive, a number of false positives are expected. The higher the false 413 positive rate, the less likely the check will be adopted in practice. 414 Mechanisms should be put in place to help the user manage false positives. 415- There are two primary mechanisms for managing false positives: supporting a 416 code pattern which allows the programmer to silence the diagnostic in an ad 417 hoc manner and check configuration options to control the behavior of the check. 418- Consider supporting a code pattern to allow the programmer to silence the 419 diagnostic whenever such a code pattern can clearly express the programmer's 420 intent. For example, allowing an explicit cast to ``void`` to silence an 421 unused variable diagnostic. 422- Consider adding check configuration options to allow the user to opt into 423 more aggressive checking behavior without burdening users for the common 424 high-confidence cases. 425 426Documenting your check 427^^^^^^^^^^^^^^^^^^^^^^ 428 429The ``add_new_check.py`` script creates entries in the 430`release notes <https://clang.llvm.org/extra/ReleaseNotes.html>`_, the list of 431checks and a new file for the check documentation itself. It is recommended that you 432have a concise summation of what your check does in a single sentence that is repeated 433in the release notes, as the first sentence in the doxygen comments in the header file 434for your check class and as the first sentence of the check documentation. Avoid the 435phrase "this check" in your check summation and check documentation. 436 437If your check relates to a published coding guideline (C++ Core Guidelines, MISRA, etc.) 438or style guide, provide links to the relevant guideline or style guide sections in your 439check documentation. 440 441Provide enough examples of the diagnostics and fix-its provided by the check so that a 442user can easily understand what will happen to their code when the check is run. 443If there are exceptions or limitations to your check, document them thoroughly. This 444will help users understand the scope of the diagnostics and fix-its provided by the check. 445 446Building the target ``docs-clang-tools-html`` will run the Sphinx documentation generator 447and create documentation HTML files in the tools/clang/tools/extra/docs/html directory in 448your build tree. Make sure that your check is correctly shown in the release notes and the 449list of checks. Make sure that the formatting and structure of your check's documentation 450looks correct. 451 452 453Registering your Check 454---------------------- 455 456(The ``add_new_check.py`` script takes care of registering the check in an existing 457module. If you want to create a new module or know the details, read on.) 458 459The check should be registered in the corresponding module with a distinct name: 460 461.. code-block:: c++ 462 463 class MyModule : public ClangTidyModule { 464 public: 465 void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override { 466 CheckFactories.registerCheck<ExplicitConstructorCheck>( 467 "my-explicit-constructor"); 468 } 469 }; 470 471Now we need to register the module in the ``ClangTidyModuleRegistry`` using a 472statically initialized variable: 473 474.. code-block:: c++ 475 476 static ClangTidyModuleRegistry::Add<MyModule> X("my-module", 477 "Adds my lint checks."); 478 479 480When using LLVM build system, we need to use the following hack to ensure the 481module is linked into the :program:`clang-tidy` binary: 482 483Add this near the ``ClangTidyModuleRegistry::Add<MyModule>`` variable: 484 485.. code-block:: c++ 486 487 // This anchor is used to force the linker to link in the generated object file 488 // and thus register the MyModule. 489 volatile int MyModuleAnchorSource = 0; 490 491And this to the main translation unit of the :program:`clang-tidy` binary (or 492the binary you link the ``clang-tidy`` library in) 493``clang-tidy/ClangTidyForceLinker.h``: 494 495.. code-block:: c++ 496 497 // This anchor is used to force the linker to link the MyModule. 498 extern volatile int MyModuleAnchorSource; 499 static int MyModuleAnchorDestination = MyModuleAnchorSource; 500 501 502Configuring Checks 503------------------ 504 505If a check needs configuration options, it can access check-specific options 506using the ``Options.get<Type>("SomeOption", DefaultValue)`` call in the check 507constructor. In this case the check should also override the 508``ClangTidyCheck::storeOptions`` method to make the options provided by the 509check discoverable. This method lets :program:`clang-tidy` know which options 510the check implements and what the current values are (e.g. for the 511``-dump-config`` command line option). 512 513.. code-block:: c++ 514 515 class MyCheck : public ClangTidyCheck { 516 const unsigned SomeOption1; 517 const std::string SomeOption2; 518 519 public: 520 MyCheck(StringRef Name, ClangTidyContext *Context) 521 : ClangTidyCheck(Name, Context), 522 SomeOption1(Options.get("SomeOption1", -1U)), 523 SomeOption2(Options.get("SomeOption2", "some default")) {} 524 525 void storeOptions(ClangTidyOptions::OptionMap &Opts) override { 526 Options.store(Opts, "SomeOption1", SomeOption1); 527 Options.store(Opts, "SomeOption2", SomeOption2); 528 } 529 ... 530 531Assuming the check is registered with the name "my-check", the option can then 532be set in a ``.clang-tidy`` file in the following way: 533 534.. code-block:: yaml 535 536 CheckOptions: 537 my-check.SomeOption1: 123 538 my-check.SomeOption2: 'some other value' 539 540If you need to specify check options on a command line, you can use the inline 541YAML format: 542 543.. code-block:: console 544 545 $ clang-tidy -config="{CheckOptions: {a: b, x: y}}" ... 546 547 548Testing Checks 549-------------- 550 551To run tests for :program:`clang-tidy`, build the ``check-clang-tools`` target. 552For instance, if you configured your CMake build with the ninja project generator, 553use the command: 554 555.. code-block:: console 556 557 $ ninja check-clang-tools 558 559:program:`clang-tidy` checks can be tested using either unit tests or 560`lit`_ tests. Unit tests may be more convenient to test complex replacements 561with strict checks. `Lit`_ tests allow using partial text matching and regular 562expressions which makes them more suitable for writing compact tests for 563diagnostic messages. 564 565The ``check_clang_tidy.py`` script provides an easy way to test both 566diagnostic messages and fix-its. It filters out ``CHECK`` lines from the test 567file, runs :program:`clang-tidy` and verifies messages and fixes with two 568separate `FileCheck`_ invocations: once with FileCheck's directive 569prefix set to ``CHECK-MESSAGES``, validating the diagnostic messages, 570and once with the directive prefix set to ``CHECK-FIXES``, running 571against the fixed code (i.e., the code after generated fix-its are 572applied). In particular, ``CHECK-FIXES:`` can be used to check 573that code was not modified by fix-its, by checking that it is present 574unchanged in the fixed code. The full set of `FileCheck`_ directives 575is available (e.g., ``CHECK-MESSAGES-SAME:``, ``CHECK-MESSAGES-NOT:``), though 576typically the basic ``CHECK`` forms (``CHECK-MESSAGES`` and ``CHECK-FIXES``) 577are sufficient for clang-tidy tests. Note that the `FileCheck`_ 578documentation mostly assumes the default prefix (``CHECK``), and hence 579describes the directive as ``CHECK:``, ``CHECK-SAME:``, ``CHECK-NOT:``, etc. 580Replace ``CHECK`` by either ``CHECK-FIXES`` or ``CHECK-MESSAGES`` for 581clang-tidy tests. 582 583An additional check enabled by ``check_clang_tidy.py`` ensures that 584if `CHECK-MESSAGES:` is used in a file then every warning or error 585must have an associated CHECK in that file. Or, you can use ``CHECK-NOTES:`` 586instead, if you want to **also** ensure that all the notes are checked. 587 588To use the ``check_clang_tidy.py`` script, put a .cpp file with the 589appropriate ``RUN`` line in the ``test/clang-tidy`` directory. Use 590``CHECK-MESSAGES:`` and ``CHECK-FIXES:`` lines to write checks against 591diagnostic messages and fixed code. 592 593It's advised to make the checks as specific as possible to avoid checks matching 594to incorrect parts of the input. Use ``[[@LINE+X]]``/``[[@LINE-X]]`` 595substitutions and distinct function and variable names in the test code. 596 597Here's an example of a test using the ``check_clang_tidy.py`` script (the full 598source code is at `test/clang-tidy/checkers/google/readability-casting.cpp`_): 599 600.. code-block:: c++ 601 602 // RUN: %check_clang_tidy %s google-readability-casting %t 603 604 void f(int a) { 605 int b = (int)a; 606 // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: redundant cast to the same type [google-readability-casting] 607 // CHECK-FIXES: int b = a; 608 } 609 610To check more than one scenario in the same test file use 611``-check-suffix=SUFFIX-NAME`` on ``check_clang_tidy.py`` command line or 612``-check-suffixes=SUFFIX-NAME-1,SUFFIX-NAME-2,...``. 613With ``-check-suffix[es]=SUFFIX-NAME`` you need to replace your ``CHECK-*`` 614directives with ``CHECK-MESSAGES-SUFFIX-NAME`` and ``CHECK-FIXES-SUFFIX-NAME``. 615 616Here's an example: 617 618.. code-block:: c++ 619 620 // RUN: %check_clang_tidy -check-suffix=USING-A %s misc-unused-using-decls %t -- -- -DUSING_A 621 // RUN: %check_clang_tidy -check-suffix=USING-B %s misc-unused-using-decls %t -- -- -DUSING_B 622 // RUN: %check_clang_tidy %s misc-unused-using-decls %t 623 ... 624 // CHECK-MESSAGES-USING-A: :[[@LINE-8]]:10: warning: using decl 'A' {{.*}} 625 // CHECK-MESSAGES-USING-B: :[[@LINE-7]]:10: warning: using decl 'B' {{.*}} 626 // CHECK-MESSAGES: :[[@LINE-6]]:10: warning: using decl 'C' {{.*}} 627 // CHECK-FIXES-USING-A-NOT: using a::A;$ 628 // CHECK-FIXES-USING-B-NOT: using a::B;$ 629 // CHECK-FIXES-NOT: using a::C;$ 630 631There are many dark corners in the C++ language, and it may be difficult to make 632your check work perfectly in all cases, especially if it issues fix-it hints. The 633most frequent pitfalls are macros and templates: 634 6351. code written in a macro body/template definition may have a different meaning 636 depending on the macro expansion/template instantiation; 6372. multiple macro expansions/template instantiations may result in the same code 638 being inspected by the check multiple times (possibly, with different 639 meanings, see 1), and the same warning (or a slightly different one) may be 640 issued by the check multiple times; :program:`clang-tidy` will deduplicate 641 _identical_ warnings, but if the warnings are slightly different, all of them 642 will be shown to the user (and used for applying fixes, if any); 6433. making replacements to a macro body/template definition may be fine for some 644 macro expansions/template instantiations, but easily break some other 645 expansions/instantiations. 646 647If you need multiple files to exercise all the aspects of your check, it is 648recommended you place them in a subdirectory named for the check under the ``Inputs`` 649directory for the module containing your check. This keeps the test directory from 650getting cluttered. 651 652If you need to validate how your check interacts with system header files, a set 653of simulated system header files is located in the ``checkers/Inputs/Headers`` 654directory. The path to this directory is available in a lit test with the variable 655``%clang_tidy_headers``. 656 657.. _lit: https://llvm.org/docs/CommandGuide/lit.html 658.. _FileCheck: https://llvm.org/docs/CommandGuide/FileCheck.html 659.. _test/clang-tidy/checkers/google/readability-casting.cpp: https://github.com/llvm/llvm-project/blob/main/clang-tools-extra/test/clang-tidy/checkers/google/readability-casting.cpp 660 661Out-of-tree check plugins 662------------------------- 663 664 665Developing an out-of-tree check as a plugin largely follows the steps 666outlined above, including creating a new module and doing the hacks to 667register the module. The plugin is a shared library whose code lives outside 668the clang-tidy build system. Build and link this shared library against 669LLVM as done for other kinds of Clang plugins. If using CMake, use the keyword 670``MODULE`` while invoking ``add_library`` or ``llvm_add_library``. 671 672The plugin can be loaded by passing `-load` to `clang-tidy` in addition to the 673names of the checks to enable. 674 675.. code-block:: console 676 677 $ clang-tidy --checks=-*,my-explicit-constructor -list-checks -load myplugin.so 678 679There is no expectations regarding ABI and API stability, so the plugin must be 680compiled against the version of clang-tidy that will be loading the plugin. 681 682The plugins can use threads, TLS, or any other facilities available to in-tree 683code which is accessible from the external headers. 684 685Note that testing out-of-tree checks might involve getting ``llvm-lit`` from an LLVM 686installation compiled from source. See `Getting Started with the LLVM System`_ for ways 687to do so. 688 689Alternatively, get `lit`_ following the `test-suite guide`_ and get the `FileCheck`_ binary, 690and write a version of `check_clang_tidy.py`_ to suit your needs. 691 692.. _Getting Started with the LLVM System: https://llvm.org/docs/GettingStarted.html 693.. _test-suite guide: https://llvm.org/docs/TestSuiteGuide.html 694.. _lit: https://llvm.org/docs/CommandGuide/lit.html 695.. _FileCheck: https://llvm.org/docs/CommandGuide/FileCheck.html 696.. _check_clang_tidy.py: https://github.com/llvm/llvm-project/blob/main/clang-tools-extra/test/clang-tidy/check_clang_tidy.py 697 698Running clang-tidy on LLVM 699-------------------------- 700 701To test a check it's best to try it out on a larger code base. LLVM and Clang 702are the natural targets as you already have the source code around. The most 703convenient way to run :program:`clang-tidy` is with a compile command database; 704CMake can automatically generate one, for a description of how to enable it see 705`How To Setup Clang Tooling For LLVM`_. Once ``compile_commands.json`` is in 706place and a working version of :program:`clang-tidy` is in ``PATH`` the entire 707code base can be analyzed with ``clang-tidy/tool/run-clang-tidy.py``. The script 708executes :program:`clang-tidy` with the default set of checks on every 709translation unit in the compile command database and displays the resulting 710warnings and errors. The script provides multiple configuration flags. 711 712.. _How To Setup Clang Tooling For LLVM: https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html 713 714 715* The default set of checks can be overridden using the ``-checks`` argument, 716 taking the identical format as :program:`clang-tidy` does. For example 717 ``-checks=-*,modernize-use-override`` will run the ``modernize-use-override`` 718 check only. 719 720* To restrict the files examined you can provide one or more regex arguments 721 that the file names are matched against. 722 ``run-clang-tidy.py clang-tidy/.*Check\.cpp`` will only analyze `clang-tidy` 723 checks. It may also be necessary to restrict the header files that warnings 724 are displayed from by using the ``-header-filter`` and ``-exclude-header-filter`` flags. 725 They have the same behavior as the corresponding :program:`clang-tidy` flags. 726 727* To apply suggested fixes ``-fix`` can be passed as an argument. This gathers 728 all changes in a temporary directory and applies them. Passing ``-format`` 729 will run clang-format over changed lines. 730 731 732On checks profiling 733------------------- 734 735:program:`clang-tidy` can collect per-check profiling info, and output it 736for each processed source file (translation unit). 737 738To enable profiling info collection, use the ``-enable-check-profile`` argument. 739The timings will be output to ``stderr`` as a table. Example output: 740 741.. code-block:: console 742 743 $ clang-tidy -enable-check-profile -checks=-*,readability-function-size source.cpp 744 ===-------------------------------------------------------------------------=== 745 clang-tidy checks profiling 746 ===-------------------------------------------------------------------------=== 747 Total Execution Time: 1.0282 seconds (1.0258 wall clock) 748 749 ---User Time--- --System Time-- --User+System-- ---Wall Time--- --- Name --- 750 0.9136 (100.0%) 0.1146 (100.0%) 1.0282 (100.0%) 1.0258 (100.0%) readability-function-size 751 0.9136 (100.0%) 0.1146 (100.0%) 1.0282 (100.0%) 1.0258 (100.0%) Total 752 753It can also store that data as JSON files for further processing. Example output: 754 755.. code-block:: console 756 757 $ clang-tidy -enable-check-profile -store-check-profile=. -checks=-*,readability-function-size source.cpp 758 $ # Note that there won't be timings table printed to the console. 759 $ ls /tmp/out/ 760 20180516161318717446360-source.cpp.json 761 $ cat 20180516161318717446360-source.cpp.json 762 { 763 "file": "/path/to/source.cpp", 764 "timestamp": "2018-05-16 16:13:18.717446360", 765 "profile": { 766 "time.clang-tidy.readability-function-size.wall": 1.0421266555786133e+00, 767 "time.clang-tidy.readability-function-size.user": 9.2088400000005421e-01, 768 "time.clang-tidy.readability-function-size.sys": 1.2418899999999974e-01 769 } 770 } 771 772There is only one argument that controls profile storage: 773 774* ``-store-check-profile=<prefix>`` 775 776 By default reports are printed in tabulated format to stderr. When this option 777 is passed, these per-TU profiles are instead stored as JSON. 778 If the prefix is not an absolute path, it is considered to be relative to the 779 directory from where you have run :program:`clang-tidy`. All ``.`` and ``..`` 780 patterns in the path are collapsed, and symlinks are resolved. 781 782 Example: 783 Let's suppose you have a source file named ``example.cpp``, located in the 784 ``/source`` directory. Only the input filename is used, not the full path 785 to the source file. Additionally, it is prefixed with the current timestamp. 786 787 * If you specify ``-store-check-profile=/tmp``, then the profile will be saved 788 to ``/tmp/<ISO8601-like timestamp>-example.cpp.json`` 789 790 * If you run :program:`clang-tidy` from within ``/foo`` directory, and specify 791 ``-store-check-profile=.``, then the profile will still be saved to 792 ``/foo/<ISO8601-like timestamp>-example.cpp.json``