https://github.com/zeyi2 updated https://github.com/llvm/llvm-project/pull/168722
>From 4908ebaa5652957761db6116a3e4c823877fd9e3 Mon Sep 17 00:00:00 2001 From: mtx <[email protected]> Date: Wed, 19 Nov 2025 23:19:32 +0800 Subject: [PATCH 1/2] [clang-tidy][NFC] Fix formatting issue in `unsafe-functions.rst` --- .../checks/bugprone/unsafe-functions.rst | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unsafe-functions.rst b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unsafe-functions.rst index cb7ea415c54b2..e907326f8978a 100644 --- a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unsafe-functions.rst +++ b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unsafe-functions.rst @@ -96,21 +96,22 @@ to be checked. The format is the following, without newlines: The functions are matched using POSIX extended regular expressions. *(Note: The regular expressions do not support negative* ``(?!)`` *matches.)* -The ``reason`` is optional and is used to provide additional information about the -reasoning behind the replacement. The default reason is ``is marked as unsafe``. +The ``reason`` is optional and is used to provide additional information about +the reasoning behind the replacement. The default reason is +``is marked as unsafe``. If ``replacement`` is empty, the default text ``it should not be used`` will be shown instead of the suggestion for a replacement. -If the ``reason`` starts with the character ``>``, the reason becomes fully custom. -The default suffix is disabled even if a ``replacement`` is present, and only the -reason message is shown after the matched function, to allow better control over -the suggestions. (The starting ``>`` and whitespace directly after it are -trimmed from the message.) +If the ``reason`` starts with the character ``>``, the reason becomes fully +custom. The default suffix is disabled even if a ``replacement`` is present, +and only the reason message is shown after the matched function, to allow +better control over the suggestions. (The starting ``>`` and whitespace +directly after it are trimmed from the message.) -As an example, the following configuration matches only the function ``original`` -in the default namespace. A similar diagnostic can also be printed using a fully -custom reason. +As an example, the following configuration matches only the function +``original`` in the default namespace. A similar diagnostic can also be printed +using a fully custom reason. .. code:: c @@ -123,10 +124,10 @@ custom reason. ::std::original(); // no-warning original_function(); // no-warning -If the regular expression contains the character ``:``, it is matched against the -qualified name (i.e. ``std::original``), otherwise the regex is matched against -the unqualified name (``original``). If the regular expression starts with ``::`` -(or ``^::``), it is matched against the fully qualified name +If the regular expression contains the character ``:``, it is matched against +the qualified name (i.e. ``std::original``), otherwise the regex is matched +against the unqualified name (``original``). If the regular expression starts +with ``::`` (or ``^::``), it is matched against the fully qualified name (``::std::original``). One of the use cases for fully custom messages is suggesting compiler options >From 41aeccfe2c3c32fc26a8788a4c2a3f6a9d6d1ecf Mon Sep 17 00:00:00 2001 From: mtx <[email protected]> Date: Sun, 14 Dec 2025 17:28:32 +0800 Subject: [PATCH 2/2] Fix document formatting --- .../docs/clang-tidy/Contributing.rst | 416 +++++++++--------- .../clang-tidy/ExternalClang-TidyExamples.rst | 25 +- .../docs/clang-tidy/Integrations.rst | 7 +- .../clang-tidy/QueryBasedCustomChecks.rst | 3 +- .../checks/fuchsia/multiple-inheritance.rst | 2 +- .../checks/google/readability-casting.rst | 4 +- clang-tools-extra/docs/clang-tidy/index.rst | 60 +-- 7 files changed, 271 insertions(+), 246 deletions(-) diff --git a/clang-tools-extra/docs/clang-tidy/Contributing.rst b/clang-tools-extra/docs/clang-tidy/Contributing.rst index 4ede4ea36c13d..4db4ba94eee48 100644 --- a/clang-tools-extra/docs/clang-tidy/Contributing.rst +++ b/clang-tools-extra/docs/clang-tidy/Contributing.rst @@ -8,10 +8,10 @@ checks, but its power is in the ability to easily write custom checks. Checks are organized in modules, which can be linked into :program:`clang-tidy` with minimal or no code changes in :program:`clang-tidy`. -Checks can plug into the analysis on the preprocessor level using `PPCallbacks`_ -or on the AST level using `AST Matchers`_. When an error is found, checks can -report them in a way similar to how Clang diagnostics work. A fix-it hint can be -attached to a diagnostic message. +Checks can plug into the analysis on the preprocessor level using +`PPCallbacks`_ or on the AST level using `AST Matchers`_. When an error is +found, checks can report them in a way similar to how Clang diagnostics work. +A fix-it hint can be attached to a diagnostic message. The interface provided by :program:`clang-tidy` makes it easy to write useful and precise checks in just a few lines of code. If you have an idea for a good @@ -34,7 +34,7 @@ If CMake is configured with ``CLANG_TIDY_ENABLE_STATIC_ANALYZER=NO``, ``clang-analyzer-*`` checks or the ``mpi-*`` checks. If CMake is configured with ``CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS=NO``, -:program:`clang-tidy` will not be built with support for query based checks. +:program:`clang-tidy` will not be built with support for query based checks. .. _AST Matchers: https://clang.llvm.org/docs/LibASTMatchers.html @@ -78,10 +78,10 @@ let's start! When you `configure the CMake build <https://llvm.org/docs/GettingStarted.html#local-llvm-configuration>`_, make sure that you enable the ``clang`` and ``clang-tools-extra`` projects to build :program:`clang-tidy`. -Because your new check will have associated documentation, you will also want to install -`Sphinx <https://www.sphinx-doc.org/en/master/>`_ and enable it in the CMake configuration. -To save build time of the core Clang libraries, you may want to only enable the ``X86`` -target in the CMake configuration. +Because your new check will have associated documentation, you will also want +to install `Sphinx <https://www.sphinx-doc.org/en/master/>`_ and enable it in +the CMake configuration. To save build time of the core Clang libraries, you +may want to only enable the ``X86`` target in the CMake configuration. The Directory Structure @@ -130,11 +130,11 @@ Writing a clang-tidy Check So you have an idea of a useful check for :program:`clang-tidy`. -First, if you're not familiar with LLVM development, read through the `Getting Started -with the LLVM System`_ document for instructions on setting up your workflow and -the `LLVM Coding Standards`_ document to familiarize yourself with the coding -style used in the project. For code reviews, we currently use `LLVM Github`_, -though historically we used Phabricator. +First, if you're not familiar with LLVM development, read through the `Getting +Started with the LLVM System`_ document for instructions on setting up your +workflow and the `LLVM Coding Standards`_ document to familiarize yourself +with the coding style used in the project. For code reviews, we currently +use `LLVM Github`_, though historically we used Phabricator. .. _Getting Started with the LLVM System: https://llvm.org/docs/GettingStarted.html .. _LLVM Coding Standards: https://llvm.org/docs/CodingStandards.html @@ -144,13 +144,14 @@ Next, you need to decide which module the check belongs to. Modules are located in subdirectories of `clang-tidy/ <https://github.com/llvm/llvm-project/tree/main/clang-tools-extra/clang-tidy/>`_ and contain checks targeting a certain aspect of code quality (performance, -readability, etc.), a certain coding style or standard (Google, LLVM, CERT, etc.) -or a widely used API (e.g. MPI). Their names are the same as the user-facing -check group names described :ref:`above <checks-groups-table>`. +readability, etc.), a certain coding style or standard (Google, LLVM, CERT, +etc.) or a widely used API (e.g. MPI). Their names are the same as the +user-facing check group names described :ref:`above <checks-groups-table>`. After choosing the module and the name for the check, run the ``clang-tidy/add_new_check.py`` script to create the skeleton of the check and -plug it to :program:`clang-tidy`. It's the recommended way of adding new checks. +plug it to :program:`clang-tidy`. It's the recommended way of adding new +checks. By default, the new check will apply only to C++ code. If it should apply under different language options, use the ``--language`` script's parameter. @@ -203,10 +204,10 @@ In our case the check needs to operate on the AST level and it overrides the preprocessor level, we'd need instead to override the ``registerPPCallbacks`` method. -In the ``registerMatchers`` method, we create an AST Matcher (see `AST Matchers`_ -for more information) that will find the pattern in the AST that we want to -inspect. The results of the matching are passed to the ``check`` method, which -can further inspect them and report diagnostics. +In the ``registerMatchers`` method, we create an AST Matcher (see `AST +Matchers`_ for more information) that will find the pattern in the AST that we +want to inspect. The results of the matching are passed to the ``check`` method, +which can further inspect them and report diagnostics. .. code-block:: c++ @@ -231,17 +232,17 @@ can further inspect them and report diagnostics. and `clang-tidy/google/ExplicitConstructorCheck.cpp <https://reviews.llvm.org/diffusion/L/browse/clang-tools-extra/trunk/clang-tidy/google/ExplicitConstructorCheck.cpp>`_). -If you need to interact with macros or preprocessor directives, you will want to -override the method ``registerPPCallbacks``. The ``add_new_check.py`` script -does not generate an override for this method in the starting point for your -new check. +If you need to interact with macros or preprocessor directives, you will want +to override the method ``registerPPCallbacks``. The ``add_new_check.py`` +script does not generate an override for this method in the starting point for +your new check. Check development tips ---------------------- -Writing your first check can be a daunting task, particularly if you are unfamiliar -with the LLVM and Clang code bases. Here are some suggestions for orienting yourself -in the codebase and working on your check incrementally. +Writing your first check can be a daunting task, particularly if you are +unfamiliar with the LLVM and Clang code bases. Here are some suggestions for +orienting yourself in the codebase and working on your check incrementally. Guide to useful documentation ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -249,9 +250,9 @@ Guide to useful documentation Many of the support classes created for LLVM are used by Clang, such as `StringRef <https://llvm.org/docs/ProgrammersManual.html#the-stringref-class>`_ and `SmallVector <https://llvm.org/docs/ProgrammersManual.html#llvm-adt-smallvector-h>`_. -These and other commonly used classes are described in the `Important and useful LLVM APIs -<https://llvm.org/docs/ProgrammersManual.html#important-and-useful-llvm-apis>`_ and -`Picking the Right Data Structure for the Task +These and other commonly used classes are described in the `Important and +useful LLVM APIs <https://llvm.org/docs/ProgrammersManual.html#important-and-useful-llvm-apis>`_ +and `Picking the Right Data Structure for the Task <https://llvm.org/docs/ProgrammersManual.html#picking-the-right-data-structure-for-a-task>`_ sections of the `LLVM Programmer's Manual <https://llvm.org/docs/ProgrammersManual.html>`_. You don't need to memorize all the @@ -261,61 +262,66 @@ has everything if you need it. In the header `LLVM/ADT/STLExtras.h algorithms that operate on LLVM containers, such as `llvm::all_of <https://llvm.org/doxygen/STLExtras_8h.html#func-members>`_. -Clang is implemented on top of LLVM and introduces its own set of classes that you -will interact with while writing your check. When a check issues diagnostics and -fix-its, these are associated with locations in the source code. Source code locations, -source files, ranges of source locations and the `SourceManager -<https://clang.llvm.org/doxygen/classclang_1_1SourceManager.html>`_ class provide -the mechanisms for describing such locations. These and +Clang is implemented on top of LLVM and introduces its own set of classes that +you will interact with while writing your check. When a check issues +diagnostics and fix-its, these are associated with locations in the source +code. Source code locations, source files, ranges of source locations and the +`SourceManager <https://clang.llvm.org/doxygen/classclang_1_1SourceManager.html>`_ +class provide the mechanisms for describing such locations. These and other topics are described in the `"Clang" CFE Internals Manual -<https://clang.llvm.org/docs/InternalsManual.html>`_. Whereas the doxygen generated -documentation serves as a reference to the internals of Clang, this document serves -as a guide to other developers. Topics in that manual of interest to a check developer -are: +<https://clang.llvm.org/docs/InternalsManual.html>`_. Whereas the doxygen generated +documentation serves as a reference to the internals of Clang, this document +servesas a guide to other developers. Topics in that manual of interest to a +check developer are: - `The Clang "Basic" Library <https://clang.llvm.org/docs/InternalsManual.html#the-clang-basic-library>`_ for information about diagnostics, fix-it hints and source locations. - `The Lexer and Preprocessor Library <https://clang.llvm.org/docs/InternalsManual.html#the-lexer-and-preprocessor-library>`_ - for information about tokens, lexing (transforming characters into tokens) and the - preprocessor. + for information about tokens, lexing (transforming characters into tokens) + and the preprocessor. - `The AST Library <https://clang.llvm.org/docs/InternalsManual.html#the-ast-library>`_ - for information about how C++ source statements are represented as an abstract syntax - tree (AST). - -Most checks will interact with C++ source code via the AST. Some checks will interact -with the preprocessor. The input source file is lexed and preprocessed and then parsed -into the AST. Once the AST is fully constructed, the check is run by applying the check's -registered AST matchers against the AST and invoking the check with the set of matched -nodes from the AST. Monitoring the actions of the preprocessor is detached from the -AST construction, but a check can collect information during preprocessing for later -use by the check when nodes are matched by the AST. - -Every syntactic (and sometimes semantic) element of the C++ source code is represented by -different classes in the AST. You select the portions of the AST you're interested in -by composing AST matcher functions. You will want to study carefully the `AST Matcher -Reference <https://clang.llvm.org/docs/LibASTMatchersReference.html>`_ to understand -the relationship between the different matcher functions. + for information about how C++ source statements are represented as an + abstract syntax tree (AST). + +Most checks will interact with C++ source code via the AST. Some checks will +interact with the preprocessor. The input source file is lexed and preprocessed +and then parsed into the AST. Once the AST is fully constructed, the check is +run by applying the check's registered AST matchers against the AST and +invoking the check with the set of matched nodes from the AST. Monitoring the +actions of the preprocessor is detached from the AST construction, but a check +can collect information during preprocessing for later use by the check when +nodes are matched by the AST. + +Every syntactic (and sometimes semantic) element of the C++ source code is +represented by different classes in the AST. You select the portions of the +AST you're interested in by composing AST matcher functions. You will want +to study carefully the `AST Matcher Reference +<https://clang.llvm.org/docs/LibASTMatchersReference.html>`_ +to understand the relationship between the different matcher functions. Using the Transformer library ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -The Transformer library allows you to write a check that transforms source code by -expressing the transformation as a ``RewriteRule``. The Transformer library provides -functions for composing edits to source code to create rewrite rules. Unless you need -to perform low-level source location manipulation, you may want to consider writing your -check with the Transformer library. The `Clang Transformer Tutorial -<https://clang.llvm.org/docs/ClangTransformerTutorial.html>`_ describes the Transformer -library in detail. - -To use the Transformer library, make the following changes to the code generated by -the ``add_new_check.py`` script: - -- Include ``../utils/TransformerClangTidyCheck.h`` instead of ``../ClangTidyCheck.h`` -- Change the base class of your check from ``ClangTidyCheck`` to ``TransformerClangTidyCheck`` -- Delete the override of the ``registerMatchers`` and ``check`` methods in your check class. +The Transformer library allows you to write a check that transforms source code +by expressing the transformation as a ``RewriteRule``. The Transformer library +provides functions for composing edits to source code to create rewrite rules. +Unless you need to perform low-level source location manipulation, you may want +to consider writing your check with the Transformer library. The `Clang +Transformer Tutorial <https://clang.llvm.org/docs/ClangTransformerTutorial.html>`_ +describes the Transformer library in detail. + +To use the Transformer library, make the following changes to the code +generated by the ``add_new_check.py`` script: + +- Include ``../utils/TransformerClangTidyCheck.h`` instead of + ``../ClangTidyCheck.h`` +- Change the base class of your check from ``ClangTidyCheck`` to + ``TransformerClangTidyCheck`` +- Delete the override of the ``registerMatchers`` and ``check`` methods in + your check class. - Write a function that creates the ``RewriteRule`` for your check. - Call the function in your check's constructor to pass the rewrite rule to ``TransformerClangTidyCheck``'s constructor. @@ -323,9 +329,10 @@ the ``add_new_check.py`` script: Developing your check incrementally ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -The best way to develop your check is to start with simple test cases and increase -complexity incrementally. The test file created by the ``add_new_check.py`` script is -a starting point for your test cases. A rough outline of the process looks like this: +The best way to develop your check is to start with simple test cases and +increase complexity incrementally. The test file created by the +``add_new_check.py`` script is a starting point for your test cases. +A rough outline of the process looks like this: - Write a test case for your check. - Prototype matchers on the test file using :program:`clang-query`. @@ -337,66 +344,68 @@ a starting point for your test cases. A rough outline of the process looks like - Repeat the process until all aspects of your check are covered by tests. The quickest way to prototype your matcher is to use :program:`clang-query` to -interactively build up your matcher. For complicated matchers, build up a matching -expression incrementally and use :program:`clang-query`'s ``let`` command to save named -matching expressions to simplify your matcher. +interactively build up your matcher. For complicated matchers, build up a +matching expression incrementally and use :program:`clang-query`'s ``let`` +command to save named matching expressions to simplify your matcher. .. code-block:: console clang-query> let c1 cxxRecordDecl() clang-query> match c1 -Alternatively, pressing the tab key after a previous matcher's open parentheses -would also show which matchers can be chained with the previous matcher, -though some matchers that work may not be listed. Note that tab completion +Alternatively, pressing the tab key after a previous matcher's open parentheses +would also show which matchers can be chained with the previous matcher, +though some matchers that work may not be listed. Note that tab completion does not currently work on Windows. -Just like breaking up a huge function into smaller chunks with -intention-revealing names can help you understand a complex algorithm, breaking -up a matcher into smaller matchers with intention-revealing names can help -you understand a complicated matcher. +Just like breaking up a huge function into smaller chunks with +intention-revealing names can help you understand a complex algorithm, breaking +up a matcher into smaller matchers with intention-revealing names can help +you understand a complicated matcher. -Once you have a working :program:`clang-query` matcher, the C++ API matchers -will be the same or similar to your interactively constructed matcher (there -can be cases where they differ slightly). You can use local variables to preserve -your intention-revealing names that you applied to nested matchers. +Once you have a working :program:`clang-query` matcher, the C++ API matchers +will be the same or similar to your interactively constructed matcher (there +can be cases where they differ slightly). You can use local variables to +preserve your intention-revealing names that you applied to nested matchers. Creating private matchers ^^^^^^^^^^^^^^^^^^^^^^^^^ -Sometimes you want to match a specific aspect of the AST that isn't provided by the -existing AST matchers. You can create your own private matcher using the same -infrastructure as the public matchers. A private matcher can simplify the processing -in your ``check`` method by eliminating complex hand-crafted AST traversal of the -matched nodes. Using the private matcher allows you to select the desired portions -of the AST directly in the matcher and refer to it by a bound name in the ``check`` -method. +Sometimes you want to match a specific aspect of the AST that isn't provided +by the existing AST matchers. You can create your own private matcher using +the same infrastructure as the public matchers. A private matcher can +simplify the processing in your ``check`` method by eliminating complex +hand-crafted AST traversal of the matched nodes. Using the private matcher +allows you to select the desired portions of the AST directly in the matcher +and refer to it by a bound name in the ``check`` method. Unit testing helper code ^^^^^^^^^^^^^^^^^^^^^^^^ -Private custom matchers are a good example of auxiliary support code for your check -that can be tested with a unit test. It will be easier to test your matchers or -other support classes by writing a unit test than by writing a ``FileCheck`` integration -test. The ``ASTMatchersTests`` target contains unit tests for the public AST matcher -classes and is a good source of testing idioms for matchers. +Private custom matchers are a good example of auxiliary support code for your +check that can be tested with a unit test. It will be easier to test your +matchers or other support classes by writing a unit test than by writing a +``FileCheck`` integration test. The ``ASTMatchersTests`` target contains unit +tests for the public AST matcher classes and is a good source of testing +idioms for matchers. -You can build the Clang-tidy unit tests by building the ``ClangTidyTests`` target. -Test targets in LLVM and Clang are excluded from the "build all" style action of -IDE-based CMake generators, so you need to explicitly build the target for the unit -tests to be built. +You can build the Clang-tidy unit tests by building the ``ClangTidyTests`` +target. Test targets in LLVM and Clang are excluded from the "build all" style +action of IDE-based CMake generators, so you need to explicitly build the +target for the unit tests to be built. Making your check robust ^^^^^^^^^^^^^^^^^^^^^^^^ -Once you've covered your check with the basic "happy path" scenarios, you'll want to -torture your check with as many edge cases as you can cover in order to ensure your -check is robust. Running your check on a large code base, such as Clang/LLVM, is a -good way to catch things you forgot to account for in your matchers. However, the -LLVM code base may be insufficient for testing purposes as it was developed against a -particular set of coding styles and quality measures. The larger the corpus of code -the check is tested against, the higher confidence the community will have in the -check's efficacy and false-positive rate. +Once you've covered your check with the basic "happy path" scenarios, you'll +want to torture your check with as many edge cases as you can cover in order to +ensure your check is robust. Running your check on a large code base, such as +Clang/LLVM, is a good way to catch things you forgot to account for in your +matchers. However, the LLVM code base may be insufficient for testing purposes +as it was developed against a particular set of coding styles and quality +measures. The larger the corpus of code the check is tested against, the +higher confidence the community will have in the check's efficacy and +false-positive rate. Some suggestions to ensure your check is robust: @@ -409,14 +418,16 @@ Some suggestions to ensure your check is robust: - Define template classes that contain code matched by your check. - Define template specializations that contain code matched by your check. - Test your check under both Windows and Linux environments. -- Watch out for high false-positive rates. Ideally, a check would have no false - positives, but given that matching against an AST is not control- or data flow- - sensitive, a number of false positives are expected. The higher the - false-positive rate, the less likely the check will be adopted in practice. - Mechanisms should be put in place to help the user manage false positives. +- Watch out for high false-positive rates. Ideally, a check would have no + false positives, but given that matching against an AST is not control- + or data flow- sensitive, a number of false positives are expected. The + higher the false-positive rate, the less likely the check will be adopted + in practice. Mechanisms should be put in place to help the user manage + false positives. - There are two primary mechanisms for managing false positives: supporting a code pattern which allows the programmer to silence the diagnostic in an ad - hoc manner and check configuration options to control the behavior of the check. + hoc manner and check configuration options to control the behavior of the + check. - Consider supporting a code pattern to allow the programmer to silence the diagnostic whenever such a code pattern can clearly express the programmer's intent. For example, allowing an explicit cast to ``void`` to silence an @@ -430,35 +441,40 @@ Documenting your check The ``add_new_check.py`` script creates entries in the `release notes <https://clang.llvm.org/extra/ReleaseNotes.html>`_, the list of -checks and a new file for the check documentation itself. It is recommended that you -have a concise summary of what your check does in a single sentence that is repeated -in the release notes, as the first sentence in the doxygen comments in the header file -for your check class and as the first sentence of the check documentation. Avoid the -phrase "this check" in your check summary and check documentation. - -If your check relates to a published coding guideline (C++ Core Guidelines, SEI CERT, etc.) -or style guide, provide links to the relevant guideline or style guide sections in your -check documentation. - -Provide enough examples of the diagnostics and fix-its provided by the check so that a -user can easily understand what will happen to their code when the check is run. -If there are exceptions or limitations to your check, document them thoroughly. This -will help users understand the scope of the diagnostics and fix-its provided by the check. - -Building the target ``docs-clang-tools-html`` will run the Sphinx documentation generator -and create HTML documentation files in the tools/clang/tools/extra/docs/html directory in -your build tree. Make sure that your check is correctly shown in the release notes and the -list of checks. Make sure that the formatting and structure of your check's documentation -look correct. +checks and a new file for the check documentation itself. It is recommended +that you have a concise summary of what your check does in a single sentence +that is repeated in the release notes, as the first sentence in the doxygen +comments in the header file for your check class and as the first sentence of +the check documentation. Avoid the phrase "this check" in your check summary +and check documentation. + +If your check relates to a published coding guideline (C++ Core Guidelines, +SEI CERT, etc.) or style guide, provide links to the relevant guideline or +style guide sections in your check documentation. + +Provide enough examples of the diagnostics and fix-its provided by the check so +that a user can easily understand what will happen to their code when the check +is run. If there are exceptions or limitations to your check, document them +thoroughly. This will help users understand the scope of the diagnostics and +fix-its provided by the check. + +Building the target ``docs-clang-tools-html`` will run the Sphinx documentation +generator and create HTML documentation files in the +tools/clang/tools/extra/docs/html directory in your build tree. +Make sure that your check is correctly shown in the release notes and the list +of checks. Make sure that the formatting and structure of your check's +documentation look correct. Registering your Check ---------------------- -(The ``add_new_check.py`` script takes care of registering the check in an existing -module. If you want to create a new module or know the details, read on.) +(The ``add_new_check.py`` script takes care of registering the check in an +existing module. If you want to create a new module or know the details, +read on.) -The check should be registered in the corresponding module with a distinct name: +The check should be registered in the corresponding module with a distinct +name: .. code-block:: c++ @@ -550,9 +566,9 @@ YAML format: Testing Checks -------------- -To run tests for :program:`clang-tidy`, build the ``check-clang-tools`` target. -For instance, if you configured your CMake build with the ninja project generator, -use the command: +To run tests for :program:`clang-tidy`, build the ``check-clang-tools`` +target. For instance, if you configured your CMake build with the ninja project +generator, use the command: .. code-block:: console @@ -592,8 +608,8 @@ appropriate ``RUN`` line in the ``test/clang-tidy`` directory. Use ``CHECK-MESSAGES:`` and ``CHECK-FIXES:`` lines to write checks against diagnostic messages and fixed code. -It's advised to make the checks as specific as possible to avoid checks matching -incorrect parts of the input. Use ``[[@LINE+X]]``/``[[@LINE-X]]`` +It's advised to make the checks as specific as possible to avoid checks +matching incorrect parts of the input. Use ``[[@LINE+X]]``/``[[@LINE-X]]`` substitutions and distinct function and variable names in the test code. Here's an example of a test using the ``check_clang_tidy.py`` script (the full @@ -630,31 +646,32 @@ Here's an example: // CHECK-FIXES-USING-B-NOT: using a::B;$ // CHECK-FIXES-NOT: using a::C;$ -There are many dark corners in the C++ language, and it may be difficult to make -your check work perfectly in all cases, especially if it issues fix-it hints. The -most frequent pitfalls are macros and templates: - -1. Code written in a macro body/template definition may have a different meaning - depending on the macro expansion/template instantiation. -2. Multiple macro expansions/template instantiations may result in the same code - being inspected by the check multiple times (possibly, with different - meanings, see 1), and the same warning (or a slightly different one) may be - issued by the check multiple times; :program:`clang-tidy` will deduplicate - _identical_ warnings, but if the warnings are slightly different, all of them - will be shown to the user (and used for applying fixes, if any). -3. Making replacements to a macro body/template definition may be fine for some - macro expansions/template instantiations, but easily break some other +There are many dark corners in the C++ language, and it may be difficult to +make your check work perfectly in all cases, especially if it issues fix-it +hints. The most frequent pitfalls are macros and templates: + +1. Code written in a macro body/template definition may have a different + meaning depending on the macro expansion/template instantiation. +2. Multiple macro expansions/template instantiations may result in the + same code being inspected by the check multiple times (possibly, with + different meanings, see 1), and the same warning (or a slightly different + one) may be issued by the check multiple times; :program:`clang-tidy` will + deduplicate _identical_ warnings, but if the warnings are slightly + different, all of them will be shown to the user (and used for applying + fixes, if any). +3. Making replacements to a macro body/template definition may be fine for + some macro expansions/template instantiations, but easily break some other expansions/instantiations. If you need multiple files to exercise all the aspects of your check, it is -recommended you place them in a subdirectory named for the check under the ``Inputs`` -directory for the module containing your check. This keeps the test directory from -getting cluttered. +recommended you place them in a subdirectory named for the check under the +``Inputs`` directory for the module containing your check. This keeps the +test directory from getting cluttered. -If you need to validate how your check interacts with system header files, a set -of simulated system header files is located in the ``checkers/Inputs/Headers`` -directory. The path to this directory is available in a lit test with the variable -``%clang_tidy_headers``. +If you need to validate how your check interacts with system header files, a +set of simulated system header files is located in the +``checkers/Inputs/Headers`` directory. The path to this directory is +available in a lit test with the variable ``%clang_tidy_headers``. .. _lit: https://llvm.org/docs/CommandGuide/lit.html .. _FileCheck: https://llvm.org/docs/CommandGuide/FileCheck.html @@ -688,7 +705,7 @@ Out-of-tree check plugins Developing an out-of-tree check as a plugin largely follows the steps -outlined above, including creating a new module and doing the hacks to +outlined above, including creating a new module and doing the hacks to register the module. The plugin is a shared library whose code lives outside the clang-tidy build system. Build and link this shared library against LLVM as done for other kinds of Clang plugins. If using CMake, use the keyword @@ -701,18 +718,19 @@ names of the checks to enable. $ clang-tidy --checks=-*,my-explicit-constructor -list-checks -load myplugin.so -There are no expectations regarding ABI and API stability, so the plugin must be -compiled against the version of clang-tidy that will be loading the plugin. +There are no expectations regarding ABI and API stability, so the plugin must +be compiled against the version of clang-tidy that will be loading the plugin. The plugins can use threads, TLS, or any other facilities available to in-tree code which is accessible from the external headers. -Note that testing out-of-tree checks might involve getting ``llvm-lit`` from an LLVM -installation compiled from source. See `Getting Started with the LLVM System`_ for ways -to do so. +Note that testing out-of-tree checks might involve getting ``llvm-lit`` from an +LLVM installation compiled from source. See `Getting Started with the LLVM +System`_ for ways to do so. -Alternatively, get `lit`_ following the `test-suite guide`_ and get the `FileCheck`_ binary, -and write a version of `check_clang_tidy.py`_ to suit your needs. +Alternatively, get `lit`_ following the `test-suite guide`_ and get the +`FileCheck`_ binary, and write a version of `check_clang_tidy.py`_ to suit your +needs. .. _Getting Started with the LLVM System: https://llvm.org/docs/GettingStarted.html .. _test-suite guide: https://llvm.org/docs/TestSuiteGuide.html @@ -726,13 +744,14 @@ Running clang-tidy on LLVM To test a check, it's best to try it out on a larger code base. LLVM and Clang are the natural targets as you already have the source code around. The most convenient way to run :program:`clang-tidy` is with a compile command database; -CMake can automatically generate one; for a description of how to enable it, see -`How To Setup Clang Tooling For LLVM`_. Once ``compile_commands.json`` is in -place and a working version of :program:`clang-tidy` is in ``PATH`` the entire -code base can be analyzed with ``clang-tidy/tool/run-clang-tidy.py``. The script -executes :program:`clang-tidy` with the default set of checks on every -translation unit in the compile command database and displays the resulting -warnings and errors. The script provides multiple configuration flags. +CMake can automatically generate one; for a description of how to enable it, +see `How To Setup Clang Tooling For LLVM`_. Once ``compile_commands.json`` is +in place and a working version of :program:`clang-tidy` is in ``PATH`` the +entire code base can be analyzed with ``clang-tidy/tool/run-clang-tidy.py``. +The script executes :program:`clang-tidy` with the default set of checks on +every translation unit in the compile command database and displays the +resulting warnings and errors. The script provides multiple configuration +flags. .. _How To Setup Clang Tooling For LLVM: https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html @@ -746,8 +765,9 @@ warnings and errors. The script provides multiple configuration flags. that the file names are matched against. ``run-clang-tidy.py clang-tidy/.*Check\.cpp`` will only analyze `clang-tidy` checks. It may also be necessary to restrict the header files that warnings - are displayed from by using the ``-header-filter`` and ``-exclude-header-filter`` flags. - They have the same behavior as the corresponding :program:`clang-tidy` flags. + are displayed from by using the ``-header-filter`` and + ``-exclude-header-filter`` flags. They have the same behavior as the + corresponding :program:`clang-tidy` flags. * To apply suggested fixes, ``-fix`` can be passed as an argument. This gathers all changes in a temporary directory and applies them. Passing ``-format`` @@ -760,8 +780,9 @@ On checks profiling :program:`clang-tidy` can collect per-check profiling info, and output it for each processed source file (translation unit). -To enable profiling info collection, use the ``-enable-check-profile`` argument. -The timings will be output to ``stderr`` as a table. Example output: +To enable profiling info collection, use the ``-enable-check-profile`` +argument. The timings will be output to ``stderr`` as a table. +Example output: .. code-block:: console @@ -775,7 +796,8 @@ The timings will be output to ``stderr`` as a table. Example output: 0.9136 (100.0%) 0.1146 (100.0%) 1.0282 (100.0%) 1.0258 (100.0%) readability-function-size 0.9136 (100.0%) 0.1146 (100.0%) 1.0282 (100.0%) 1.0258 (100.0%) Total -It can also store that data as JSON files for further processing. Example output: +It can also store that data as JSON files for further processing. +Example output: .. code-block:: console @@ -798,8 +820,8 @@ There is only one argument that controls profile storage: * ``-store-check-profile=<prefix>`` - By default, reports are printed in tabulated format to stderr. When this option - is passed, these per-TU profiles are instead stored as JSON. + By default, reports are printed in tabulated format to stderr. When this + option is passed, these per-TU profiles are instead stored as JSON. If the prefix is not an absolute path, it is considered to be relative to the directory from where you have run :program:`clang-tidy`. All ``.`` and ``..`` patterns in the path are collapsed, and symlinks are resolved. @@ -809,9 +831,9 @@ There is only one argument that controls profile storage: ``/source`` directory. Only the input filename is used, not the full path to the source file. Additionally, it is prefixed with the current timestamp. - * If you specify ``-store-check-profile=/tmp``, then the profile will be saved - to ``/tmp/<ISO8601-like timestamp>-example.cpp.json`` + * If you specify ``-store-check-profile=/tmp``, then the profile will be + saved to ``/tmp/<ISO8601-like timestamp>-example.cpp.json`` - * If you run :program:`clang-tidy` from within ``/foo`` directory, and specify - ``-store-check-profile=.``, then the profile will still be saved to - ``/foo/<ISO8601-like timestamp>-example.cpp.json`` \ No newline at end of file + * If you run :program:`clang-tidy` from within ``/foo`` directory, and + specify ``-store-check-profile=.``, then the profile will still be + saved to ``/foo/<ISO8601-like timestamp>-example.cpp.json`` diff --git a/clang-tools-extra/docs/clang-tidy/ExternalClang-TidyExamples.rst b/clang-tools-extra/docs/clang-tidy/ExternalClang-TidyExamples.rst index 3d654e232a3ad..9b9b48478447a 100644 --- a/clang-tools-extra/docs/clang-tidy/ExternalClang-TidyExamples.rst +++ b/clang-tools-extra/docs/clang-tidy/ExternalClang-TidyExamples.rst @@ -5,20 +5,21 @@ External Clang-Tidy Examples Introduction ============ -This page provides examples of what people have done with :program:`clang-tidy` that -might serve as useful guides (or starting points) to develop your own checks. -They may be helpful for necessary things such as how to write the `CMakeLists.txt` -for an out-of-tree plugin of :program:`clang-tidy` checks. +This page provides examples of what people have done with :program:`clang-tidy` +that might serve as useful guides (or starting points) to develop your own +checks. They may be helpful for necessary things such as how to write the +`CMakeLists.txt` for an out-of-tree plugin of :program:`clang-tidy` checks. -If you know of (or wrote!) a tool or project using :program:`clang-tidy`, please share it -on `the Discourse forums (Clang Frontend category) -<https://discourse.llvm.org/c/clang/6>`_ for wider visibility and open a -pull-request on `LLVM Github`_ to have it added here. Since the primary purpose of -this page is to provide examples that can help developers, the listed projects should -have code available. +If you know of (or wrote!) a tool or project using :program:`clang-tidy`, +please share it on `the Discourse forums (Clang Frontend category) +<https://discourse.llvm.org/c/clang/6>`_ for wider visibility and open a +pull-request on `LLVM Github`_ to have it added here. Since the primary +purpose of this page is to provide examples that can help developers, the +listed projects should have code available. -As :program:`clang-tidy` is using, for example, the AST Matchers and diagnostics of Clang, -`External Clang Examples`_ may also be useful to look at for such examples. +As :program:`clang-tidy` is using, for example, the AST Matchers and +diagnostics of Clang, `External Clang Examples`_ may also be useful to look at +for such examples. .. _LLVM Github: https://github.com/llvm/llvm-project .. _External Clang Examples: https://clang.llvm.org/docs/ExternalClangExamples.html diff --git a/clang-tools-extra/docs/clang-tidy/Integrations.rst b/clang-tools-extra/docs/clang-tidy/Integrations.rst index 7104944120a93..e8cb03524ab34 100644 --- a/clang-tools-extra/docs/clang-tidy/Integrations.rst +++ b/clang-tools-extra/docs/clang-tidy/Integrations.rst @@ -83,9 +83,10 @@ possible with the `Clang Tools`_ analyzer. .. _Visual Assist: https://docs.wholetomato.com/default.asp?W761 .. _Clang Power Tools: https://marketplace.visualstudio.com/items?itemName=caphyon.ClangPowerTools -`MS Visual Studio`_ can integrate :program:`clang-tidy` by means of three different tools. -The `ReSharper C++`_ extension, version 2017.3 and later, provides seamless -:program:`clang-tidy` integration: checks and quick-fixes run alongside native inspections. +`MS Visual Studio`_ can integrate :program:`clang-tidy` by means of three +different tools. The `ReSharper C++`_ extension, version 2017.3 and later, +provides seamless :program:`clang-tidy` integration: checks and quick-fixes run +alongside native inspections. Apart from that, ReSharper C++ incorporates :program:`clang-tidy` as a separate step of its code clean-up process. `Visual Assist`_ build 2210 includes a subset of :program:`clang-tidy` checklist to inspect the code as you edit. diff --git a/clang-tools-extra/docs/clang-tidy/QueryBasedCustomChecks.rst b/clang-tools-extra/docs/clang-tidy/QueryBasedCustomChecks.rst index f10d15412fe16..f68a8a7e3ba42 100644 --- a/clang-tools-extra/docs/clang-tidy/QueryBasedCustomChecks.rst +++ b/clang-tools-extra/docs/clang-tidy/QueryBasedCustomChecks.rst @@ -28,7 +28,8 @@ Configuration - Diagnostic: list of diagnostics to be reported. - BindName: name of the node to be bound in `Query`. - Message: message to be reported. - - Level: severity of the diagnostic, the possible values are `Note`, `Warning`. + - Level: severity of the diagnostic, the possible values are `Note`, + `Warning`. `CustomChecks` can be configured by `Checks` option in the configuration file. diff --git a/clang-tools-extra/docs/clang-tidy/checks/fuchsia/multiple-inheritance.rst b/clang-tools-extra/docs/clang-tidy/checks/fuchsia/multiple-inheritance.rst index 85eb504104f6b..c5ae6a2efb2cb 100644 --- a/clang-tools-extra/docs/clang-tidy/checks/fuchsia/multiple-inheritance.rst +++ b/clang-tools-extra/docs/clang-tidy/checks/fuchsia/multiple-inheritance.rst @@ -6,4 +6,4 @@ fuchsia-multiple-inheritance The `fuchsia-multiple-inheritance` check is an alias, please See :doc:`misc-multiple-inheritance <../misc/multiple-inheritance>` for details. -See the features disallowed in Fuchsia at https://fuchsia.dev/fuchsia-src/development/languages/c-cpp/cxx?hl=en \ No newline at end of file +See the features disallowed in Fuchsia at https://fuchsia.dev/fuchsia-src/development/languages/c-cpp/cxx?hl=en diff --git a/clang-tools-extra/docs/clang-tidy/checks/google/readability-casting.rst b/clang-tools-extra/docs/clang-tidy/checks/google/readability-casting.rst index 31ee3bd457d03..77983c400053d 100644 --- a/clang-tools-extra/docs/clang-tidy/checks/google/readability-casting.rst +++ b/clang-tools-extra/docs/clang-tidy/checks/google/readability-casting.rst @@ -3,8 +3,8 @@ google-readability-casting ========================== -The `google-readability-casting` check is an alias, please see -:doc:`modernize-avoid-c-style-cast <../modernize/avoid-c-style-cast>` +The `google-readability-casting` check is an alias, please see +:doc:`modernize-avoid-c-style-cast <../modernize/avoid-c-style-cast>` for more information. Finds usages of C-style casts. diff --git a/clang-tools-extra/docs/clang-tidy/index.rst b/clang-tools-extra/docs/clang-tidy/index.rst index 6ff82bf230f4b..420dbafb510a1 100644 --- a/clang-tools-extra/docs/clang-tidy/index.rst +++ b/clang-tools-extra/docs/clang-tidy/index.rst @@ -17,9 +17,9 @@ See also: :program:`clang-tidy` is a clang-based C++ "linter" tool. Its purpose is to provide an extensible framework for diagnosing and fixing typical programming -errors, like style violations, interface misuse, or bugs that can be deduced via -static analysis. :program:`clang-tidy` is modular and provides a convenient -interface for writing new checks. +errors, like style violations, interface misuse, or bugs that can be deduced +via static analysis. :program:`clang-tidy` is modular and provides a +convenient interface for writing new checks. Using Clang-Tidy @@ -57,16 +57,16 @@ checks except for ``clang-analyzer-cplusplus*`` ones. The ``-list-checks`` option lists all the enabled checks. When used without ``-checks=``, it shows checks enabled by default. Use ``-checks=*`` to see all -available checks or with any other value of ``-checks=`` to see which checks are -enabled by this value. +available checks or with any other value of ``-checks=`` to see which checks +are enabled by this value. .. _checks-groups-table: There are currently the following groups of checks: -====================== ========================================================= +====================== ======================================================== Name prefix Description -====================== ========================================================= +====================== ======================================================== ``abseil-`` Checks related to Abseil library. ``altera-`` Checks related to OpenCL programming for FPGAs. ``android-`` Checks related to Android. @@ -85,24 +85,24 @@ Name prefix Description ``llvm-`` Checks related to the LLVM coding conventions. ``llvmlibc-`` Checks related to the LLVM-libc coding standards. ``misc-`` Checks that we didn't have a better category for. -``modernize-`` Checks that advocate usage of modern (currently "modern" - means "C++11") language constructs. +``modernize-`` Checks that advocate usage of modern (currently + "modern" means "C++11") language constructs. ``mpi-`` Checks related to MPI (Message Passing Interface). ``objc-`` Checks related to Objective-C coding conventions. ``openmp-`` Checks related to OpenMP API. ``performance-`` Checks that target performance-related issues. -``portability-`` Checks that target portability-related issues that don't - relate to any particular coding style. -``readability-`` Checks that target readability-related issues that don't - relate to any particular coding style. +``portability-`` Checks that target portability-related issues that + don't relate to any particular coding style. +``readability-`` Checks that target readability-related issues that + don't relate to any particular coding style. ``zircon-`` Checks related to Zircon kernel coding conventions. -====================== ========================================================= +====================== ======================================================== Clang diagnostics are treated in a similar way as check diagnostics. Clang -diagnostics are displayed by :program:`clang-tidy` and can be filtered out using -the ``-checks=`` option. However, the ``-checks=`` option does not affect -compilation arguments, so it cannot turn on Clang warnings which are not -already turned on in the build configuration. The ``-warnings-as-errors=`` +diagnostics are displayed by :program:`clang-tidy` and can be filtered out +using the ``-checks=`` option. However, the ``-checks=`` option does not +affect compilation arguments, so it cannot turn on Clang warnings which are +not already turned on in the build configuration. The ``-warnings-as-errors=`` option upgrades any warnings emitted under the ``-checks=`` flag to errors (but it does not enable any checks itself). @@ -112,12 +112,12 @@ Diagnostics which have a corresponding warning option, are named ``-Wliteral-conversion`` will be reported with check name ``clang-diagnostic-literal-conversion``. -Clang compiler errors (such as syntax errors, semantic errors, or other failures -that prevent Clang from compiling the code) are reported with the check name -``clang-diagnostic-error``. These represent fundamental compilation failures that -must be fixed before :program:`clang-tidy` can perform its analysis. Unlike other -diagnostics, ``clang-diagnostic-error`` cannot be disabled, as :program:`clang-tidy` -requires valid code to function. +Clang compiler errors (such as syntax errors, semantic errors, or other +failures that prevent Clang from compiling the code) are reported with the +check name ``clang-diagnostic-error``. These represent fundamental compilation +failures that must be fixed before :program:`clang-tidy` can perform its +analysis. Unlike other diagnostics, ``clang-diagnostic-error`` cannot be +disabled, as :program:`clang-tidy` requires valid code to function. The ``-fix`` flag instructs :program:`clang-tidy` to fix found errors if supported by corresponding checks. @@ -472,12 +472,12 @@ its use is not desired for some reason, :program:`clang-tidy` has a generic mechanism to suppress diagnostics using ``NOLINT``, ``NOLINTNEXTLINE``, and ``NOLINTBEGIN`` ... ``NOLINTEND`` comments. -The ``NOLINT`` comment instructs :program:`clang-tidy` to ignore warnings on the -*same line* (it doesn't apply to a function, a block of code or any other -language construct; it applies to the line of code it is on). If introducing the -comment on the same line would change the formatting in an undesired way, the -``NOLINTNEXTLINE`` comment allows suppressing clang-tidy warnings on the *next -line*. The ``NOLINTBEGIN`` and ``NOLINTEND`` comments allow suppressing +The ``NOLINT`` comment instructs :program:`clang-tidy` to ignore warnings on +the *same line* (it doesn't apply to a function, a block of code or any other +language construct; it applies to the line of code it is on). If introducing +the comment on the same line would change the formatting in an undesired way, +the ``NOLINTNEXTLINE`` comment allows suppressing clang-tidy warnings on the +*next line*. The ``NOLINTBEGIN`` and ``NOLINTEND`` comments allow suppressing clang-tidy warnings on *multiple lines* (affecting all lines between the two comments). _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
