Commit Graph

1108 Commits

Author SHA1 Message Date
flovent
5a8d096ae3 [clang-tidy] Fix false positive for cppcoreguidelines-pro-bounds-pointer-arithmetic (#127394)
this PR fixes #126424
for `ArraySubScriptExpr`, `hasBase` Matcher will get right operand when
it is not integer type, but is not for sure that left operand is integer
type. For the example code below `hasBase` will get `r` for the
Subsequent matching and causing false positive.
```
template <typename R>
int f(std::map<R*, int>& map, R* r) {
  return map[r];
}
```
so is needed to see if index is integer type to avoid this situation.
2025-07-02 17:41:24 +03:00
Dimitrije Dobrota
0f291e5787 [clang-tidy] Add flag to specify an alternative to std::move in cppcoreguidelines-rvalue-reference-param-not-moved (#138757)
Since std::move is nothing more than a cast, part of STL and not the
language itself, it's easy to provide a custom implementation if one
wishes not to include the entirety of <utility>.

Added flag (MoveFunction) provides a way to continue using this
essential check even with the custom implementation of moving.

---------

Co-authored-by: EugeneZelenko <eugene.zelenko@gmail.com>
2025-06-30 22:36:23 +03:00
Dimitrije Dobrota
6a57af8d03 [clang-tidy] Add flag to specify an alternative to std::forward (#138755)
Since std::forward is nothing more than a cast, part of STL and not the
language itself, it's easy to provide a custom implementation if one
wishes not to include the entirety of <utility>.

Added flag (ForwardFunction) provides a way to continue using this
essential check even with the custom implementation of forwarding.

---------

Co-authored-by: EugeneZelenko <eugene.zelenko@gmail.com>
2025-06-30 22:13:33 +03:00
Baranov Victor
a3a60e03e2 [clang-tidy] add new check: modernize-use-scoped-lock (#126434)
Add new clang-tidy check that finds uses of `std::lock_guard` and suggests
replacing them with C++17's more flexible and safer alternative
`std::scoped_lock`.

Here is a small description of how it works for better understanding of
the code:
Two separate AST matchers are registered:

- The first one matches declarations of `std::lock_guard` that are
single in their scope (only one `std::lock_guard` in `CompoundStmt`).
It's an easy case, we can emit warning right away.

- The second one matches `CompoundStmt`'s that have multiple
`std::lock_guard` declarations, which means that we may have consecutive
declarations of `std::lock_guard` that can be replaced by a single
`std::scoped_lock`. In order to ensure that declarations are
consecutive, we need to loop over `Stmt`'s in `CompoundStmt`. Here is a
small example:
```cpp
{
  std::mutex m1, m2;
  std::lock(m1, m2);
  std::lock_guard<std::mutex> l1(m, std::adopt_lock); // first declaration of 'std::lock_guard'
  std::lock_guard<std::mutex> l2(m, std::adopt_lock); // second declaration of 'std::lock_guard' that can be merged with first using 'scoped_lock'
}
```

This PR closes https://github.com/llvm/llvm-project/issues/107839.
2025-06-29 22:34:32 +03:00
Björn Svensson
8351752dbc [clang-tidy] Fix false positives in readability-redundant-inline-specifier (#135391)
The out-of-line explicitly-defaulted definition is not the first
declaration, so it is not implicitly inline.

Alt. reference:
9.5.2 (3) Explicitly-defaulted functions in
[N4950](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/n4950.pdf).
or https://timsong-cpp.github.io/cppwp/n4861/dcl.fct.def.default#3

Fixes #130745

---------

Signed-off-by: Björn Svensson <bjorn.a.svensson@est.tech>
2025-06-28 09:10:34 +03:00
Malavika Samak
86026ee623 [clang-tidy] Warn about misuse of sizeof operator in loops. (#143205)
The sizeof operator misuses in loop conditionals can be a source of
bugs. The common misuse is attempting to retrieve the number of elements
in the array by using the sizeof expression and forgetting to divide the
value by the sizeof the array elements. This results in an incorrect
computation of the array length and requires a warning from the sizeof
checker.

Example:
```
 int array[20];

void test_for_loop() {
  // Needs warning.
  for(int i = 0; i < sizeof(array); i++) {
    array[i] = i;
  }
}

void test_while_loop() {

  int count = 0;
  // Needs warning. 
  while(count < sizeof(array)) {
    array[count] = 0;
    count = count + 2;
  }
}
```
rdar://151403083

---------

Co-authored-by: MalavikaSamak <malavika2@apple.com>
2025-06-25 10:04:10 -07:00
Baranov Victor
e435558ff9 [clang-tidy] add 'IgnoreMarcos' option to 'special-member-functions' check (#143550) 2025-06-24 08:39:05 +03:00
Baranov Victor
c594f6e697 Revert "[clang-tidy] Add new check readability-use-numeric-limits" (#145355)
Reverts llvm/llvm-project#127430 due to stable asan buildbot failures:
https://lab.llvm.org/buildbot/#/builders/169
2025-06-23 19:39:01 +03:00
Baranov Victor
05491e0359 [clang-tidy] add 'IgnoreMarcos' option to 'avoid-goto' check (#143554) 2025-06-23 16:27:18 +03:00
Katherine Whitlock
e7dd223ec4 [clang-tidy] Add new check readability-use-numeric-limits (#127430)
The adds a check that replaces specific numeric literals like `32767`
with the equivalent call to `std::numeric_limits` (such as
`std::numeric_limits<int16_t>::max())`.

Partially addresses #34434, but notably does not handle cases listed in
the title post such as `~0` and `-1`.
2025-06-21 21:10:20 +03:00
Baranov Victor
1b5d6ec685 [clang-tidy] count class member initializers as statements in 'readability-function-size' (#131669)
Improve `readability-function-size` by counting class member
initializers as statements.
Relates to https://github.com/llvm/llvm-project/issues/131126
2025-06-21 13:14:19 +03:00
Philipp Jung
669627d0c7 Add check 'cppcoreguidelines-use-enum-class' (#138282)
Warn on non-class enum definitions as suggested by the Core Guidelines:
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Renum-class
2025-06-18 11:02:53 +02:00
Dmitry Polukhin
26d082d330 [clang-tidy][performance-unnecessary-value-param] Avoid in coroutines (#140912)
Summary:
Replacing by-value parameters with passing by-reference is not safe for
coroutines because the caller may be executed in parallel with the
callee, which increases the chances of resulting in dangling references
and hard-to-find crashes. See for the reference
[cppcoreguidelines-avoid-reference-coroutine-parameters](https://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines/avoid-reference-coroutine-parameters.html).

Test Plan: check-clang-tools
2025-06-17 09:47:15 +01:00
David Rivera
3c1053811e Revert "[clang-tidy] Improve integer comparison by matching valid expressions outside implicitCastExpr" (#143944)
Reverts llvm/llvm-project#134188
related: https://github.com/llvm/llvm-project/issues/143927
2025-06-12 14:33:06 -04:00
David Rivera
e65d323166 [clang-tidy] Improve integer comparison by matching valid expressions outside implicitCastExpr (#134188)
Aims to fix #127471
Covered the edge case where an int expression is not necessarily
directly wrapped around an 'ImplicitCastExpr' which seemed to be a
requirement in 'use-integer-sign-comparison.cpp' check to trigger.

**For instance**:

```cpp
#include <vector>

bool f() {
  std::vector<int> v;
  unsigned int i = 0;

  return i >= v.size();
}
```
2025-06-10 10:57:11 +03:00
Thorsten Klein
00eb22fff9 added option google-readability-namespace-comments.AllowNoNamespaceComments (#124265)
New option AllowNoNamespaceComments for
`google-readability-namespace-comments.AllowNoNamespaceComments` is
added.

When true, the check will allow that no namespace comment is present. If
a namespace comment is added but it is not matching, the check will
fail. Default is `false`

Fixes #124264
2025-06-08 13:19:40 +03:00
flovent
239c8ac268 [clang-tidy] Fix false positives with deducing this in readability-convert-member-functions-to-static check (#141391)
Add check for `DeclRefExpr` which points to an explicit object
parameter.

Fixes #141381.

---------

Co-authored-by: fubowen <fubowen@protomail.com>
Co-authored-by: flovent <flbven@protomail.com>
2025-06-08 09:58:24 +03:00
Carlos Galvez
30d8aebbe2 [clang-tidy] Add option to disable bugprone-multi-level-pointer-conversion in C code (#141209)
Sometimes a project may want to enable this check only in C++, and
disable it in C, since the patterns the check warns about are quite
common and idiomatic in C, and there are no better alternatives.
    
Fixes #140659

Co-authored-by: Carlos Gálvez <carlos.galvez@zenseact.com>
2025-06-07 21:52:23 +02:00
Baranov Victor
0f03f8ab2e [clang-tidy] Add support for lambda-expression in use-trailing-return-type check (#135383)
Add support for lambda-expression in `use-trailing-return-type` check.

Added two new options:
1. `TransformFunctions` will trigger function declarations to use
trailing return type.
2. `TransformLambdas` will trigger lambda expression to use trailing
return type if it was not stated explicitly.

Fixed false positives when lambda was matched as a function in C++11
mode.

Closes https://github.com/llvm/llvm-project/issues/95711
2025-06-06 10:46:41 +03:00
flovent
a12f4f0031 [clang-tidy] Add check for assignment or comparision operators' operand in readability-math-missing-parentheses (#141345)
Fixes false negative in #141249. 

Add check for math binary operators which are operands of assignment or
comparision operators.

Closes #141249.
2025-06-05 15:18:01 +03:00
FabianWolff
317f3bdcc1 [clang-tidy] Fix formatting and add release notes entry (#141584)
Follow-up to #141092.
2025-05-27 21:52:59 +02:00
Tommy Chen
4cb25e2d37 [clang-tidy] Add avoid-pragma-once. (#140388)
#139618
2025-05-27 05:57:51 +08:00
Baranov Victor
ac0a880f4e [clang-tidy] added AllowedTypes option to readability-qualified-auto check (#136571)
Added `AllowedTypes` option to `readability-qualified-auto` check

Fixes https://github.com/llvm/llvm-project/issues/63461.
2025-05-26 13:25:35 +03:00
Baranov Victor
eda3e96b40 [clang-tidy] Fix false positives in bugprone-crtp-constructor-accessibility check (#132543)
Fix false positives in `bugprone-crtp-constructor-accessibility` check
on deleted constructors that cannot be used to construct objects, even
if they have public or protected access.

Closes https://github.com/llvm/llvm-project/issues/131737.
2025-05-26 06:25:19 +03:00
David Rivera
4675f2287c [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (#129370)
This aims to address a portion of #122480 by adding matchers on binary
operators. **This allows the detection of explicit arithmetic operations
within initializers.**
2025-05-24 20:15:36 +03:00
Daan De Meyer
c46a394df9 [clang-tidy] Add UnusedIncludes/MissingIncludes options to misc-include-cleaner (#140600)
These mimick the same options from clangd and allow using the check to
only check for unused includes or missing includes.
2025-05-21 16:41:04 +02:00
Carlos Galvez
322d0197f5 [clang-tidy] Do not flag strerror in concurrency-mt-unsafe (#140520)
The docs of the check state:

> Glibc’s list is compiled from GNU web documentation with a search for
MT-Safe tag

And strerror fulfills exactly that:
https://www.gnu.org/software/libc/manual/html_node/Error-Messages.html

> Function: char * strerror (int errnum)
> Preliminary: | MT-Safe | AS-Unsafe heap i18n | AC-Unsafe mem | See
POSIX Safety Concepts.

So concurrency-mt-unsafe should not flag it.

Fixes #140515

---------

Co-authored-by: Carlos Gálvez <carlos.galvez@zenseact.com>
Co-authored-by: EugeneZelenko <eugene.zelenko@gmail.com>
2025-05-19 21:27:37 +02:00
Balázs Kéri
d84b97ebb3 [clang-tidy] Add check bugprone-misleading-setter-of-reference (#132242) 2025-05-17 10:26:13 +02:00
Mohamed Emad
212f2456fc [include-cleaner] rename enabled flags to disable-* (#132991)
Closes #132983
2025-05-01 07:21:50 -04:00
Carlos Galvez
014ab736dc [clang-tidy] Do not pass any file when listing checks in run_clang_ti… (#137286)
…dy.py

Currently, run_clang_tidy.py does not correctly display the list of
checks picked up from the top-level .clang-tidy file. The reason for
that is that we are passing an empty string as input file.

However, that's not how we are supposed to use clang-tidy to list
checks. Per
65eccb463d,
we simply should not pass any file at all - the internal code of
clang-tidy will pass a "dummy" file if that's the case and get the
.clang-tidy file from the current working directory.

Fixes #136659

Co-authored-by: Carlos Gálvez <carlos.galvez@zenseact.com>
2025-04-29 11:13:30 +02:00
David Rivera
45411ac895 [clang-tidy] Avoid diagnosing std::array initializations for modernize-use-designated-initializers (#134774)
**Edit:**
I suggest we avoid diagnosing initializers for `std::array` type. The
fixit provided is incorrect as observed in **#133715.** The only
workaround would require C99-style array designators which don’t really
align with the purpose of this check. This would also generate extra
compiler warnings.

Fixes #133715
2025-04-28 20:12:38 +02:00
Björn Svensson
0276915a6c [clang-tidy] Fix cert-err33-c to ignore functions with same prefixes as target (#135160)
PR #82952 introduced regex matching for `CheckedFunctions` in
`UnusedReturnValueCheck` which is used by the checker `cert-err33-c`.

Add a testcase and fix false positives by adding end-of-string to target
regex's.

---------

Signed-off-by: Björn Svensson <bjorn.a.svensson@est.tech>
2025-04-11 10:08:29 +02:00
Nicolas van Kempen
15750a0ab2 [clang-tidy] Use --match-full-lines instead of --strict-whitespace in check_clang_tidy (#133756)
See Discourse post here:
https://discourse.llvm.org/t/rfc-using-match-full-lines-in-clang-tidy-tests/85553

I've added `--match-partial-fixes` to all tests that were failing,
unless I noticed the fix was quick and trivial.
2025-04-07 16:34:07 -04:00
Baranov Victor
da6e2454ff [clang-tidy] Improve bugprone-capturing-this-in-member-variable check: add support of bind functions. (#132635)
Improve `bugprone-capturing-this-in-member-variable` check:
Added support of `bind`-like functions that capture and store `this`
pointer in class member.

Closes https://github.com/llvm/llvm-project/issues/131220.
2025-04-07 09:57:55 +08:00
Carlos Galvez
6333fa5160 [clang-tidy] Fix broken HeaderFilterRegex when read from config file (#133582)
PR https://github.com/llvm/llvm-project/pull/91400 broke the usage of
HeaderFilterRegex via config file, because it is now created at a
different point in the execution and leads to a different value.

The result of that is that using HeaderFilterRegex only in the config
file does NOT work, in other words clang-tidy stops triggering warnings
on header files, thereby losing a lot of coverage.

This patch reverts the logic so that the header filter is created upon
calling the getHeaderFilter() function.

Additionally, this patch adds 2 unit tests to prevent regressions in the
future:

- One of them, "simple", tests the most basic use case with a single
top-level .clang-tidy file.

- The second one, "inheritance", demonstrates that the subfolder only
gets warnings from headers within it, and not from parent headers.

Fixes #118009
Fixes #121969
Fixes #133453

Co-authored-by: Carlos Gálvez <carlos.galvez@zenseact.com>
2025-04-03 09:28:34 +02:00
Baranov Victor
d6dcd985c0 [clang-tidy] Fix thread_local false positives in misc-use-internal-linkage check (#132573)
Based on C++ standard (see issue
https://github.com/llvm/llvm-project/issues/131679) and
[StackOverflow](https://stackoverflow.com/questions/22794382/are-c11-thread-local-variables-automatically-static)
`thread_local` variables are implicitly `static` so we should not
suggest adding `static` on a `thread_local` variables. I'd appreciate if
someone else will confirm this too because reading standard is tricky.

However, many people still use `static` and `thread_local` together:
[github
code-search](https://github.com/search?type=code&q=%22static+thread_local%22+language%3AC%2B%2B).
Maybe disabling warnings on `thread_local` should be made as a flag?
WDYT?

Closes https://github.com/llvm/llvm-project/issues/131679.
2025-03-28 21:33:58 +08:00
Congcong Cai
01e505b992 [clang-tidy][misc-const-correctness] fix fp when using const array type. (#133018)
Fixed: #132931
const array is immutable in C/C++ language design, we don't need to
check constness for it.
2025-03-28 06:21:15 +08:00
Carlos Galvez
0fb4ef40b1 Revert "[clang-tidy] Avoid processing declarations in system headers … (#132743)
…(#128150)"

This was too aggressive, and leads to problems for downstream users:
https://github.com/llvm/llvm-project/pull/128150#issuecomment-2739803409

Let's revert and reland it once we have addressed the problems.

This reverts commit e4a8969e56.

Co-authored-by: Carlos Gálvez <carlos.galvez@zenseact.com>
2025-03-24 20:47:57 +01:00
Baranov Victor
2909c420f6 [clang-tidy] modernize-use-starts-ends-with: fix false positives on find and rfind (#129564)
Also document cases with two or three arguments (matching default arguments)
this check matches.

Closes https://github.com/llvm/llvm-project/issues/129498.
2025-03-22 08:07:58 -04:00
Julian Ruess
ccfabe8380 [clang-tidy-diff] Add an option to treat warnings as errors (#128221)
This patch allows to treat warnings as erros using clang-tidy-diff.

Co-authored-by: Piotr Zegar <me@piotrzegar.pl>
2025-03-17 15:55:40 +08:00
Congcong Cai
3b1e18c2db [clang-tidy] Add new check bugprone-capture-this-by-field (#130297)
Finds lambda captures that capture the ``this`` pointer and store it as
class
members without handle the copy and move constructors and the
assignments.

Capture this in a lambda and store it as a class member is dangerous
because the
lambda can outlive the object it captures. Especially when the object is
copied
or moved, the captured ``this`` pointer will be implicitly propagated to
the
new object. Most of the time, people will believe that the captured
``this``
pointer points to the new object, which will lead to bugs.

Fixes: #120863

---------

Co-authored-by: Baranov Victor <70346889+vbvictor@users.noreply.github.com>
Co-authored-by: Baranov Victor <bar.victor.2002@gmail.com>
2025-03-17 15:11:43 +08:00
David Rivera
5e65b40f9c [clang-tidy] detect explicit casting within modernize-use-default-member-init (#129408)
This aims to fix a portion of #122480. Added some matchers to detect
explicit casting which utilize builtin types as its source expression.
these are the various forms of casting supported I thought would useful
for this check:

- C Style explicit casting
- Static explicit casting
- Functional explicit casting
2025-03-15 23:15:12 +01:00
Baranov Victor
471f034b1c [clang-tidy][NFC] clean ReleaseNotes.rst (#130626)
1. Fixed ordering to be alphabetical
2. Made lines no more than 80 characters long
3. Fixed typos
2025-03-14 23:31:50 +01:00
Congcong Cai
1a68269e28 [clang-tidy] support pointee mutation check in misc-const-correctness (#130494)
Co-authored-by: Baranov Victor <bar.victor.2002@gmail.com>
2025-03-14 21:18:43 +08:00
Carlos Galvez
e4a8969e56 [clang-tidy] Avoid processing declarations in system headers (#128150)
[clang-tidy] Avoid processing declarations in system headers

Currently, clang-tidy processes the entire TranslationUnit, including
declarations in system headers. However, the work done in system
headers is discarded at the very end when presenting results, unless
the SystemHeaders option is active.

This is a lot of wasted work, and makes clang-tidy very slow.
In comparison, clangd only processes declarations in the main file,
and it's claimed to be 10x faster than clang-tidy:

https://github.com/lljbash/clangd-tidy

To solve this problem, we can apply a similar solution done in clangd
into clang-tidy. We do this by changing the traversal scope from the
default TranslationUnitDecl, to only contain the top-level declarations
that are _not_ part of system headers. We do this in the
MatchASTConsumer class, so the logic can be reused by other tools.
This behavior is currently off by default, and only clang-tidy
enables skipping system headers. If wanted, this behavior can be
activated by other tools in follow-up patches.

I had to move MatchFinderOptions out of the MatchFinder class,
because otherwise I could not set a default value for the
"bool SkipSystemHeaders" member otherwise. The compiler error message
was "default member initializer required before the end of its
enclosing class".

Note: this behavior is not active if the user requests warnings from
system headers via the SystemHeaders option.

Note2: out of all the unit tests, only one of them fails:

readability/identifier-naming-anon-record-fields.cpp

This is because the limited traversal scope no longer includes the
"CXXRecordDecl" of the global anonymous union, see:
https://github.com/llvm/llvm-project/issues/130618

I have not found a way to make this work. For now, document the
technical debt introduced.

Note3: I have purposely decided to make this new feature enabled by
default, instead of adding a new "opt-in/opt-out" flag. Having a new
flag would mean duplicating all our tests to ensure they work in both
modes, which would be infeasible. Having it enabled by default allow
people to get the benefits immediately. Given that all unit tests pass,
the risk for regressions is low. Even if that's the case, the only
issue would be false negatives (fewer things are detected), which
are much more tolerable than false positives.

Credits: original implementation by @njames93, here:
https://reviews.llvm.org/D150126

This implementation is simpler in the sense that it does not consider
HeaderFilterRegex to filter even further. A follow-up patch could
include the functionality if wanted.

Fixes #52959

Co-authored-by: Carlos Gálvez <carlos.galvez@zenseact.com>
2025-03-14 13:16:17 +01:00
Congcong Cai
0e4ba47ca8 [clang-tidy] support to detect conversion in make_optional for bugprone-optional-value-conversion (#130417)
Add support for std::make_optional.

Fixes #119554
2025-03-12 06:12:09 +08:00
Tommy Chen
d22d14375d [clang-tidy] support different precisions (#130540)
Support float and long double versions of the math functions for
UseStdNumbersCheck.
For example, after this commit the check is able to catch `sqrtf(2)` and
`expl(1)`.

Fixes: #130325
2025-03-11 18:05:01 +01:00
David Rivera
517c6778ea [clang-tidy] Add check on constexpr & static values in modernize-use-default-member-init (#129425)
This aims to fix a portion of #122480. Simply added a check to look for
either compile time initialized variables or static stored variables.
2025-03-11 18:00:43 +01:00
Baranov Victor
75f76d482c [clang-tidy] Add bugprone-smartptr-reset-ambiguous-call check (#121291)
Add new clang-tidy check that finds potentially erroneous calls to
``reset()`` method on smart pointers when
the pointee type also has a ``reset()`` method.

It's easy to make typo and delete object because the difference between
``.`` and ``->`` is really small.

Sometimes IDE's autocomplete will change ``->`` to ``.`` automatically.
For example, developer wrote ``ptr->res`` but after pressing _Tab_ it
became ``ptr.reset()``.

Fixes #120908
2025-03-11 07:22:15 +01:00
Andrewyuan34
2a3e782f40 [clang-tidy] Fix invalid fixit from modernize-use-ranges for nullptr used with std::unique_ptr (#127162)
This PR fixes issue #124815 by correcting the handling of `nullptr` with
`std::unique_ptr` in the `modernize-use-ranges` check.

Updated the logic to suppress warnings for `nullptr` in `std::find`.
2025-03-09 20:09:59 +08:00