brintos

brintos / llvm-project-archived public Read only

0
0
Text · 29.1 KiB · 6ff82bf Raw
577 lines · plain
1==========2Clang-Tidy3==========4 5.. contents::6 7See also:8 9.. toctree::10   :maxdepth: 111 12   List of Clang-Tidy Checks <checks/list>13   Query Based Custom Clang-Tidy Checks <QueryBasedCustomChecks>14   Clang-tidy IDE/Editor Integrations <Integrations>15   Getting Involved <Contributing>16   External Clang-Tidy Examples <ExternalClang-TidyExamples>17 18:program:`clang-tidy` is a clang-based C++ "linter" tool. Its purpose is to19provide an extensible framework for diagnosing and fixing typical programming20errors, like style violations, interface misuse, or bugs that can be deduced via21static analysis. :program:`clang-tidy` is modular and provides a convenient22interface for writing new checks.23 24 25Using Clang-Tidy26================27 28:program:`clang-tidy` is a `LibTooling`_-based tool, and it's easier to work29with if you set up a compile command database for your project (for an example30of how to do this, see `How To Setup Tooling For LLVM`_). You can also specify31compilation options on the command line after ``--``:32 33.. code-block:: console34 35  $ clang-tidy test.cpp -- -Imy_project/include -DMY_DEFINES ...36 37If there are too many options or source files to specify on the command line,38you can store them in a parameter file, and use :program:`clang-tidy` with that39parameters file:40 41.. code-block:: console42 43  $ clang-tidy @parameters_file44 45:program:`clang-tidy` has its own checks and can also run Clang Static Analyzer46checks. Each check has a name and the checks to run can be chosen using the47``-checks=`` option, which specifies a comma-separated list of positive and48negative (prefixed with ``-``) globs. Positive globs add subsets of checks, and49negative globs remove them. For example,50 51.. code-block:: console52 53  $ clang-tidy test.cpp -checks=-*,clang-analyzer-*,-clang-analyzer-cplusplus*54 55will disable all default checks (``-*``) and enable all ``clang-analyzer-*``56checks except for ``clang-analyzer-cplusplus*`` ones.57 58The ``-list-checks`` option lists all the enabled checks. When used without59``-checks=``, it shows checks enabled by default. Use ``-checks=*`` to see all60available checks or with any other value of ``-checks=`` to see which checks are61enabled by this value.62 63.. _checks-groups-table:64 65There are currently the following groups of checks:66 67====================== =========================================================68Name prefix            Description69====================== =========================================================70``abseil-``            Checks related to Abseil library.71``altera-``            Checks related to OpenCL programming for FPGAs.72``android-``           Checks related to Android.73``boost-``             Checks related to Boost library.74``bugprone-``          Checks that target bug-prone code constructs.75``cert-``              Checks related to CERT Secure Coding Guidelines.76``clang-analyzer-``    Clang Static Analyzer checks.77``concurrency-``       Checks related to concurrent programming (including78                       threads, fibers, coroutines, etc.).79``cppcoreguidelines-`` Checks related to C++ Core Guidelines.80``darwin-``            Checks related to Darwin coding conventions.81``fuchsia-``           Checks related to Fuchsia coding conventions.82``google-``            Checks related to Google coding conventions.83``hicpp-``             Checks related to High Integrity C++ Coding Standard.84``linuxkernel-``       Checks related to the Linux Kernel coding conventions.85``llvm-``              Checks related to the LLVM coding conventions.86``llvmlibc-``          Checks related to the LLVM-libc coding standards.87``misc-``              Checks that we didn't have a better category for.88``modernize-``         Checks that advocate usage of modern (currently "modern"89                       means "C++11") language constructs.90``mpi-``               Checks related to MPI (Message Passing Interface).91``objc-``              Checks related to Objective-C coding conventions.92``openmp-``            Checks related to OpenMP API.93``performance-``       Checks that target performance-related issues.94``portability-``       Checks that target portability-related issues that don't95                       relate to any particular coding style.96``readability-``       Checks that target readability-related issues that don't97                       relate to any particular coding style.98``zircon-``            Checks related to Zircon kernel coding conventions.99====================== =========================================================100 101Clang diagnostics are treated in a similar way as check diagnostics. Clang102diagnostics are displayed by :program:`clang-tidy` and can be filtered out using103the ``-checks=`` option. However, the ``-checks=`` option does not affect104compilation arguments, so it cannot turn on Clang warnings which are not105already turned on in the build configuration. The ``-warnings-as-errors=``106option upgrades any warnings emitted under the ``-checks=`` flag to errors (but107it does not enable any checks itself).108 109Clang diagnostics have check names starting with ``clang-diagnostic-``.110Diagnostics which have a corresponding warning option, are named111``clang-diagnostic-<warning-option>``, e.g. Clang warning controlled by112``-Wliteral-conversion`` will be reported with check name113``clang-diagnostic-literal-conversion``.114 115Clang compiler errors (such as syntax errors, semantic errors, or other failures116that prevent Clang from compiling the code) are reported with the check name117``clang-diagnostic-error``. These represent fundamental compilation failures that118must be fixed before :program:`clang-tidy` can perform its analysis. Unlike other119diagnostics, ``clang-diagnostic-error`` cannot be disabled, as :program:`clang-tidy`120requires valid code to function.121 122The ``-fix`` flag instructs :program:`clang-tidy` to fix found errors if123supported by corresponding checks.124 125An overview of all the command-line options:126 127.. code-block:: console128 129  $ clang-tidy --help130  USAGE: clang-tidy [options] <source0> [... <sourceN>]131 132  OPTIONS:133 134  Generic Options:135 136    --help                           - Display available options (--help-hidden for more)137    --help-list                      - Display list of available options (--help-list-hidden for more)138    --version                        - Display the version of this program139 140  clang-tidy options:141 142    --checks=<string>                - Comma-separated list of globs with optional '-'143                                       prefix. Globs are processed in order of144                                       appearance in the list. Globs without '-'145                                       prefix add checks with matching names to the146                                       set, globs with the '-' prefix remove checks147                                       with matching names from the set of enabled148                                       checks. This option's value is appended to the149                                       value of the 'Checks' option in .clang-tidy150                                       file, if any.151    --config=<string>                - Specifies a configuration in YAML/JSON format:152                                         -config="{Checks: '*',153                                                   CheckOptions: {x: y}}"154                                       When the value is empty, clang-tidy will155                                       attempt to find a file named .clang-tidy for156                                       each source file in its parent directories.157    --config-file=<string>           - Specify the path of .clang-tidy or custom config file:158                                        e.g. --config-file=/some/path/myTidyConfigFile159                                       This option internally works exactly the same way as160                                        --config option after reading specified config file.161                                       Use either --config-file or --config, not both.162    --dump-config                    - Dumps configuration in the YAML format to163                                       stdout. This option can be used along with a164                                       file name (and '--' if the file is outside of a165                                       project with configured compilation database).166                                       The configuration used for this file will be167                                       printed.168                                       Use along with -checks=* to include169                                       configuration of all checks.170    --enable-check-profile           - Enable per-check timing profiles, and print a171                                       report to stderr.172    --enable-module-headers-parsing  - Enables preprocessor-level module header parsing173                                       for C++20 and above, empowering specific checks174                                       to detect macro definitions within modules. This175                                       feature may cause performance and parsing issues176                                       and is therefore considered experimental.177    --exclude-header-filter=<string> - Regular expression matching the names of the178                                       headers to exclude diagnostics from. Diagnostics179                                       from the main file of each translation unit are180                                       always displayed.181                                       Must be used together with --header-filter.182                                       Can be used together with -line-filter.183                                       This option overrides the 'ExcludeHeaderFilterRegex'184                                       option in .clang-tidy file, if any.185    --explain-config                 - For each enabled check explains, where it is186                                       enabled, i.e. in clang-tidy binary, command187                                       line or a specific configuration file.188    --export-fixes=<filename>        - YAML file to store suggested fixes in. The189                                       stored fixes can be applied to the input source190                                       code with clang-apply-replacements.191    --extra-arg=<string>             - Additional argument to append to the compiler command line192    --extra-arg-before=<string>      - Additional argument to prepend to the compiler command line193    --fix                            - Apply suggested fixes. Without -fix-errors194                                       clang-tidy will bail out if any compilation195                                       errors were found.196    --fix-errors                     - Apply suggested fixes even if compilation197                                       errors were found. If compiler errors have198                                       attached fix-its, clang-tidy will apply them as199                                       well.200    --fix-notes                      - If a warning has no fix, but a single fix can201                                       be found through an associated diagnostic note,202                                       apply the fix.203                                       Specifying this flag will implicitly enable the204                                       '--fix' flag.205    --format-style=<string>          - Style for formatting code around applied fixes:206                                         - 'none' (default) turns off formatting207                                         - 'file' (literally 'file', not a placeholder)208                                           uses .clang-format file in the closest parent209                                           directory210                                         - '{ <json> }' specifies options inline, e.g.211                                           -format-style='{BasedOnStyle: llvm, IndentWidth: 8}'212                                         - 'llvm', 'google', 'webkit', 'mozilla'213                                       See clang-format documentation for the up-to-date214                                       information about formatting styles and options.215                                       This option overrides the 'FormatStyle` option in216                                       .clang-tidy file, if any.217    --header-filter=<string>         - Regular expression matching the names of the218                                       headers to output diagnostics from. The default219                                       value is '.*', i.e. diagnostics from all non-system220                                       headers are displayed by default. Diagnostics221                                       from the main file of each translation unit are222                                       always displayed.223                                       Can be used together with -line-filter.224                                       This option overrides the 'HeaderFilterRegex'225                                       option in .clang-tidy file, if any.226    --line-filter=<string>           - List of files and line ranges to output diagnostics from.227                                       The range is inclusive on both ends. Can be used together228                                       with -header-filter. The format of the list is a JSON229                                       array of objects. For example:230 231                                         [232                                           {"name":"file1.cpp","lines":[[1,3],[5,7]]},233                                           {"name":"file2.h"}234                                         ]235 236                                       This will output diagnostics from 'file1.cpp' only for237                                       the line ranges [1,3] and [5,7], as well as all from the238                                       entire 'file2.h'.239    --list-checks                    - List all enabled checks and exit. Use with240                                       -checks=* to list all available checks.241    --load=<pluginfilename>          - Load the specified plugin242    -p <string>                      - Build path243    --quiet                          - Run clang-tidy in quiet mode. This suppresses244                                       printing statistics about ignored warnings and245                                       warnings treated as errors if the respective246                                       options are specified.247    --store-check-profile=<prefix>   - By default reports are printed in tabulated248                                       format to stderr. When this option is passed,249                                       these per-TU profiles are instead stored as JSON.250    --system-headers                 - Display the errors from system headers.251                                       This option overrides the 'SystemHeaders' option252                                       in .clang-tidy file, if any.253    --use-color                      - Use colors in diagnostics. If not set, colors254                                       will be used if the terminal connected to255                                       standard output supports colors.256                                       This option overrides the 'UseColor' option in257                                       .clang-tidy file, if any.258    --verify-config                  - Check the config files to ensure each check and259                                       option is recognized.260    --vfsoverlay=<filename>          - Overlay the virtual filesystem described by file261                                       over the real file system.262    --warnings-as-errors=<string>    - Upgrades warnings to errors. Same format as263                                       '-checks'.264                                       This option's value is appended to the value of265                                       the 'WarningsAsErrors' option in .clang-tidy266                                       file, if any.267    --allow-no-checks                - Allow empty enabled checks. This suppresses268                                       the "no checks enabled" error when disabling269                                       all of the checks.270 271  -p <build-path> is used to read a compile command database.272 273    For example, it can be a CMake build directory in which a file named274    compile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON275    CMake option to get this output). When no build path is specified,276    a search for compile_commands.json will be attempted through all277    parent paths of the first input file . See:278    https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an279    example of setting up Clang Tooling on a source tree.280 281  <source0> ... specify the paths of source files. These paths are282    looked up in the compile command database. If the path of a file is283    absolute, it needs to point into CMake's source tree. If the path is284    relative, the current working directory needs to be in the CMake285    source tree and the file must be in a subdirectory of the current286    working directory. "./" prefixes in the relative files will be287    automatically removed, but the rest of a relative path must be a288    suffix of a path in the compile command database.289 290  Parameters files:291    A large number of options or source files can be passed as parameter files292    by use '@parameter-file' in the command line.293 294  Configuration files:295    clang-tidy attempts to read configuration for each source file from a296    .clang-tidy file located in the closest parent directory of the source297    file. The .clang-tidy file is specified in YAML format. If any configuration298    options have a corresponding command-line option, command-line option takes299    precedence.300 301    The following configuration options may be used in a .clang-tidy file:302 303    CheckOptions                 - List of key-value pairs defining check-specific304                                   options. Example:305                                     CheckOptions:306                                       some-check.SomeOption: 'some value'307    Checks                       - Same as '--checks'. Additionally, the list of308                                   globs can be specified as a list instead of a309                                   string.310    CustomChecks                 - List of user defined checks based on311                                   Clang-Query syntax.312    ExcludeHeaderFilterRegex     - Same as '--exclude-header-filter'.313    ExtraArgs                    - Same as '--extra-arg'.314    ExtraArgsBefore              - Same as '--extra-arg-before'.315    FormatStyle                  - Same as '--format-style'.316    HeaderFileExtensions         - File extensions to consider to determine if a317                                   given diagnostic is located in a header file.318    HeaderFilterRegex            - Same as '--header-filter'.319    ImplementationFileExtensions - File extensions to consider to determine if a320                                   given diagnostic is located in an321                                   implementation file.322    InheritParentConfig          - If this option is true in a config file, the323                                   configuration file in the parent directory324                                   (if any exists) will be taken and the current325                                   config file will be applied on top of the326                                   parent one.327    SystemHeaders                - Same as '--system-headers'.328    UseColor                     - Same as '--use-color'.329    User                         - Specifies the name or e-mail of the user330                                   running clang-tidy. This option is used, for331                                   example, to place the correct user name in332                                   TODO() comments in the relevant check.333    WarningsAsErrors             - Same as '--warnings-as-errors'.334 335    The effective configuration can be inspected using --dump-config:336 337      $ clang-tidy --dump-config338      ---339      Checks:              '-*,some-check'340      WarningsAsErrors:    ''341      HeaderFileExtensions:         ['', 'h','hh','hpp','hxx']342      ImplementationFileExtensions: ['c','cc','cpp','cxx']343      HeaderFilterRegex:   '.*'344      FormatStyle:         none345      InheritParentConfig: true346      User:                user347      CheckOptions:348        some-check.SomeOption: 'some value'349      ...350 351Clang-Tidy Automation352=====================353 354:program:`clang-tidy` can analyze multiple source files by specifying them on355the command line. For larger projects, automation scripts provide additional356functionality like parallel execution and integration with version control357systems.358 359Running Clang-Tidy in Parallel360-------------------------------361 362:program:`clang-tidy` can process multiple files sequentially, but for projects363with many source files, the :program:`run-clang-tidy.py` script provides364parallel execution to significantly reduce analysis time. This script is365included with clang-tidy and runs :program:`clang-tidy` over all files in a366compilation database or a specified path concurrently.367 368The script requires a compilation database (``compile_commands.json``) which369can be generated by build systems like CMake (using370``-DCMAKE_EXPORT_COMPILE_COMMANDS=ON``) or by tools like `Bear`_.371 372The script supports most of the same options as :program:`clang-tidy` itself,373including ``-checks=``, ``-fix``, ``-header-filter=``, and configuration374options. Run ``run-clang-tidy.py --help`` for a complete list of available375options.376 377Example invocations:378 379.. code-block:: console380 381  # Run clang-tidy on all files in the compilation database in parallel382  $ run-clang-tidy.py -p=build/383 384  # Run with specific checks and apply fixes385  $ run-clang-tidy.py -p=build/ -fix -checks=-*,readability-*386 387  # Run on specific files/directories with header filtering388  $ run-clang-tidy.py -p=build/ -header-filter=src/ src/389 390  # Run with parallel execution (uses all CPU cores by default)391  $ run-clang-tidy.py -p=build/ -j 4392 393Running Clang-Tidy on Diff394---------------------------395 396The :program:`clang-tidy-diff.py` script allows you to run397:program:`clang-tidy` on the lines that have been modified in your working398directory or in a specific diff. Importantly, :program:`clang-tidy-diff.py` only reports399diagnostics for changed lines; :program:`clang-tidy` still analyzes the entire400file and filters out unchanged lines after analysis, so this does not improve401performance. This is particularly useful for code reviews and continuous402integration, as it focuses analysis on the changed code rather than the entire403codebase.404 405The script can work with various diff sources:406 407* Git working directory changes408* Output from ``git diff``409* Output from ``svn diff``410* Patch files411 412Example invocations:413 414.. code-block:: console415 416  # Run clang-tidy on all changes in the working directory417  $ git diff -U0 --no-color HEAD^ | clang-tidy-diff.py -p1418 419  # Run with specific checks and apply fixes420  $ git diff -U0 --no-color HEAD^ | clang-tidy-diff.py -p1 -fix \421    -checks=-*,readability-*422 423  # Run on staged changes424  $ git diff -U0 --no-color --cached | clang-tidy-diff.py -p1425 426  # Run on changes between two commits427  $ git diff -U0 --no-color HEAD~2 HEAD | clang-tidy-diff.py -p1428 429  # Run on a patch file430  $ clang-tidy-diff.py -p1 < changes.patch431 432The ``-p1`` option tells the script to strip one level of path prefix from433the diff, which is typically needed for Git diffs. The script supports most of434the same options as :program:`clang-tidy` itself, including ``-checks=``,435``-fix``, ``-header-filter=``, and configuration options.436 437While :program:`clang-tidy-diff.py` is useful for focusing on recent changes,438relying solely on it may lead to incomplete analysis. Since the script only439reports warnings from the modified lines, it may miss issues that are caused440by the changes but manifest elsewhere in the code. For example, changes that441only add lines to a function may cause it to violate size limits (e.g.,442`readability-function-size <checks/readability/function-size.html>`_), but the443diagnostic will be reported at the function declaration, which may not be in444the diff and thus filtered out. Modifications to header files may also affect445many implementation files, but only warnings in the modified header lines will446be reported.447 448For comprehensive analysis, especially before merging significant changes,449consider running :program:`clang-tidy` on the entire affected files or the450whole project using :program:`run-clang-tidy.py`.451 452.. _clang-tidy-nolint:453 454Suppressing Undesired Diagnostics455=================================456 457:program:`clang-tidy` diagnostics are intended to call out code that does not458adhere to a coding standard, or is otherwise problematic in some way. However,459if the code is known to be correct, it may be useful to silence the warning.460Some clang-tidy checks provide a check-specific way to silence the diagnostics,461e.g. `bugprone-use-after-move <checks/bugprone/use-after-move.html>`_ can be462silenced by re-initializing the variable after it has been moved out,463`bugprone-string-integer-assignment464<checks/bugprone/string-integer-assignment.html>`_ can be suppressed by465explicitly casting the integer to ``char``,466`readability-implicit-bool-conversion467<checks/readability/implicit-bool-conversion.html>`_ can also be suppressed by468using explicit casts, etc.469 470If a specific suppression mechanism is not available for a certain warning, or471its use is not desired for some reason, :program:`clang-tidy` has a generic472mechanism to suppress diagnostics using ``NOLINT``, ``NOLINTNEXTLINE``, and473``NOLINTBEGIN`` ... ``NOLINTEND`` comments.474 475The ``NOLINT`` comment instructs :program:`clang-tidy` to ignore warnings on the476*same line* (it doesn't apply to a function, a block of code or any other477language construct; it applies to the line of code it is on). If introducing the478comment on the same line would change the formatting in an undesired way, the479``NOLINTNEXTLINE`` comment allows suppressing clang-tidy warnings on the *next480line*. The ``NOLINTBEGIN`` and ``NOLINTEND`` comments allow suppressing481clang-tidy warnings on *multiple lines* (affecting all lines between the two482comments).483 484All comments can be followed by an optional list of check names in parentheses485(see below for the formal syntax). The list of check names supports globbing,486with the same format and semantics as for enabling checks. Note: negative globs487are ignored here, as they would effectively re-activate the warning.488 489For example:490 491.. code-block:: c++492 493  class Foo {494    // Suppress all the diagnostics for the line495    Foo(int param); // NOLINT496 497    // Consider explaining the motivation to suppress the warning498    Foo(char param); // NOLINT: Allow implicit conversion from `char`, because <some valid reason>499 500    // Silence only the specified checks for the line501    Foo(double param); // NOLINT(google-explicit-constructor, google-runtime-int)502 503    // Silence all checks from the `google` module504    Foo(bool param); // NOLINT(google*)505 506    // Silence all checks ending with `-avoid-c-arrays`507    int array[10]; // NOLINT(*-avoid-c-arrays)508 509    // Silence only the specified diagnostics for the next line510    // NOLINTNEXTLINE(google-explicit-constructor, google-runtime-int)511    Foo(bool param);512 513    // Silence all checks from the `google` module for the next line514    // NOLINTNEXTLINE(google*)515    Foo(bool param);516 517    // Silence all checks ending with `-avoid-c-arrays` for the next line518    // NOLINTNEXTLINE(*-avoid-c-arrays)519    int array[10];520 521    // Silence only the specified checks for all lines between the BEGIN and END522    // NOLINTBEGIN(google-explicit-constructor, google-runtime-int)523    Foo(short param);524    Foo(long param);525    // NOLINTEND(google-explicit-constructor, google-runtime-int)526 527    // Silence all checks from the `google` module for all lines between the BEGIN and END528    // NOLINTBEGIN(google*)529    Foo(bool param);530    // NOLINTEND(google*)531 532    // Silence all checks ending with `-avoid-c-arrays` for all lines between the BEGIN and END533    // NOLINTBEGIN(*-avoid-c-arrays)534    int array[10];535    // NOLINTEND(*-avoid-c-arrays)536  };537 538The formal syntax of ``NOLINT``, ``NOLINTNEXTLINE``, and ``NOLINTBEGIN`` ...539``NOLINTEND`` is the following:540 541.. parsed-literal::542 543  lint-comment:544    lint-command545    lint-command lint-args546 547  lint-args:548    **(** check-name-list **)**549 550  check-name-list:551    *check-name*552    check-name-list **,** *check-name*553 554  lint-command:555    **NOLINT**556    **NOLINTNEXTLINE**557    **NOLINTBEGIN**558    **NOLINTEND**559 560Note that whitespaces between561``NOLINT``/``NOLINTNEXTLINE``/``NOLINTBEGIN``/``NOLINTEND`` and the opening562parenthesis are not allowed (in this case the comment will be treated just as563``NOLINT``/``NOLINTNEXTLINE``/``NOLINTBEGIN``/``NOLINTEND``), whereas in the564check names list (inside the parentheses), whitespaces can be used and will be565ignored.566 567All ``NOLINTBEGIN`` comments must be paired by an equal number of ``NOLINTEND``568comments. Moreover, a pair of comments must have matching arguments -- for569example, ``NOLINTBEGIN(check-name)`` can be paired with570``NOLINTEND(check-name)`` but not with ``NOLINTEND`` `(zero arguments)`.571:program:`clang-tidy` will generate a ``clang-tidy-nolint`` error diagnostic if572any ``NOLINTBEGIN``/``NOLINTEND`` comment violates these requirements.573 574.. _Bear: https://github.com/rizsotto/Bear575.. _LibTooling: https://clang.llvm.org/docs/LibTooling.html576.. _How To Setup Tooling For LLVM: https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html577