Skip to content

Commit 7de1a17

Browse files
authored
[clang-tidy] Fix modernize-use-scoped-lock crash on malformed code (#165127)
This code: ```cpp void f() { std::lock_guard<std::mutex> dont_crash {some_nonexistant_variable}; } ``` Generates an AST like this: ```txt TranslationUnitDecl `-FunctionDecl <line:3:1, line:5:1> line:3:6 f 'void ()' `-CompoundStmt <col:10, line:5:1> `-DeclStmt <line:4:3, col:69> `-VarDecl <col:3, col:31> col:31 dont_crash 'std::lock_guard<std::mutex>' destroyed ``` Where the `VarDecl` has no initializer. The check doesn't expect this and crashes.
1 parent d63983b commit 7de1a17

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

clang-tools-extra/clang-tidy/modernize/UseScopedLockCheck.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,8 @@ void UseScopedLockCheck::diagOnSingleLock(
217217

218218
// Create Fix-its only if we can find the constructor call to properly handle
219219
// 'std::lock_guard l(m, std::adopt_lock)' case.
220-
const auto *CtorCall = dyn_cast<CXXConstructExpr>(LockGuard->getInit());
220+
const auto *CtorCall =
221+
dyn_cast_if_present<CXXConstructExpr>(LockGuard->getInit());
221222
if (!CtorCall)
222223
return;
223224

clang-tools-extra/docs/ReleaseNotes.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,11 @@ Changes in existing checks
380380
on Windows when the check was enabled with a 32-bit :program:`clang-tidy`
381381
binary.
382382

383+
- Improved :doc:`modernize-use-scoped-lock
384+
<clang-tidy/checks/modernize/use-scoped-lock>` check by fixing a crash
385+
on malformed code (common when using :program:`clang-tidy` through
386+
:program:`clangd`).
387+
383388
- Improved :doc:`modernize-use-std-format
384389
<clang-tidy/checks/modernize/use-std-format>` check to correctly match
385390
when the format string is converted to a different type by an implicit
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// RUN: %check_clang_tidy -std=c++17-or-later -expect-clang-tidy-error %s modernize-use-scoped-lock %t -- -- -isystem %clang_tidy_headers
2+
3+
#include <mutex>
4+
5+
void f() {
6+
std::lock_guard<std::mutex> dont_crash {some_nonexistant_variable};
7+
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use 'std::scoped_lock' instead of 'std::lock_guard' [modernize-use-scoped-lock]
8+
// CHECK-MESSAGES: :[[@LINE-2]]:43: error: use of undeclared identifier 'some_nonexistant_variable' [clang-diagnostic-error]
9+
}

0 commit comments

Comments
 (0)