clang-tools 24.0.0git
RedundantZeroInitializerCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "clang/AST/ASTContext.h"
11#include "clang/AST/Decl.h"
12#include "clang/AST/Expr.h"
13#include "clang/AST/Type.h"
14#include "clang/AST/TypeLoc.h"
15#include "clang/ASTMatchers/ASTMatchFinder.h"
16#include "clang/ASTMatchers/ASTMatchers.h"
17
18using namespace clang::ast_matchers;
19
21
22namespace {
23AST_MATCHER(InitListExpr, isSingleElementBracedList) {
24 return Node.isExplicit() && Node.getNumInits() == 1;
25}
26
27AST_MATCHER(InitListExpr, isInMacro) {
28 return Node.getBeginLoc().isMacroID() || Node.getEndLoc().isMacroID();
29}
30
31AST_MATCHER(InitListExpr, hasScalarArrayType) {
32 const ConstantArrayType *CAT =
33 Finder->getASTContext().getAsConstantArrayType(Node.getType());
34 return CAT && CAT->getElementType()->isScalarType();
35}
36
37// Matches an array type location whose bound is deduced from the initializer
38// (``T a[]``); replacing ``{0}`` with ``{}`` there would change the size.
39AST_MATCHER(ArrayTypeLoc, hasDeducedArrayBound) {
40 return Node.getSizeExpr() == nullptr;
41}
42} // namespace
43
45 Finder->addMatcher(
46 initListExpr(hasScalarArrayType(), isSingleElementBracedList(),
47 hasInit(0, ignoringParenImpCasts(integerLiteral(equals(0)))),
48 unless(isInMacro()),
49 unless(hasAncestor(cxxStdInitializerListExpr())),
50 unless(hasParent(varDecl(
51 hasTypeLoc(arrayTypeLoc(hasDeducedArrayBound()))))))
52 .bind("init"),
53 this);
54}
55
57 const MatchFinder::MatchResult &Result) {
58 const auto *ILE = Result.Nodes.getNodeAs<InitListExpr>("init");
59 const SourceRange Range = ILE->getSourceRange();
60 diag(Range.getBegin(),
61 "redundant zero initializer; replace with empty braces")
62 << FixItHint::CreateReplacement(Range, "{}");
63}
64
65} // namespace clang::tidy::readability
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
AST_MATCHER(BinaryOperator, isRelationalOperator)