[clang-tools-extra] Add bugprone-loop-variable-copied-then-modified clang-tidy check. (PR #157213)

Yanzuo Liu via cfe-commits cfe-commits at lists.llvm.org
Fri Sep 5 19:25:08 PDT 2025


================
@@ -0,0 +1,80 @@
+
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "LoopVariableCopiedThenModifiedCheck.h"
+#include "../utils/Matchers.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
+#include "clang/Basic/Diagnostic.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+void LoopVariableCopiedThenModifiedCheck::registerMatchers(MatchFinder *Finder) {
+  auto HasReferenceOrPointerTypeOrIsAllowed = hasType(qualType(
+      unless(hasCanonicalType(anyOf(referenceType(), pointerType())))));
+  auto IteratorReturnsValueType = cxxOperatorCallExpr(
+      hasOverloadedOperatorName("*"),
+      callee(
+          cxxMethodDecl(returns(unless(hasCanonicalType(referenceType()))))));
+  auto NotConstructedByCopy = cxxConstructExpr(
+      hasDeclaration(cxxConstructorDecl(unless(isCopyConstructor()))));
+  auto ConstructedByConversion = cxxMemberCallExpr(callee(cxxConversionDecl()));
+  auto LoopVar =
+      varDecl(HasReferenceOrPointerTypeOrIsAllowed,
+              unless(hasInitializer(expr(hasDescendant(expr(
+                  anyOf(materializeTemporaryExpr(), IteratorReturnsValueType,
+                        NotConstructedByCopy, ConstructedByConversion)))))));
+  Finder->addMatcher(
+      traverse(TK_AsIs,
+               cxxForRangeStmt(hasLoopVariable(LoopVar.bind("loopVar")))
+                   .bind("forRange")),
----------------
zwuis wrote:

`TK_AsIs` is the default traverse mode. We can write `Matcher` instead of `traverse(TK_AsIs, Matcher)`.

https://github.com/llvm/llvm-project/pull/157213


More information about the cfe-commits mailing list