Before this change, `-quiet` mode in clang-tidy generated meaningless
messages `xxx warnings generated` in output:
```cpp
// main.cpp
#include <iostream>
int main() {
std::cout << 42;
}
```
```console
> clang-tidy -checks='-*,readability-magic-numbers' -quiet main.cpp
82 warnings generated.
main.cpp:4:16: warning: 42 is a magic number; consider replacing it with a named constant [readability-magic-numbers]
4 | std::cout << 42;
| ^
```
As you can see, `82 warnings generated.` does not say much `quiet` mode,
this patch removes this message completely:
```console
> ./build/bin/clang-tidy -p build -checks='-*,readability-magic-numbers' -quiet main.cpp
main.cpp:4:16: warning: 42 is a magic number; consider replacing it with a named constant [readability-magic-numbers]
4 | std::cout << 42;
| ^
```
In contrast, when running without `quiet`, It gives some meaningful
information because we know how many messages were suppressed thus
calculating total messages count:
```console
> clang-tidy -checks='-*,readability-magic-numbers' main.cpp
82 warnings generated.
main.cpp:4:16: warning: 42 is a magic number; consider replacing it with a named constant [readability-magic-numbers]
4 | std::cout << 42;
| ^
Suppressed 81 warnings (81 in non-user code).
Use -header-filter=.* to display errors from all non-system headers. Use -system-headers to display errors from system headers as well.
```
Fixes#47042
This helps better distinguish warnings that could be disabled via
`.clang-tidy` config (like `clang-diagnostic-literal-conversion`) from
errors that could not be suppressed at all (like
`clang-diagnostic-error`) because it's a hard compiler error.
```cpp
struct Base {
int m;
};
template <class T>
struct Derived : Base {
Derived() { m = 0; }
};
```
would previously generate the following output:
```
<source>:7:15: warning: 'm' should be initialized in a member initializer of the constructor [cppcoreguidelines-prefer-member-initializer]
7 | Derived() { m = 0; }
| ^~~~~~
| : m(0)
```
This patch fixes this false positive.
Note that before this patch the checker won't give false positive for
```cpp
struct Derived : Base {
Derived() { m = 0; }
};
```
and the constructor's AST is
```
`-CXXConstructorDecl 0x557df03d1fb0 <line:7:3, col:22> col:3 Derived 'void ()' implicit-inline
|-CXXCtorInitializer 'Base'
| `-CXXConstructExpr 0x557df03d2748 <col:3> 'Base' 'void () noexcept'
`-CompoundStmt 0x557df03d2898 <col:13, col:22>
`-BinaryOperator 0x557df03d2878 <col:15, col:19> 'int' lvalue '='
|-MemberExpr 0x557df03d2828 <col:15> 'int' lvalue ->m 0x557df03d1c40
| `-ImplicitCastExpr 0x557df03d2808 <col:15> 'Base *' <UncheckedDerivedToBase (Base)>
| `-CXXThisExpr 0x557df03d27f8 <col:15> 'Derived *' implicit this
`-IntegerLiteral 0x557df03d2858 <col:19> 'int' 0
```
so `isAssignmentToMemberOf` would return empty due to
f0967fca04/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp (L118-L119)Fixes#104400
This commit is a re-do of e4a8969e56572371201863594b3a549de2e23f32,
which got reverted, with the same goal: dramatically speed-up clang-tidy
by avoiding doing work in system headers (which is wasteful as warnings
are later discarded). This proposal was already discussed here with
favorable feedback: https://github.com/llvm/llvm-project/pull/132725
The novelty of this patch is:
- It's less aggressive: it does not fiddle with AST traversal. This
solves the issue with the previous patch, which impacted the ability to
inspect parents of a given node.
- Instead, what we optimize for is exitting early in each `Traverse*`
function of `MatchASTVisitor` if the node is in a system header, thus
avoiding calling the `match()` function with its corresponding callback
(when there is a match).
- It does not cause any failing tests.
- It does not move `MatchFinderOptions` - instead we add a user-defined
default constructor which solves the same problem.
- It introduces a function `shouldSkipNode` which can be extended for
adding more conditions. For example there's a PR open about skipping
modules in clang-tidy where this could come handy:
https://github.com/llvm/llvm-project/pull/145630
As a benchmark, I ran clang-tidy with all checks activated, on a single
.cpp file which #includes all the standard C++ headers, then measure the
time as well as found warnings.
On trunk:
```
Suppressed 75413 warnings (75413 in non-user code).
real 0m12.418s
user 0m12.270s
sys 0m0.129s
```
With this patch:
```
Suppressed 11448 warnings (11448 in non-user code).
Use -header-filter=.* to display errors from all non-system headers. Use -system-headers to display errors from system headers as well.
real 0m1.666s
user 0m1.538s
sys 0m0.129s
```
With the original patch that got reverted:
```
Suppressed 11428 warnings (11428 in non-user code).
real 0m1.193s
user 0m1.096s
sys 0m0.096s
```
We therefore get a dramatic reduction in number of warnings and runtime,
with no change in functionality.
The remaining warnings are due to `PPCallbacks` - implementing a similar
system-header exclusion mechanism there can lead to almost no warnings
left in system headers. This does not bring the runtime down as much,
though, so it's probably not worth the effort.
Fixes#52959
Co-authored-by: Carlos Gálvez <carlos.galvez@zenseact.com>
The script copies `ReleaseNotesTemplate.txt` to corresponding
`ReleaseNotes.rst`/`.md` to clear release notes.
The suffix of `ReleaseNotesTemplate.txt` must be `.txt`. If it is
`.rst`/`.md`, it will be treated as a documentation source file when
building documentation.
Correctly generating fix hints when size method is called from implicit
this.
Closes#152387.
---------
Co-authored-by: Baranov Victor <bar.victor.2002@gmail.com>
Co-authored-by: EugeneZelenko <eugene.zelenko@gmail.com>
Useful when the check warns on template functions to know which type
it's complaining about. Otherwise, since the instantiation stack is not
printed, it's very hard to tell.
Co-authored-by: Carlos Gálvez <carlos.galvez@zenseact.com>
This patch implements a fix for the false-positive case described in
[issue #134840](https://github.com/llvm/llvm-project/issues/134840) for
the
[bugprone-tagged-union-member-count](https://clang.llvm.org/extra/clang-tidy/checks/bugprone/tagged-union-member-count.html)
clang-tidy check.
The example given in the linked issue was the following:
```C
#include <pthread.h>
typedef enum {
MYENUM_ONE,
MYENUM_TWO,
} myEnumT;
typedef struct {
pthread_mutex_t mtx;
myEnumT my_enum;
} myTypeT;
```
The
[bugprone-tagged-union-member-count](https://clang.llvm.org/extra/clang-tidy/checks/bugprone/tagged-union-member-count.html)
check emits the following a warning for this struct:
```
<source>:8:9: warning: tagged union has more data members (3) than tags (2)! [bugprone-tagged-union-member-count]
8 | typedef struct {
| ^
1 warning generated.
```
The issue is that `pthread_mutex_t` can be a union behind a typedef like
the following:
```C
typedef union
{
struct __pthread_mutex_s __data;
char __size[__SIZEOF_PTHREAD_MUTEX_T];
long int __align;
} pthread_mutex_t;
```
From the checker's point of view therefore `myTypeT` contains a data
member with an enum type and another data member with a union type and
starts analyzing it like a user-defined tagged union.
The proposed solution is that the types from system headers and the std
namespace are no longer candidates to be the enum part or the union part
of a user-defined tagged union. This filtering for enums and the std
namespace may not be strictly necessary in this example, however I added
it preemptively out of (perhaps unnecessary) caution.
Fixes https://github.com/llvm/llvm-project/issues/134840.
Let's consider the following code from the issue #139467:
```c
void test(int cond, char c) {
char ret = cond > 0 ? ':' : c;
}
```
Initializer of `ret` looks the following:
```
-ImplicitCastExpr 'char' <IntegralCast>
`-ConditionalOperator 'int'
|-BinaryOperator 'int' '>'
| |-ImplicitCastExpr 'int' <LValueToRValue>
| | `-DeclRefExpr 'int' lvalue ParmVar 'cond' 'int'
| `-IntegerLiteral 'int' 0
|-CharacterLiteral 'int' 58
`-ImplicitCastExpr 'int' <IntegralCast>
`-ImplicitCastExpr 'char' <LValueToRValue>
`-DeclRefExpr 'char' lvalue ParmVar 'c' 'char'
```
So it could be seen that `RHS` of the conditional operator is
`DeclRefExpr 'c'` which is casted to `int` and then the whole
conditional expression is casted to 'char'. But this last conversion is
not narrowing, because `RHS` was `char` _initially_. We should just
remove the cast from `char` to `int` before the narrowing conversion
check.
Fixes#139467
Add new option `enable-check-profiling` to `run-clang-tidy` for seamless
integration of `clang-tidy`'s `enable-check-profiling` option.
`run-clang-tidy` will post aggregated results report in the same style
as `clang-tidy`.
This PR will help users to benchmark their `clang-tidy` runs easily.
Also, `clang-tidy` developers could build benchmark infrastructure in
the future.
…heck
One typically only wants to perform renaming operations in user code,
not in system headers (which are out of the user's control). Let's skip
those altogether.
This leads to performance improvements in clang-tidy. As a benchmark, I
run all checks on a .cpp file that #includes all C++ standard headers.
On trunk:
```
Suppressed 213362 warnings (213362 in non-user code).
real 0m14.422s
user 0m14.236s
sys 0m0.184s
```
On this patch:
```
Suppressed 75411 warnings (75411 in non-user code).
real 0m12.472s
user 0m12.334s
sys 0m0.136s
```
Co-authored-by: Carlos Gálvez <carlos.galvez@zenseact.com>
`readability-qualified-auto` check currently looks at the unsugared
type, skipping any typedefs, to determine if the variable is a
pointer-type. This may not be the desired behaviour, in particular when
the type depends on compilation flags.
For example
```
#if CONDITION
using Handler = int *;
#else
using Handler = uint64_t;
#endif
```
A more common example is some implementations of `std::array` use
pointers as iterators.
This introduces the IgnoreAliasing option so that
`readability-qualified-auto` does not look beyond typedefs.
---------
Co-authored-by: juanbesa <juanbesa@devvm33299.lla0.facebook.com>
Co-authored-by: Kazu Hirata <kazu@google.com>
Co-authored-by: EugeneZelenko <eugene.zelenko@gmail.com>
Co-authored-by: Baranov Victor <bar.victor.2002@gmail.com>
This relands commit
7355ea3f6b.
The original commit was reverted in
bfd73a5161
because it was breaking the buildbot.
The issue has now been resolved by
38f82534bb.
Original PR: https://github.com/llvm/llvm-project/pull/139348
Original commit message:
<blockquote>
closes https://github.com/clangd/clangd/issues/1037
closes https://github.com/clangd/clangd/issues/2240
Example:
```c++
class Base {
public:
virtual void publicMethod() = 0;
protected:
virtual auto privateMethod() const -> int = 0;
};
// Before:
// // cursor here
class Derived : public Base{}^ ;
// After:
class Derived : public Base {
public:
void publicMethod() override {
// TODO: Implement this pure virtual method.
static_assert(false, "Method `publicMethod` is not implemented.");
}
protected:
auto privateMethod() const -> int override {
// TODO: Implement this pure virtual method.
static_assert(false, "Method `privateMethod` is not implemented.");
}
};
```
https://github.com/user-attachments/assets/79de40d9-1004-4c2e-8f5c-be1fb074c6de
</blockquote>
Change the default value of `-j` from `1` to `0` in `clang-tidy-diff.py`
script to autodetect number of CPU cores to run on.
Script `run-clang-tidy.py` already had this behavior by default.
Both scripts now also print the number of threads being used to
provide better visibility into their execution behavior.
Fixes https://github.com/llvm/llvm-project/issues/148624.
These checks previously failed with absl::StrFormat and absl::PrintF
etc. with:
Unable to use 'std::format' instead of 'StrFormat' because first
argument is not a narrow string literal [modernize-use-std-format]
because FormatStringConverter was rejecting the format string if it had
already converted into a different type. Fix the tests so that they
check this case properly by accepting string_view rather than const char
* and fix the check so that these tests pass. Update the existing tests
that checked for the error message that can no longer happen.
Fixes: https://github.com/llvm/llvm-project/issues/129484
Upstream is moving towards new create method invocation, add check to flag old
usage that will be deprecated.
---------
Co-authored-by: Baranov Victor <bar.victor.2002@gmail.com>
Co-authored-by: EugeneZelenko <eugene.zelenko@gmail.com>
Ignore false positives on C23 enums which allows setting the fixed
underlying type to signed char.
The AST tree for C enums includes a ImplicitCastExp
(that was matched) but this is not the case for C++ enums.
Fixes#145651
---------
Signed-off-by: Björn Svensson <bjorn.a.svensson@est.tech>
When release notes were cleared on ``main``, clang-tools-extra project
already cleared release notes and commit
3d8db8ef50b7e59d5a1943ddc14597327eff88fd flushed them. This patch
restores lost release notes.
Ignore pure virtual member functions in
portability-template-virtual-member-function check.
Those functions will be represented in vtable
as __cxa_pure_virtual or something similar.
Fixes#139031.
Performance optimization of misc-header-include-cycle
based on clangd test on Sema.cpp. Check were slow due
calls to SM.translateFile. Cost reduction (+-) from 11% to 3%.
This change enhances the `bugprone-unhandled-self-assignment` checker by
adding an additional matcher that generalizes the copy-and-swap idiom
pattern detection.
# What Changed
Added a new matcher that checks for:
- An instance of the current class being created in operator=
(regardless of constructor arguments)
- That instance being passed to a `swap` function call
# Problem Solved
This fix reduces false positives in PMR-like scenarios where "extended"
constructors are used (typically taking an additional allocator
argument). The checker now properly recognizes copy-and-swap
implementations that use extended copy/move constructors instead of
flagging them as unhandled self-assignment cases.
Fixes#146324
---------
Co-authored-by: Baranov Victor <bar.victor.2002@gmail.com>
Before this patch, this check only handles `VarDecl` as varaibles
declaration in statement, but this will ignore variables in structured
bindings (`BindingDecl` in AST), which leads to false positives.
Closes#138842.
closes https://github.com/clangd/clangd/issues/1037
closes https://github.com/clangd/clangd/issues/2240
Example:
```c++
class Base {
public:
virtual void publicMethod() = 0;
protected:
virtual auto privateMethod() const -> int = 0;
};
// Before:
// // cursor here
class Derived : public Base{}^ ;
// After:
class Derived : public Base {
public:
void publicMethod() override {
// TODO: Implement this pure virtual method.
static_assert(false, "Method `publicMethod` is not implemented.");
}
protected:
auto privateMethod() const -> int override {
// TODO: Implement this pure virtual method.
static_assert(false, "Method `privateMethod` is not implemented.");
}
};
```
https://github.com/user-attachments/assets/79de40d9-1004-4c2e-8f5c-be1fb074c6de
---------
Co-authored-by: Marco Maia <marco.maia@iarasystems.com.br>
Allow AST matches in clang-query to have a trailing comma at the end of
matcher arguments. Makes it nicer to work with queries that span
multiple lines.
So, for example, the following is possible:
```clang-query
match namedDecl(
isExpansionInMainFile(),
anyOf(
varDecl().bind("var"),
functionDecl().bind("func"),
# enumDecl().bind("enum"),
),
)
```
This check already understands how `constexpr` makes initialization
order problems impossible, and C++20's `constinit` provides the exact
same guarantees.
This PR add stacktrace of escaped exception to
`bugprone-exception-escape` check.
Changes:
1. Modified `ExceptionAnalyzer` and `ExceptionInfo` classes to hold
stacktrace of escaped exception in `llvm::MapVector`. `llvm::MapVector`
is needed to hold relative positions of functions in stack as well as
have fast lookup.
2. Added new diagnostics based of `misc-no-recursion` check.
Fixes https://github.com/llvm/llvm-project/issues/87422.
Added function to filter out `CheckOptions` that come from
`ClangTidyOptions::getDefaults()`, but does not have a corresponding
check enabled in the `Checks` configuration.
Fixes https://github.com/llvm/llvm-project/issues/146693.
Closes#132561.
This is a check that rewrites `#if`s and `#elif`s like so:
```cpp
#if defined(MEOW) // -> #ifdef MEOW
#if !defined(MEOW) // -> #ifndef MEOW
```
And, since C23 and C++23:
```cpp
#elif defined(MEOW) // -> #elifdef MEOW
#elif !defined(MEOW) // -> #elifndef MEOW
```
Finds function and variable declarations inside anonymous namespace and
suggests replacing them with ``static`` declarations.
The check will enforce that
[restrict-visibility](https://llvm.org/docs/CodingStandards.html#restrict-visibility)
rule in LLVM Coding Standards is followed correctly (by adding `static`
to functions instead of putting them in anonimous namespace).
The check has additional levels of "strictness" represented by Options.
By default, the check works in the most relaxed way by giving warning
only for methods and functions defined in anonymous namespaces. Also, It
finds `static` functions that are placed inside anonymous namespace -
there is no point in keeping them inside.
Add InsertPlainNamesInForwardDecls option to readability-named-parameter
check to insert parameter names without comments for forward
declarations only.
When enabled, forward declarations get plain parameter names (e.g., `int
param`) while function definitions continue to use commented names
(e.g., `int /*param*/`). Named parameters in forward decls don't cause
compiler warnings and some developers prefer to have names without
comments but in sync between declarations and the definition.
Default behavior remains unchanged
(InsertPlainNamesInForwardDecls=false).
Example with InsertPlainNamesInForwardDecls=true:
```cpp
// Forward declaration - gets plain name because the definition has name.
void func(int param);
void func(int param) { ... = param; }
```
Fix false positives when copy assignment operator function in a template
class returns the result of another assignment to `*this`, this check
doesn't consider this situation that there will be a `BinaryOperator`
for assignment rather than `CXXOperatorCallExpr` since `this`'s type is
dependent.
Closes#143237.