clang-tools 19.0.0git
UseDesignatedInitializersCheck.cpp
Go to the documentation of this file.
1//===--- UseDesignatedInitializersCheck.cpp - clang-tidy ------------------===//
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 "../utils/DesignatedInitializers.h"
11#include "clang/AST/APValue.h"
12#include "clang/AST/Decl.h"
13#include "clang/AST/Expr.h"
14#include "clang/AST/Stmt.h"
15#include "clang/ASTMatchers/ASTMatchFinder.h"
16#include "clang/ASTMatchers/ASTMatchers.h"
17#include "clang/ASTMatchers/ASTMatchersMacros.h"
18#include "clang/Basic/Diagnostic.h"
19#include "clang/Lex/Lexer.h"
20
21using namespace clang::ast_matchers;
22
23namespace clang::tidy::modernize {
24
25static constexpr char IgnoreSingleElementAggregatesName[] =
26 "IgnoreSingleElementAggregates";
27static constexpr bool IgnoreSingleElementAggregatesDefault = true;
28
29static constexpr char RestrictToPODTypesName[] = "RestrictToPODTypes";
30static constexpr bool RestrictToPODTypesDefault = false;
31
32static constexpr char IgnoreMacrosName[] = "IgnoreMacros";
33static constexpr bool IgnoreMacrosDefault = true;
34
35namespace {
36
37struct Designators {
38
39 Designators(const InitListExpr *InitList) : InitList(InitList) {
40 assert(InitList->isSyntacticForm());
41 };
42
43 unsigned size() { return getCached().size(); }
44
45 std::optional<llvm::StringRef> operator[](const SourceLocation &Location) {
46 const auto &Designators = getCached();
47 const auto Result = Designators.find(Location);
48 if (Result == Designators.end())
49 return {};
50 const llvm::StringRef Designator = Result->getSecond();
51 return (Designator.front() == '.' ? Designator.substr(1) : Designator)
52 .trim("\0"); // Trim NULL characters appearing on Windows in the
53 // name.
54 }
55
56private:
57 using LocationToNameMap = llvm::DenseMap<clang::SourceLocation, std::string>;
58
59 std::optional<LocationToNameMap> CachedDesignators;
60 const InitListExpr *InitList;
61
62 LocationToNameMap &getCached() {
63 return CachedDesignators ? *CachedDesignators
64 : CachedDesignators.emplace(
66 }
67};
68
69unsigned getNumberOfDesignated(const InitListExpr *SyntacticInitList) {
70 return llvm::count_if(*SyntacticInitList, [](auto *InitExpr) {
71 return isa<DesignatedInitExpr>(InitExpr);
72 });
73}
74
75AST_MATCHER(CXXRecordDecl, isAggregate) { return Node.isAggregate(); }
76
77AST_MATCHER(CXXRecordDecl, isPOD) { return Node.isPOD(); }
78
79AST_MATCHER(InitListExpr, isFullyDesignated) {
80 if (const InitListExpr *SyntacticForm =
81 Node.isSyntacticForm() ? &Node : Node.getSyntacticForm())
82 return getNumberOfDesignated(SyntacticForm) == SyntacticForm->getNumInits();
83 return true;
84}
85
86AST_MATCHER(InitListExpr, hasMoreThanOneElement) {
87 return Node.getNumInits() > 1;
88}
89
90} // namespace
91
93 StringRef Name, ClangTidyContext *Context)
94 : ClangTidyCheck(Name, Context), IgnoreSingleElementAggregates(Options.get(
97 RestrictToPODTypes(
99 IgnoreMacros(
100 Options.getLocalOrGlobal(IgnoreMacrosName, IgnoreMacrosDefault)) {}
101
103 const auto HasBaseWithFields =
104 hasAnyBase(hasType(cxxRecordDecl(has(fieldDecl()))));
105 Finder->addMatcher(
106 initListExpr(
107 hasType(cxxRecordDecl(RestrictToPODTypes ? isPOD() : isAggregate(),
108 unless(HasBaseWithFields))
109 .bind("type")),
110 IgnoreSingleElementAggregates ? hasMoreThanOneElement() : anything(),
111 unless(isFullyDesignated()))
112 .bind("init"),
113 this);
114}
115
117 const MatchFinder::MatchResult &Result) {
118 const auto *InitList = Result.Nodes.getNodeAs<InitListExpr>("init");
119 const auto *Type = Result.Nodes.getNodeAs<CXXRecordDecl>("type");
120 if (!Type || !InitList)
121 return;
122 const auto *SyntacticInitList = InitList->getSyntacticForm();
123 if (!SyntacticInitList)
124 return;
125 Designators Designators{SyntacticInitList};
126 const unsigned NumberOfDesignated = getNumberOfDesignated(SyntacticInitList);
127 if (SyntacticInitList->getNumInits() - NumberOfDesignated >
128 Designators.size())
129 return;
130
131 // If the whole initializer list is un-designated, issue only one warning and
132 // a single fix-it for the whole expression.
133 if (0 == NumberOfDesignated) {
134 if (IgnoreMacros && InitList->getBeginLoc().isMacroID())
135 return;
136 {
137 DiagnosticBuilder Diag =
138 diag(InitList->getLBraceLoc(),
139 "use designated initializer list to initialize %0");
140 Diag << Type << InitList->getSourceRange();
141 for (const Stmt *InitExpr : *SyntacticInitList) {
142 const auto Designator = Designators[InitExpr->getBeginLoc()];
143 if (Designator && !Designator->empty())
144 Diag << FixItHint::CreateInsertion(InitExpr->getBeginLoc(),
145 ("." + *Designator + "=").str());
146 }
147 }
148 diag(Type->getBeginLoc(), "aggregate type is defined here",
149 DiagnosticIDs::Note);
150 return;
151 }
152
153 // In case that only a few elements are un-designated (not all as before), the
154 // check offers dedicated issues and fix-its for each of them.
155 for (const auto *InitExpr : *SyntacticInitList) {
156 if (isa<DesignatedInitExpr>(InitExpr))
157 continue;
158 if (IgnoreMacros && InitExpr->getBeginLoc().isMacroID())
159 continue;
160 const auto Designator = Designators[InitExpr->getBeginLoc()];
161 if (!Designator || Designator->empty()) {
162 // There should always be a designator. If there's unexpectedly none, we
163 // at least report a generic diagnostic.
164 diag(InitExpr->getBeginLoc(), "use designated init expression")
165 << InitExpr->getSourceRange();
166 } else {
167 diag(InitExpr->getBeginLoc(),
168 "use designated init expression to initialize field '%0'")
169 << InitExpr->getSourceRange() << *Designator
170 << FixItHint::CreateInsertion(InitExpr->getBeginLoc(),
171 ("." + *Designator + "=").str());
172 }
173 }
174}
175
179 IgnoreSingleElementAggregates);
180 Options.store(Opts, RestrictToPODTypesName, RestrictToPODTypes);
181 Options.store(Opts, IgnoreMacrosName, IgnoreMacros);
182}
183
184} // namespace clang::tidy::modernize
llvm::SmallString< 256U > Name
NodeType Type
::clang::DynTypedNode Node
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
UseDesignatedInitializersCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
AST_MATCHER(Decl, declHasNoReturnAttr)
matches a Decl if it has a "no return" attribute of any kind
static constexpr char IgnoreMacrosName[]
static constexpr bool RestrictToPODTypesDefault
static constexpr char IgnoreSingleElementAggregatesName[]
static constexpr bool IgnoreSingleElementAggregatesDefault
static constexpr char RestrictToPODTypesName[]
llvm::DenseMap< SourceLocation, std::string > getUnwrittenDesignators(const InitListExpr *Syn)
llvm::StringMap< ClangTidyValue > OptionMap