[clang-tools-extra] [clang-tidy] Add `modernize-redundant-zero-initializer` (PR #209367)
Yanzuo Liu via cfe-commits
cfe-commits at lists.llvm.org
Tue Jul 28 02:23:34 PDT 2026
================
@@ -0,0 +1,70 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 "RedundantZeroInitializerCheck.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/TypeLoc.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+namespace {
+// Matches an explicitly written ``{<single element>}`` list. ``isExplicit()``
+// excludes compiler-synthesized subobject lists (e.g. from brace elision in a
+// multi-dimensional array), which are not written with braces in the source.
+AST_MATCHER(InitListExpr, isSingleElementBracedList) {
+ return Node.isExplicit() && Node.getNumInits() == 1;
+}
+
+// Matches an initializer list inside a macro expansion.
+AST_MATCHER(InitListExpr, isInMacro) {
+ return Node.getBeginLoc().isMacroID() || Node.getEndLoc().isMacroID();
+}
+
+// Matches a variable whose array bound is deduced from the initializer
+// (``T a[] = ...``); replacing ``{0}`` with ``{}`` there would change the size.
+AST_MATCHER(VarDecl, hasDeducedArrayBound) {
+ const TypeSourceInfo *TSI = Node.getTypeSourceInfo();
+ if (!TSI)
+ return false;
+ const auto ATL = TSI->getTypeLoc().getAs<ArrayTypeLoc>();
+ return ATL && !ATL.getSizeExpr();
+}
+} // namespace
+
+void RedundantZeroInitializerCheck::registerMatchers(MatchFinder *Finder) {
+ Finder->addMatcher(
+ initListExpr(
+ hasType(constantArrayType()), isSingleElementBracedList(),
+ hasInit(0, ignoringParenImpCasts(integerLiteral(equals(0)))),
+ unless(isInMacro()),
+ // In a dependent pattern the element type is unknown, so `{}` may not
+ // be equivalent to `{0}`. An instantiation shares the pattern's
+ // written braces, so rewriting one could break a sibling.
+ unless(isInstantiationDependent()),
+ unless(isInTemplateInstantiation()),
+ // A deduced array bound (`T a[] = {0}`) would change size under `{}`.
+ unless(hasParent(varDecl(hasDeducedArrayBound()))))
----------------
zwuis wrote:
```cpp
varDecl(hasTypeLoc(/* custom matcher */))
```
https://github.com/llvm/llvm-project/pull/209367
More information about the cfe-commits
mailing list