Skip to content

Commit 3faba8c

Browse files
committed
[clang-tidy] Fix misc-unused-parameters on params with attrs
Don't suggest to comment-out the parameter name if the parameter has an attribute that's spelled after the parameter name. This prevents the parameter's attributes from being wrongly applied to the parameter's type.
1 parent 1a73654 commit 3faba8c

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

clang-tools-extra/clang-tidy/misc/UnusedParametersCheck.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,17 @@ bool isOverrideMethod(const FunctionDecl *Function) {
2626
return MD->size_overridden_methods() > 0 || MD->hasAttr<OverrideAttr>();
2727
return false;
2828
}
29+
30+
bool hasAttrAfterParam(const clang::SourceManager *SourceManager,
31+
const ParmVarDecl *Param) {
32+
for (const auto *Attr : Param->attrs()) {
33+
if (SourceManager->isBeforeInTranslationUnit(Param->getLocation(),
34+
Attr->getLocation())) {
35+
return true;
36+
}
37+
}
38+
return false;
39+
}
2940
} // namespace
3041

3142
void UnusedParametersCheck::registerMatchers(MatchFinder *Finder) {
@@ -189,6 +200,11 @@ void UnusedParametersCheck::check(const MatchFinder::MatchResult &Result) {
189200
if (Param->isUsed() || Param->isReferenced() || !Param->getDeclName() ||
190201
Param->hasAttr<UnusedAttr>())
191202
continue;
203+
if (hasAttrAfterParam(Result.SourceManager, Param)) {
204+
// Due to how grammar works, attributes would be wrongly applied to the
205+
// type if we remove the preceding parameter name.
206+
continue;
207+
}
192208

193209
// In non-strict mode ignore function definitions with empty bodies
194210
// (constructor initializer counts for non-empty body).

clang-tools-extra/test/clang-tidy/checkers/misc/unused-parameters.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,10 @@ void f(void (*fn)()) {;}
3333
// CHECK-MESSAGES: :[[@LINE-1]]:15: warning: parameter 'fn' is unused [misc-unused-parameters]
3434
// CHECK-FIXES: {{^}}void f(void (* /*fn*/)()) {;}{{$}}
3535

36+
int *k([[clang::lifetimebound]] int *i) {;}
37+
// CHECK-MESSAGES: :[[@LINE-1]]:38: warning: parameter 'i' is unused [misc-unused-parameters]
38+
// CHECK-FIXES: {{^}}int *k({{\[\[clang::lifetimebound\]\]}} int * /*i*/) {;}{{$}}
39+
3640
// Unchanged cases
3741
// ===============
3842
void f(int i); // Don't remove stuff in declarations
@@ -41,6 +45,7 @@ void h(int i[]);
4145
void s(int i[1]);
4246
void u(void (*fn)());
4347
void w(int i) { (void)i; } // Don't remove used parameters
48+
int *x(int *i [[clang::lifetimebound]]) { return nullptr; } // Don't reanchor attribute to the type.
4449

4550
bool useLambda(int (*fn)(int));
4651
static bool static_var = useLambda([] (int a) { return a; });

0 commit comments

Comments
 (0)