clang-tools 20.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
35static constexpr char StrictCStandardComplianceName[] =
36 "StrictCStandardCompliance";
37static constexpr bool StrictCStandardComplianceDefault = true;
38
39static constexpr char StrictCppStandardComplianceName[] =
40 "StrictCppStandardCompliance";
41static constexpr bool StrictCppStandardComplianceDefault = true;
42
43namespace {
44
45struct Designators {
46
47 Designators(const InitListExpr *InitList) : InitList(InitList) {
48 assert(InitList->isSyntacticForm());
49 };
50
51 unsigned size() { return getCached().size(); }
52
53 std::optional<llvm::StringRef> operator[](const SourceLocation &Location) {
54 const auto &Designators = getCached();
55 const auto Result = Designators.find(Location);
56 if (Result == Designators.end())
57 return {};
58 const llvm::StringRef Designator = Result->getSecond();
59 return (Designator.front() == '.' ? Designator.substr(1) : Designator)
60 .trim("\0"); // Trim NULL characters appearing on Windows in the
61 // name.
62 }
63
64private:
65 using LocationToNameMap = llvm::DenseMap<clang::SourceLocation, std::string>;
66
67 std::optional<LocationToNameMap> CachedDesignators;
68 const InitListExpr *InitList;
69
70 LocationToNameMap &getCached() {
71 return CachedDesignators ? *CachedDesignators
72 : CachedDesignators.emplace(
74 }
75};
76
77unsigned getNumberOfDesignated(const InitListExpr *SyntacticInitList) {
78 return llvm::count_if(*SyntacticInitList, [](auto *InitExpr) {
79 return isa<DesignatedInitExpr>(InitExpr);
80 });
81}
82
83AST_MATCHER(CXXRecordDecl, isAggregate) { return Node.isAggregate(); }
84
85AST_MATCHER(CXXRecordDecl, isPOD) { return Node.isPOD(); }
86
87AST_MATCHER(InitListExpr, isFullyDesignated) {
88 if (const InitListExpr *SyntacticForm =
89 Node.isSyntacticForm() ? &Node : Node.getSyntacticForm())
90 return getNumberOfDesignated(SyntacticForm) == SyntacticForm->getNumInits();
91 return true;
92}
93
94AST_MATCHER(InitListExpr, hasMoreThanOneElement) {
95 return Node.getNumInits() > 1;
96}
97
98} // namespace
99
101 StringRef Name, ClangTidyContext *Context)
102 : ClangTidyCheck(Name, Context), IgnoreSingleElementAggregates(Options.get(
105 RestrictToPODTypes(
107 IgnoreMacros(
108 Options.getLocalOrGlobal(IgnoreMacrosName, IgnoreMacrosDefault)),
109 StrictCStandardCompliance(Options.get(StrictCStandardComplianceName,
111 StrictCppStandardCompliance(
114
116 const auto HasBaseWithFields =
117 hasAnyBase(hasType(cxxRecordDecl(has(fieldDecl()))));
118 Finder->addMatcher(
119 initListExpr(
120 hasType(cxxRecordDecl(RestrictToPODTypes ? isPOD() : isAggregate(),
121 unless(HasBaseWithFields))
122 .bind("type")),
123 IgnoreSingleElementAggregates ? hasMoreThanOneElement() : anything(),
124 unless(isFullyDesignated()))
125 .bind("init"),
126 this);
127}
128
130 const MatchFinder::MatchResult &Result) {
131 const auto *InitList = Result.Nodes.getNodeAs<InitListExpr>("init");
132 const auto *Type = Result.Nodes.getNodeAs<CXXRecordDecl>("type");
133 if (!Type || !InitList)
134 return;
135 const auto *SyntacticInitList = InitList->getSyntacticForm();
136 if (!SyntacticInitList)
137 return;
138 Designators Designators{SyntacticInitList};
139 const unsigned NumberOfDesignated = getNumberOfDesignated(SyntacticInitList);
140 if (SyntacticInitList->getNumInits() - NumberOfDesignated >
141 Designators.size())
142 return;
143
144 // If the whole initializer list is un-designated, issue only one warning and
145 // a single fix-it for the whole expression.
146 if (0 == NumberOfDesignated) {
147 if (IgnoreMacros && InitList->getBeginLoc().isMacroID())
148 return;
149 {
150 DiagnosticBuilder Diag =
151 diag(InitList->getLBraceLoc(),
152 "use designated initializer list to initialize %0");
153 Diag << Type << InitList->getSourceRange();
154 for (const Stmt *InitExpr : *SyntacticInitList) {
155 const auto Designator = Designators[InitExpr->getBeginLoc()];
156 if (Designator && !Designator->empty())
157 Diag << FixItHint::CreateInsertion(InitExpr->getBeginLoc(),
158 ("." + *Designator + "=").str());
159 }
160 }
161 diag(Type->getBeginLoc(), "aggregate type is defined here",
162 DiagnosticIDs::Note);
163 return;
164 }
165
166 // In case that only a few elements are un-designated (not all as before), the
167 // check offers dedicated issues and fix-its for each of them.
168 for (const auto *InitExpr : *SyntacticInitList) {
169 if (isa<DesignatedInitExpr>(InitExpr))
170 continue;
171 if (IgnoreMacros && InitExpr->getBeginLoc().isMacroID())
172 continue;
173 const auto Designator = Designators[InitExpr->getBeginLoc()];
174 if (!Designator || Designator->empty()) {
175 // There should always be a designator. If there's unexpectedly none, we
176 // at least report a generic diagnostic.
177 diag(InitExpr->getBeginLoc(), "use designated init expression")
178 << InitExpr->getSourceRange();
179 } else {
180 diag(InitExpr->getBeginLoc(),
181 "use designated init expression to initialize field '%0'")
182 << InitExpr->getSourceRange() << *Designator
183 << FixItHint::CreateInsertion(InitExpr->getBeginLoc(),
184 ("." + *Designator + "=").str());
185 }
186 }
187}
188
192 IgnoreSingleElementAggregates);
193 Options.store(Opts, RestrictToPODTypesName, RestrictToPODTypes);
194 Options.store(Opts, IgnoreMacrosName, IgnoreMacros);
195 Options.store(Opts, StrictCStandardComplianceName, StrictCStandardCompliance);
197 StrictCppStandardCompliance);
198}
199
200} // 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 StrictCppStandardComplianceDefault
static constexpr bool IgnoreSingleElementAggregatesDefault
static constexpr char StrictCppStandardComplianceName[]
static constexpr bool StrictCStandardComplianceDefault
static constexpr char RestrictToPODTypesName[]
static constexpr char StrictCStandardComplianceName[]
llvm::DenseMap< SourceLocation, std::string > getUnwrittenDesignators(const InitListExpr *Syn)
llvm::StringMap< ClangTidyValue > OptionMap