================
@@ -0,0 +1,75 @@
+//===----------------------------------------------------------------------===//
+//
+// 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"
+#include "clang/Basic/SourceManager.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+namespace {
+// Matches an initializer list written as ``{<single element>}``.
+AST_MATCHER(InitListExpr, isSingleElementBracedList) {
+  return Node.getLBraceLoc().isValid() && Node.getNumInits() == 1;
+}
+} // namespace
+
+void RedundantZeroInitializerCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+      initListExpr(
+          hasType(constantArrayType()), isSingleElementBracedList(),
+          hasInit(0, ignoringParenImpCasts(integerLiteral(equals(0)))),
+          // Template instantiations share the pattern's written braces,
+          // so rewriting them could break a sibling instantiation.
+          unless(isInTemplateInstantiation()),
+          optionally(hasParent(varDecl().bind("var"))))
+          .bind("init"),
+      this);
+}
+
+void RedundantZeroInitializerCheck::check(
+    const MatchFinder::MatchResult &Result) {
+  const auto *ILE = Result.Nodes.getNodeAs<InitListExpr>("init");
+
+  // In dependent template patterns the element type is unknown, so `{}` may 
not
+  // be equivalent to `{0}`.
+  if (ILE->isInstantiationDependent())
+    return;
+
+  // Skip arrays whose bound is deduced from the initializer (`T a[] = {0}`);
+  // there `{}` would deduce a different size than `{0}`.
+  if (const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var"))
+    if (const TypeSourceInfo *TSI = Var->getTypeSourceInfo())
+      if (const auto ATL = TSI->getTypeLoc().getAs<ArrayTypeLoc>())
+        if (!ATL.getSizeExpr())
+          return;
+
+  const SourceRange Range = ILE->getSourceRange();
+  if (Range.getBegin().isMacroID() || Range.getEnd().isMacroID())
+    return;
----------------
zwuis wrote:

Move these to AST matchers like `isSingleElementBracedList`.

https://github.com/llvm/llvm-project/pull/209367
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to