Lines Matching +full:check +full:- +full:docs +full:- +full:build

5 :program:`clang-tidy` has several own checks and can run Clang static analyzer
8 Checks are organized in modules, which can be linked into :program:`clang-tidy`
9 with minimal or no code changes in :program:`clang-tidy`.
13 report them in a way similar to how Clang diagnostics work. A fix-it hint can be
16 The interface provided by :program:`clang-tidy` makes it easy to write useful
18 check, the rest of this document explains how to do this.
20 There are a few tools particularly useful when developing clang-tidy checks:
22 check, it will create the check, update the CMake file and create a test;
24 check;
25 * :program:`pp-trace` logs method calls on `PPCallbacks` for a source file
27 * :program:`clang-query` is invaluable for interactive prototyping of AST
29 * `clang-check`_ with the ``-ast-dump`` (and optionally ``-ast-dump-filter``)
33 :program:`clang-tidy` will not be built with support for the
34 ``clang-analyzer-*`` checks or the ``mpi-*`` checks.
37 .. _AST Matchers: https://clang.llvm.org/docs/LibASTMatchers.html
39 .. _clang-check: https://clang.llvm.org/docs/ClangCheck.html
42 Choosing the Right Place for your Check
43 ---------------------------------------
45 If you have an idea of a check, you should decide whether it should be
48 + *Clang diagnostic*: if the check is generic enough, targets code patterns that
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.
56 + *clang-tidy check* is a good choice for linter-style checks, checks that are
61 ------------------------
65 LLVM`_ documents to check out and build LLVM, Clang and Clang Extra Tools with
68 Once you are done, change to the ``llvm/clang-tools-extra`` directory, and
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
75 When you `configure the CMake build <https://llvm.org/docs/GettingStarted.html#local-llvm-configuration>`_,
76 make sure that you enable the ``clang`` and ``clang-tools-extra`` projects to
77 build :program:`clang-tidy`.
78 Because 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.
80 To save build time of the core Clang libraries you may want to only enable the ``X86``
85 -----------------------
87 :program:`clang-tidy` source code resides in the
88 ``llvm/clang-tools-extra`` directory and is structured as follows:
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.
98 |-- google/ # Google clang-tidy module.
99 |-+
100 |-- GoogleTidyModule.cpp
101 |-- GoogleTidyModule.h
103 |-- llvm/ # LLVM clang-tidy module.
104 |-+
105 |-- LLVMTidyModule.cpp
106 |-- LLVMTidyModule.h
108 |-- objc/ # Objective-C clang-tidy module.
109 |-+
110 |-- ObjCTidyModule.cpp
111 |-- ObjCTidyModule.h
113 |-- tool/ # Sources of the clang-tidy binary.
115 test/clang-tidy/ # Integration tests.
117 unittests/clang-tidy/ # Unit tests.
118 |-- ClangTidyTest.h
119 |-- GoogleModuleTest.cpp
120 |-- LLVMModuleTest.cpp
121 |-- ObjCModuleTest.cpp
125 Writing a clang-tidy Check
126 --------------------------
128 So you have an idea of a useful check for :program:`clang-tidy`.
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
140 Next, you need to decide which module the check belongs to. Modules
141 are located in subdirectories of `clang-tidy/
142 <https://github.com/llvm/llvm-project/tree/main/clang-tools-extra/clang-tidy/>`_
145 or a widely used API (e.g. MPI). Their names are the same as the user-facing
146 check group names described :ref:`above <checks-groups-table>`.
148 After 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
150 plug it to :program:`clang-tidy`. It's the recommended way of adding new checks.
152 If we want to create a `readability-awesome-function-names`, we would run:
154 .. code-block:: console
156 $ clang-tidy/add_new_check.py readability awesome-function-names
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;
164 ``docs/clang-tidy/checks/list.rst``.
166 Let's see in more detail at the check class definition:
168 .. code-block:: c++
184 void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
193 Constructor of the check receives the ``Name`` and ``Context`` parameters, and
196 In 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
203 inspect. The results of the matching are passed to the ``check`` method, which
206 .. code-block:: c++
211 Finder->addMatcher(functionDecl().bind("x"), this);
214 void AwesomeFunctionNamesCheck::check(const MatchFinder::MatchResult &Result) {
216 if (!MatchedDecl->getIdentifier() || MatchedDecl->getName().startswith("awesome_"))
218 diag(MatchedDecl->getLocation(), "function %0 is insufficiently awesome")
220 << FixItHint::CreateInsertion(MatchedDecl->getLocation(), "awesome_");
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>`_
226 and `clang-tidy/google/ExplicitConstructorCheck.cpp
227 <https://reviews.llvm.org/diffusion/L/browse/clang-tools-extra/trunk/clang-tidy/google/ExplicitConstructorCheck.cpp>`_).
232 new check.
234 If your check applies only under a specific set of language options, be sure
237 Check development tips
238 ----------------------
240 Writing your first check can be a daunting task, particularly if you are unfamiliar
242 in the codebase and working on your check incrementally.
248 <https://llvm.org/docs/ProgrammersManual.html#the-stringref-class>`_
249 and `SmallVector <https://llvm.org/docs/ProgrammersManual.html#llvm-adt-smallvector-h>`_.
251 <https://llvm.org/docs/ProgrammersManual.html#important-and-useful-llvm-apis>`_ and
253 <https://llvm.org/docs/ProgrammersManual.html#picking-the-right-data-structure-for-a-task>`_
255 <https://llvm.org/docs/ProgrammersManual.html>`_. You don't need to memorize all the
260 <https://llvm.org/doxygen/STLExtras_8h.html#func-members>`_.
263 will interact with while writing your check. When a check issues diagnostics and
264 fix-its, these are associated with locations in the source code. Source code locations,
269 <https://clang.llvm.org/docs/InternalsManual.html>`_. Whereas the doxygen generated
271 as a guide to other developers. Topics in that manual of interest to a check developer
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>`_
281 - `The AST Library
282 <https://clang.llvm.org/docs/InternalsManual.html#the-ast-library>`_
288 into the AST. Once the AST is fully constructed, the check is run by applying the check's
289 registered AST matchers against the AST and invoking the check with the set of matched
291 AST construction, but a check can collect information during preprocessing for later
292 use by the check when nodes are matched by the AST.
297 Reference <https://clang.llvm.org/docs/LibASTMatchersReference.html>`_ to understand
303 The Transformer library allows you to write a check that transforms source code by
306 to perform low-level source location manipulation, you may want to consider writing your
307 check with the Transformer library. The `Clang Transformer Tutorial
308 <https://clang.llvm.org/docs/ClangTransformerTutorial.html>`_ describes the Transformer
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
321 Developing your check incrementally
324 The best way to develop your check is to start with the simple test cases and increase
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.
337 The quickest way to prototype your matcher is to use :program:`clang-query` to
338 interactively build up your matcher. For complicated matchers, build up a matching
339 expression incrementally and use :program:`clang-query`'s ``let`` command to save named
342 .. code-block:: console
344 clang-query> let c1 cxxRecordDecl()
345 clang-query> match c1
353 intention-revealing names can help you understand a complex algorithm, breaking
354 up a matcher into smaller matchers with intention-revealing names can help
357 Once you have a working :program:`clang-query` matcher, the C++ API matchers
360 your intention-revealing names that you applied to nested matchers.
368 in your ``check`` method by eliminating complex hand-crafted AST traversal of the
370 of the AST directly in the matcher and refer to it by a bound name in the ``check``
376 Private custom matchers are a good example of auxiliary support code for your check
382 You can build the Clang-tidy unit tests by building the ``ClangTidyTests`` target.
383 Test targets in LLVM and Clang are excluded from the "build all" style action of
384 IDE-based CMake generators, so you need to explicitly build the target for the unit
387 Making your check robust
390 Once you've covered your check with the basic "happy path" scenarios, you'll want to
391 torture your check with as many edge cases as you can cover in order to ensure your
392 check is robust. Running your check on a large code base, such as Clang/LLVM, is a
396 the check is tested against, the higher confidence the community will have in the
397 check's efficacy and false positive rate.
399 Some suggestions to ensure your check is robust:
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
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-
413 positive rate, the less likely the check will be adopted in practice.
415 - There are two primary mechanisms for managing false positives: supporting a
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
422 - Consider adding check configuration options to allow the user to opt into
424 high-confidence cases.
426 Documenting your check
431 checks and a new file for the check documentation itself. It is recommended that you
432 have a concise summation of what your check does in a single sentence that is repeated
434 for your check class and as the first sentence of the check documentation. Avoid the
435 phrase "this check" in your check summation and check documentation.
437 If your check relates to a published coding guideline (C++ Core Guidelines, MISRA, etc.)
439 check documentation.
441 Provide enough examples of the diagnostics and fix-its provided by the check so that a
442 user can easily understand what will happen to their code when the check is run.
443 If there are exceptions or limitations to your check, document them thoroughly. This
444 will help users understand the scope of the diagnostics and fix-its provided by the check.
446 Building the target ``docs-clang-tools-html`` will run the Sphinx documentation generator
447 and create documentation HTML files in the tools/clang/tools/extra/docs/html directory in
448 your build tree. Make sure that your check is correctly shown in the release notes and the
449 list of checks. Make sure that the formatting and structure of your check's documentation
453 Registering your Check
454 ----------------------
456 (The ``add_new_check.py`` script takes care of registering the check in an existing
459 The check should be registered in the corresponding module with a distinct name:
461 .. code-block:: c++
467 "my-explicit-constructor");
474 .. code-block:: c++
476 static ClangTidyModuleRegistry::Add<MyModule> X("my-module",
480 When using LLVM build system, we need to use the following hack to ensure the
481 module is linked into the :program:`clang-tidy` binary:
485 .. code-block:: c++
491 And this to the main translation unit of the :program:`clang-tidy` binary (or
492 the binary you link the ``clang-tidy`` library in)
493 ``clang-tidy/ClangTidyForceLinker.h``:
495 .. code-block:: c++
503 ------------------
505 If a check needs configuration options, it can access check-specific options
506 using the ``Options.get<Type>("SomeOption", DefaultValue)`` call in the check
507 constructor. In this case the check should also override the
509 check discoverable. This method lets :program:`clang-tidy` know which options
510 the check implements and what the current values are (e.g. for the
511 ``-dump-config`` command line option).
513 .. code-block:: c++
522 SomeOption1(Options.get("SomeOption1", -1U)),
531 Assuming the check is registered with the name "my-check", the option can then
532 be set in a ``.clang-tidy`` file in the following way:
534 .. code-block:: yaml
537 my-check.SomeOption1: 123
538 my-check.SomeOption2: 'some other value'
540 If you need to specify check options on a command line, you can use the inline
543 .. code-block:: console
545 $ clang-tidy -config="{CheckOptions: {a: b, x: y}}" ...
549 --------------
551 To run tests for :program:`clang-tidy`, build the ``check-clang-tools`` target.
552 For instance, if you configured your CMake build with the ninja project generator,
555 .. code-block:: console
557 $ ninja check-clang-tools
559 :program:`clang-tidy` checks can be tested using either unit tests or
566 diagnostic messages and fix-its. It filters out ``CHECK`` lines from the test
567 file, runs :program:`clang-tidy` and verifies messages and fixes with two
569 prefix set to ``CHECK-MESSAGES``, validating the diagnostic messages,
570 and once with the directive prefix set to ``CHECK-FIXES``, running
571 against the fixed code (i.e., the code after generated fix-its are
572 applied). In particular, ``CHECK-FIXES:`` can be used to check
573 that code was not modified by fix-its, by checking that it is present
575 is available (e.g., ``CHECK-MESSAGES-SAME:``, ``CHECK-MESSAGES-NOT:``), though
576 typically the basic ``CHECK`` forms (``CHECK-MESSAGES`` and ``CHECK-FIXES``)
577 are sufficient for clang-tidy tests. Note that the `FileCheck`_
578 documentation mostly assumes the default prefix (``CHECK``), and hence
579 describes the directive as ``CHECK:``, ``CHECK-SAME:``, ``CHECK-NOT:``, etc.
580 Replace ``CHECK`` by either ``CHECK-FIXES`` or ``CHECK-MESSAGES`` for
581 clang-tidy tests.
583 An additional check enabled by ``check_clang_tidy.py`` ensures that
584 if `CHECK-MESSAGES:` is used in a file then every warning or error
585 must have an associated CHECK in that file. Or, you can use ``CHECK-NOTES:``
589 appropriate ``RUN`` line in the ``test/clang-tidy`` directory. Use
590 ``CHECK-MESSAGES:`` and ``CHECK-FIXES:`` lines to write checks against
594 to incorrect parts of the input. Use ``[[@LINE+X]]``/``[[@LINE-X]]``
598 source code is at `test/clang-tidy/checkers/google/readability-casting.cpp`_):
600 .. code-block:: c++
602 // RUN: %check_clang_tidy %s google-readability-casting %t
606 // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: redundant cast to the same type [google-readability-casting]
607 // CHECK-FIXES: int b = a;
610 To 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,...``.
613 With ``-check-suffix[es]=SUFFIX-NAME`` you need to replace your ``CHECK-*``
614 directives with ``CHECK-MESSAGES-SUFFIX-NAME`` and ``CHECK-FIXES-SUFFIX-NAME``.
618 .. code-block:: c++
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
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;$
632 your check work perfectly in all cases, especially if it issues fix-it hints. The
638 being inspected by the check multiple times (possibly, with different
640 issued by the check multiple times; :program:`clang-tidy` will deduplicate
647 If you need multiple files to exercise all the aspects of your check, it is
648 recommended you place them in a subdirectory named for the check under the ``Inputs``
649 directory for the module containing your check. This keeps the test directory from
652 If you need to validate how your check interacts with system header files, a set
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
661 Out-of-tree check plugins
662 -------------------------
665 Developing an out-of-tree check as a plugin largely follows the steps
668 the clang-tidy build system. Build and link this shared library against
672 The plugin can be loaded by passing `-load` to `clang-tidy` in addition to the
675 .. code-block:: console
677 $ clang-tidy --checks=-*,my-explicit-constructor -list-checks -load myplugin.so
680 compiled against the version of clang-tidy that will be loading the plugin.
682 The plugins can use threads, TLS, or any other facilities available to in-tree
685 Note that testing out-of-tree checks might involve getting ``llvm-lit`` from an LLVM
689 Alternatively, get `lit`_ following the `test-suite guide`_ and get the `FileCheck`_ binary,
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
698 Running clang-tidy on LLVM
699 --------------------------
701 To test a check it's best to try it out on a larger code base. LLVM and Clang
703 convenient way to run :program:`clang-tidy` is with a compile command database;
706 place and a working version of :program:`clang-tidy` is in ``PATH`` the entire
707 code base can be analyzed with ``clang-tidy/tool/run-clang-tidy.py``. The script
708 executes :program:`clang-tidy` with the default set of checks on every
712 .. _How To Setup Clang Tooling For LLVM: https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
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.
722 ``run-clang-tidy.py clang-tidy/.*Check\.cpp`` will only analyze `clang-tidy`
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.
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.
733 -------------------
735 :program:`clang-tidy` can collect per-check profiling info, and output it
738 To enable profiling info collection, use the ``-enable-check-profile`` argument.
741 .. code-block:: console
743 $ clang-tidy -enable-check-profile -checks=-*,readability-function-size source.cpp
744 ===-------------------------------------------------------------------------===
745 clang-tidy checks profiling
746 ===-------------------------------------------------------------------------===
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
755 .. code-block:: console
757 $ clang-tidy -enable-check-profile -store-check-profile=. -checks=-*,readability-function-size source.cpp
760 20180516161318717446360-source.cpp.json
761 $ cat 20180516161318717446360-source.cpp.json
764 "timestamp": "2018-05-16 16:13:18.717446360",
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
774 * ``-store-check-profile=<prefix>``
777 is passed, these per-TU profiles are instead stored as JSON.
779 directory from where you have run :program:`clang-tidy`. All ``.`` and ``..``
787 * If you specify ``-store-check-profile=/tmp``, then the profile will be saved
788 to ``/tmp/<ISO8601-like timestamp>-example.cpp.json``
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`