If two different texts are inserted at the same offset, clang-apply-replacements prints the conflict error and discards all fixes. This patch adds support for adjusting conflict offset and keeps running to continually fix them.
https://godbolt.org/z/P938EGoxj doesn't have any fixes when I run run-clang-tidy.py to generate a YAML file with clang-tidy and fix them with clang-apply-replacements. The YAML file has two different header texts insertions at the same offset, unlike clang-tidy with '-fix', clang-apply-replacements does not adjust for this conflict.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D123924
The checker missed a check for parameter type of primary template of specialization template and this could cause build breakages.
Reviewed By: aaron.ballman, flx
Differential Revision: https://reviews.llvm.org/D116593
Adds an option SimplifyDemorganRelaxed which, when enabled, will transform negated conjunctions or disjunctions when neither operand is a negation.
Default value is `false`.
Reviewed By: LegalizeAdulthood
Differential Revision: https://reviews.llvm.org/D126162
5da7c04 introduced a regression in the NOLINT macro checking loop, replacing the
call to `getImmediateExpansionRange().getBegin()` with
`getImmediateMacroCallerLoc()`, which has similar but subtly different
behaviour.
The consequence is that NOLINTs cannot suppress diagnostics when they are
attached to a token that came from a macro **argument**, rather than elsewhere
in the macro expansion.
Revert to pre-patch behaviour and add test cases to cover this issue.
Differential Revision: https://reviews.llvm.org/D126138
When looking for whether or not a check provides fixits, the script
examines the implementation of the check. Some checks are not
implemented in source files that correspond one-to-one with the check
name, e.g. cert-dcl21-cpp. So if we can't find the check implementation
directly from the check name, open up the corresponding module file and
look for the class name that is registered with the check. Then consult
the file corresponding to the class name.
Some checks are derived from a base class that implements fixits. So if
we can't find fixits in the implementation file for a check, scrape out
the name of it's base class. If it's not ClangTidyCheck, then consult
the base class implementation to look for fixit support.
Differential Revision: https://reviews.llvm.org/D126134Fixes#55630
The end-user has no way of 'fixing' bugs in the system library anyway.
Let's suppress these as well.
Reviewed By: LegalizeAdulthood
Differential Revision: https://reviews.llvm.org/D125770
Unfortunately, we must restrict the checker to warn for deprecated headers
only if the header is included directly from a c++ source file.
For header files, we cannot know if the project has a C source file
that also directly/indirectly includes the offending header file
otherwise. Thus, it's better to be on the safe side and suppress those
reports.
One can opt-in the old behavior, emitting diagnostics into header files,
if one explicitly sets the WarnIntoHeaders=true, in which case nothing
will be changed.
Reviewed By: LegalizeAdulthood
Differential Revision: https://reviews.llvm.org/D125769
This partially reverts commit e8cae48702.
Changes since that commit:
- Use `SourceManager::isBeforeInTranslationUnit` instead of the fancy
decomposed decl logarithmic search.
- Add a test for including a system header containing a deprecated
include.
- Add `REQUIRES: system-linux` clause to the test.
Reviewed By: LegalizeAdulthood, whisperity
Differential Revision: https://reviews.llvm.org/D125209
Reimplement the matching logic using Visitors instead of matchers.
Benchmarks from running the check over SemaCodeComplete.cpp
Before 0.20s, After 0.04s
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D125026
Add a recursive descent parser to match macro expansion tokens against
fully formed valid expressions of integral literals. Partial
expressions will not be matched -- they can't be valid initializing
expressions for an enum.
Differential Revision: https://reviews.llvm.org/D124500Fixes#55055
The check should not report includes wrapped by `extern "C" { ... }` blocks,
such as:
```lang=C++
#ifdef __cplusplus
extern "C" {
#endif
#include "assert.h"
#ifdef __cplusplus
}
#endif
```
This pattern comes up sometimes in header files designed to be consumed
by both C and C++ source files.
The check now reports false reports when the header file is consumed by
a C++ translation unit.
In this change, I'm not emitting the reports immediately from the
`PPCallback`, rather aggregating them for further processing.
After all preprocessing is done, the matcher will be called on the
`TranslationUnitDecl`, ensuring that the check callback is called only
once.
Within that callback, I'm recursively visiting each decls, looking for
`LinkageSpecDecls` which represent the `extern "C"` specifier.
After this, I'm dropping all the reports coming from inside of it.
After the visitation is done, I'm emitting the reports I'm left with.
For performance reasons, I'm sorting the `IncludeMarkers` by their
corresponding locations.
This makes the scan `O(log(N)` when looking up the `IncludeMarkers`
affected by the given `extern "C"` block. For this, I'm using
`lower_bound()` and `upper_bound()`.
Reviewed By: whisperity
Differential Revision: https://reviews.llvm.org/D125209
Fixes the `FIXME:` related to adding `forEachTemplateArgument` to the
core AST Matchers library.
Reviewed By: aaron.ballman
Differential Revision: http://reviews.llvm.org/D125383
There's many instances in clang tidy checks where owning strings are used when we already have a stable string from the options, so using a StringRef makes much more sense.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D124341
This check verifies the safety of access to `std::optional` and related
types (including `absl::optional`). It is based on a corresponding Clang
Dataflow Analysis, which does most of the work. This check merely runs it and
converts its findings into diagnostics.
Differential Revision: https://reviews.llvm.org/D121120
This method won't add a check if it isn't supported in the Contexts current LanguageOptions.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D124320
Currently it rejects "// FOO_BAR_H" as an endif comment due to the extra space.
A user complained that this is too picky, which seems fair enough.
Differential Revision: https://reviews.llvm.org/D124955
Messages generated by Transformer rules may have `%` in them, which
needs to be escaped before being passed to `diag`, which interprets them
specially (and crashes if they are misused).
Differential Revision: https://reviews.llvm.org/D124952
Support for loading shared objects as plugins into clang-tidy was added
in http://reviews.llvm.org/D111100. Unfortunately, the utility scripts
`clang-tidy-diff.py` and `run-clang-tidy.py` did not receive
corresponding arguments to forward such plugins to clang-tidy.
This diff adds a `-load=plugin` option to both scripts.
Differential Revision: http://reviews.llvm.org/D12306
Reviewed By: aaron.ballman
If a macro is used in the expansion of another macro, that can cause
a compile error if the macro is replaced with an enum. Token-pasting is
an example where converting a macro defined as an integral constant can
cause code to no longer compile.
This change causes such macros to be skipped from the conversion
process in order to prevent fixits from creating code that no longer
compiles.
A subsequent enhancement will examine macro usage in more detail to
allow more cases to be handled without breaking code.
Differential Revision: https://reviews.llvm.org/D124316Fixes#54948
`find_compilation_database` checked only for "/" as exit point, but on Windows, this root is impossible.
Fixes#53642
Authored By: Febbe
Reviewed By: JonasToth
Differential Revision: https://reviews.llvm.org/D119481
Modernize-macro-to-enum shouldn't try to convert macros to enums
when they are defined inside a declaration or definition, only
when the macros are defined at the top level. Since preprocessing
is disconnected from AST traversal, match nodes in the AST and then
invalidate source ranges spanning AST nodes before issuing diagnostics.
ClangTidyCheck::onEndOfTranslationUnit is called before
PPCallbacks::EndOfMainFile, so defer final diagnostics to the
PPCallbacks implementation.
Differential Revision: https://reviews.llvm.org/D124066Fixes#54883
The routine that facilitated symbols to be explicitly allowed asked
the name of the called function, which resulted in a crash when the
check was accidentally run on non-trivial C++ code.
Differential Revision: http://reviews.llvm.org/D123992
Reviewed By: aaron.ballman
When a macro is undef'ed or used in a preprocessor conditional
expression, we need to remember that macro should it later be
defined in the file to an integral value. We need to exclude
such macro names from being turned into an enum.
Maintain a blacklist of identifiers that we've seen in an
undef or conditional preprocessor directive. When the file is
done processing, remove all the blacklisted identifiers from
conversion to an enum.
Differential Revision: https://reviews.llvm.org/D123889Fixes#54842
Adds a flag to `ClangTidyContext` that is used to indicate to checks that fixes will only be applied one at a time.
This is to indicate to checks that each fix emitted should not depend on any other fixes emitted across the translation unit.
I've currently implemented the `IncludeInserter`, `LoopConvertCheck` and `PreferMemberInitializerCheck` to use these support these modes.
Reasoning behind this is in use cases like `clangd` it's only possible to apply one fix at a time.
For include inserter checks, the include is only added once for the first diagnostic that requires it, this will result in subsequent fixes not having the included needed.
A similar issue is seen in the `PreferMemberInitializerCheck` where the `:` will only be added for the first member that needs fixing.
Fixes emitted in `StandaloneDiagsMode` will likely result in malformed code if they are applied all together, conversely fixes currently emitted may result in malformed code if they are applied one at a time.
For this reason invoking `clang-tidy` from the binary will always with `StandaloneDiagsMode` disabled, However using it as a library its possible to select the mode you wish to use, `clangd` always selects `StandaloneDiagsMode`.
This is an example of the current behaviour failing
```lang=c++
struct Foo {
int A, B;
Foo(int D, int E) {
A = D;
B = E; // Fix Here
}
};
```
Incorrectly transformed to:
```lang=c++
struct Foo {
int A, B;
Foo(int D, int E), B(E) {
A = D;
// Fix Here
}
};
```
In `StandaloneDiagsMode`, it gets transformed to:
```lang=c++
struct Foo {
int A, B;
Foo(int D, int E) : B(E) {
A = D;
// Fix Here
}
};
```
Reviewed By: sammccall
Differential Revision: https://reviews.llvm.org/D97121
Report use of `std::vector<const T>` (and similar containers of const
elements). These are now allowed in standard C++ due to undefined
`std::allocator<const T>`. They do not compile with libstdc++ or MSVC.
Future libc++ will remove the extension (D120996).
See docs/clang-tidy/checks/portability-std-allocator-const.rst for detail.
I have attempted clean-up in a large code base. Here are some statistics:
* 98% are related to the container `std::vector`, among `deque/forward_list/list/multiset/queue/set/stack/vector`.
* 24% are related to `std::vector<const std::string>`.
* Both `std::vector<const absl::string_view>` and `std::vector<const int>` contribute 2%. The other contributors spread over various class types.
The check can be useful to other large code bases and may serve as an example
for future libc++ strictness improvement.
Note: on MSVC where -fdelayed-template-parsing is the default, the check cannot
catch cases in uninstantiated templates.
Reviewed By: sammccall
Differential Revision: https://reviews.llvm.org/D123655
This patch changes type of the `File` parameter in `PPCallbacks::InclusionDirective()` from `const FileEntry *` to `Optional<FileEntryRef>`.
With the API change in place, this patch then removes some uses of the deprecated `FileEntry::getName()` (e.g. in `DependencyGraph.cpp` and `ModuleDependencyCollector.cpp`).
Reviewed By: dexonsmith, bnbarham
Differential Revision: https://reviews.llvm.org/D123574
Report use of ``std::vector<const T>`` (and similar containers of const
elements). These are now allowed in standard C++ due to undefined
``std::allocator<const T>``. They do not compile with libstdc++ or MSVC.
Future libc++ will remove the extension (D120996).
See docs/clang-tidy/checks/portability-std-allocator-const.rst for detail.
I have attempted clean-up in a large code base. Here are some statistics:
* 98% are related to the container `std::vector`, among `deque/forward_list/list/multiset/queue/set/stack/vector`.
* 24% are related to `std::vector<const std::string>`.
* Both `std::vector<const absl::string_view>` and `std::vector<const int>` contribute 2%. The other contributors spread over various class types.
The check can be useful to other large code bases and may serve as an example
for future libc++ strictness improvement.
Reviewed By: sammccall
Differential Revision: https://reviews.llvm.org/D123655
When scanning a macro expansion to examine it as a candidate enum,
first strip off arbitrary matching parentheses from the outside in,
then examine what remains to see if it is Lit, +Lit, -Lit or ~Lit.
If not, reject it as a possible enum candidate.
Differential Revision: https://reviews.llvm.org/D123479Fixes#54843
When a "keyword" token like __restrict was present in a macro condition,
modernize-macro-to-enum would assert in non-release builds. However,
even for a "keyword" token, calling getIdentifierInfo()->getName() would
retrieve the text of the token, which is what we want. Our intention is
to scan names that appear in conditional expressions in potential enum
clusters and invalidate those clusters if they contain the name.
Also, guard against "raw identifiers" appearing as potential enums.
This shouldn't happen, but it doesn't hurt to generalize the code.
Differential Revision: https://reviews.llvm.org/D123349Fixes#54775
Another change of the code design.
Code simplified again, now there is a single place to check
a handler function and less functions for bug report emitting.
More details are added to the bug report messages.
Reviewed By: whisperity
Differential Revision: https://reviews.llvm.org/D118370
The new -config-file option introduced by 9e1f4f1 was accidentally
referenced as args.config_path on the python side. This patch renames
args.config_path to args.config_file.
To avoid confusion with python file objects, the input argument for
get_tidy_invocation has been renamed from config_path to
config_file_path.
See GitHub issue #54728 for a discussion.
[buildbot issues fixed]
This check performs basic analysis of macros and replaces them
with an anonymous unscoped enum. Using an unscoped anonymous enum
ensures that everywhere the macro token was used previously, the
enumerator name may be safely used.
Potential macros for replacement must meet the following constraints:
- Macros must expand only to integral literal tokens. The unary
operators plus, minus and tilde are recognized to allow for positive,
negative and bitwise negated integers.
- Macros must be defined on sequential source file lines, or with
only comment lines in between macro definitions.
- Macros must all be defined in the same source file.
- Macros must not be defined within a conditional compilation block.
- Macros must not be defined adjacent to other preprocessor directives.
- Macros must not be used in preprocessor conditions
Each cluster of macros meeting the above constraints is presumed to
be a set of values suitable for replacement by an anonymous enum.
From there, a developer can give the anonymous enum a name and
continue refactoring to a scoped enum if desired. Comments on the
same line as a macro definition or between subsequent macro definitions
are preserved in the output. No formatting is assumed in the provided
replacements.
The check cppcoreguidelines-macro-to-enum is an alias for this check.
Fixes#27408
Differential Revision: https://reviews.llvm.org/D117522
This check performs basic analysis of macros and replaces them
with an anonymous unscoped enum. Using an unscoped anonymous enum
ensures that everywhere the macro token was used previously, the
enumerator name may be safely used.
Potential macros for replacement must meet the following constraints:
- Macros must expand only to integral literal tokens. The unary
operators plus, minus and tilde are recognized to allow for positive,
negative and bitwise negated integers.
- Macros must be defined on sequential source file lines, or with
only comment lines in between macro definitions.
- Macros must all be defined in the same source file.
- Macros must not be defined within a conditional compilation block.
- Macros must not be defined adjacent to other preprocessor directives.
- Macros must not be used in preprocessor conditions
Each cluster of macros meeting the above constraints is presumed to
be a set of values suitable for replacement by an anonymous enum.
From there, a developer can give the anonymous enum a name and
continue refactoring to a scoped enum if desired. Comments on the
same line as a macro definition or between subsequent macro definitions
are preserved in the output. No formatting is assumed in the provided
replacements.
The check cppcoreguidelines-macro-to-enum is an alias for this check.
Fixes#27408
Differential Revision: https://reviews.llvm.org/D117522
Change RewriteRule from holding an `Explanation` to being able to generate
arbitrary metadata. Where TransformerClangTidyCheck was interested in a string
description for the diagnostic, other tools may be interested in richer metadata
at a higher level of abstraction than at the edit level (which is currently
available as ASTEdit::Metadata).
Reviewed By: ymandel
Differential Revision: https://reviews.llvm.org/D120360
Change RewriteRule from holding an `Explanation` to being able to generate
arbitrary metadata. Where TransformerClangTidyCheck was interested in a string
description for the diagnostic, other tools may be interested in richer metadata
at a higher level of abstraction than at the edit level (which is currently
available as ASTEdit::Metadata).
Reviewed By: ymandel
Differential Revision: https://reviews.llvm.org/D120360
Link to the GitHub Issue: https://github.com/llvm/llvm-project/issues/53745
Added config_path variable within the python script which makes the
required call to the clang-tidy binary with --config-file option.
If the config_path is None then config will be used. No error is raised
if both are given but silently chooses config_path over config
The checker removes `const`s that are superfluos and badly affect
readability. `decltype(auto)`/`decltype(expr)` are often const-qualified, but
have no effect on readability and usually can't stop being const-qualified
without significant code change.
Fixes https://github.com/llvm/llvm-project/issues/52890
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D119470
This changes the clang-tidy script to discover binaries you've built
locally without having to pass them.
Differential Revision: https://reviews.llvm.org/D100692
It was probably a copy-paste mistake.
The check was added as `cert-dcl58-cpp`, so the doc should point there.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D121373
The docs URL was dangling, and the docs suggested that it has no fixits,
but it actually had.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D121372
It cannot match a `pure virtual function`. This patch fixes this behavior.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D116439
As originally reported by @steakhal in
http://github.com/llvm/llvm-project/issues/54074, the name extraction logic of
`readability-suspicious-call-argument` crashes if the argument passed to a
function was a function call to a non-trivially named entity (e.g. an operator).
Fixed this crash case by ignoring such constructs and considering them as having
no name.
Reviewed By: aaron.ballman, steakhal
Differential Revision: http://reviews.llvm.org/D120555
The checker missed a check for a case when the parameter is referenced by an lvalue and this could cause build breakages.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D117090
The tristate is a little redundant as we can determine if the item was already in the cache based on the return from try_emplace.
Reviewed By: salman-javed-nz
Differential Revision: https://reviews.llvm.org/D120196
D90110 modified the behavior of `run-clang-tidy` to always pass the
`--use-color` option to clang-tidy, which enabled colored diagnostics
output regardless of TTY status or .clang-tidy settings. This left the
user with no option to disable the colored output.
This presents an issue when trying to parse the output of run-clang-tidy
programmaticall, as the output is polluted with ANSI escape characters.
This PR fixes this issue in two ways:
1. It restores the default behavior of `run-clang-tidy` to let
`clang-tidy` decide whether to color output. This allows the user to
configure color via the `UseColor` option in a .clang-tidy file.
2. It adds mutually exclusive, optional `-use-color` and `-no-use-color`
argument flags that let the user explicitly set the color option via
the invocation.
After this change the default behavior of `run-clang-tidy` when no
.clang-tidy file is available is now to show no color, presumably
because `clang-tidy` detects that the output is being piped and defaults
to not showing colored output. This seems like an acceptable tradeoff
to respect .clang-tidy configurations, as users can still use the
`-use-color` option to explicitly enable color.
Fixes#49441 (50097 in Bugzilla)
Reviewed By: njames93
Differential Revision: https://reviews.llvm.org/D119562
This option allows callers to disable the warning from
https://clang.llvm.org/extra/clang-tidy/checks/performance-move-const-arg.html
that would warn on the following
```
void f(const string &s);
string s;
f(std::move(s)); // ALLOWED if performance-move-const-arg.CheckMoveToConstRef=false
```
The reason people might want to disable this check, is because it allows
callers to use `std::move()` or not based on local reasoning about the
argument, and without having to care about how the function `f` accepts
the argument. Indeed, `f` might accept the argument by const-ref today,
but change to by-value tomorrow, and if the caller had moved the
argument that they were finished with, the code would work as
efficiently as possible regardless of how `f` accepted the parameter.
Reviewed By: ymandel
Differential Revision: https://reviews.llvm.org/D119370
Implement P2128R6 in C++23 mode.
Unlike GCC's implementation, this doesn't try to recover when a user
meant to use a comma expression.
Because the syntax changes meaning in C++23, the patch is *NOT*
implemented as an extension. Instead, declaring an array with not
exactly 1 parameter is an error in older languages modes. There is an
off-by-default extension warning in C++23 mode.
Unlike the standard, we supports default arguments;
Ie, we assume, based on conversations in WG21, that the proposed
resolution to CWG2507 will be accepted.
We allow arrays OpenMP sections and C++23 multidimensional array to
coexist:
[a , b] multi dimensional array
[a : b] open mp section
[a, b: c] // error
The rest of the patch is relatively straight forward: we take care to
support an arbitrary number of arguments everywhere.
The test invocation at the start of run-clang-tidy.py (line 257) prints
all enabled checks - meaning either the default set or anything
configured via the -checks option. If any checks were (un-)configured
via the -config option, these are not printed. This is confusing to the
user, since the list of checks that are printed may be different from
the list of checks that are used by the non-testing calls to clang-tidy,
where the -config option is passed correctly.
This patch adds the -config option to the test invocation of clang-tidy
at the start of the script. This means that checks (un-)configured via
the -config option (rather than the -checks option) are applied
correctly, when printing the list of enabled checks.
Display notes for a possible call chain if an unsafe function is found to be
called (maybe indirectly) from a signal handler.
The call chain displayed this way includes probably not the first calls of
the functions, but it is a valid possible (in non path-sensitive way) one.
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D118224
This reverts commit 36892727e4 which
breaks the build when LLVM_INSTALL_TOOLCHAIN_ONLY is enabled with:
CMake Error at cmake/modules/AddLLVM.cmake:683 (add_dependencies):
The dependency target "clang-tidy-headers" of target "CTTestTidyModule"
does not exist.
Inside a switch the caseStmt() and defaultStmt() have a nested statement
associated with them. Similarly, labelStmt() has a nested statement.
These statements were being missed when looking for a compound-if of the
form "if (x) return true; return false;" when the if is nested under one
of these labelling constructs.
Enhance the matchers to look for these nested statements using some
private matcher hasSubstatement() traversal matcher on case, default
and label statements. Add the private matcher hasSubstatementSequence()
to match the compound "if (x) return true; return false;" pattern.
- Add unit tests for private matchers and corresponding test
infrastructure
- Add corresponding test file readability-simplify-bool-expr-case.cpp.
- Fix variable name copy/paste error in readability-simplify-bool-expr.cpp.
- Drop the asserts, which were used only for debugging matchers.
- Run clang-format on the whole check.
- Move local functions out of anonymous namespace and declare state, per
LLVM style guide
- Declare labels constexpr
- Declare visitor arguments as pointer to const
- Drop braces around simple control statements per LLVM style guide
- Prefer explicit arguments over default arguments to methods
Differential Revision: https://reviews.llvm.org/D56303Fixes#27078
This commit checks if a function is marked with the naked attribute
and, if it is, will silence the emission of any unused-parameter
warning.
Inside a naked function only the usage of basic ASM instructions is
expected. In this context the parameters can actually be used by
fetching them according to the underlying ABI. Since parameters might
be used through ASM instructions, the linter and the compiler will have
a hard time understanding if one of those is unused or not, therefore
no unused-parameter warning should ever be triggered whenever a
function is marked naked.