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 | |
9 | #include "UseDesignatedInitializersCheck.h" |
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 | |
21 | using namespace clang::ast_matchers; |
22 | |
23 | namespace clang::tidy::modernize { |
24 | |
25 | static constexpr char IgnoreSingleElementAggregatesName[] = |
26 | "IgnoreSingleElementAggregates"; |
27 | static constexpr bool IgnoreSingleElementAggregatesDefault = true; |
28 | |
29 | static constexpr char RestrictToPODTypesName[] = "RestrictToPODTypes"; |
30 | static constexpr bool RestrictToPODTypesDefault = false; |
31 | |
32 | static constexpr char IgnoreMacrosName[] = "IgnoreMacros"; |
33 | static constexpr bool IgnoreMacrosDefault = true; |
34 | |
35 | static constexpr char StrictCStandardComplianceName[] = |
36 | "StrictCStandardCompliance"; |
37 | static constexpr bool StrictCStandardComplianceDefault = true; |
38 | |
39 | static constexpr char StrictCppStandardComplianceName[] = |
40 | "StrictCppStandardCompliance"; |
41 | static constexpr bool StrictCppStandardComplianceDefault = true; |
42 | |
43 | namespace { |
44 | |
45 | struct 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(Val: Location); |
56 | if (Result == Designators.end()) |
57 | return {}; |
58 | const llvm::StringRef Designator = Result->getSecond(); |
59 | return (Designator.front() == '.' ? Designator.substr(Start: 1) : Designator) |
60 | .trim(Chars: "\0"); // Trim NULL characters appearing on Windows in the |
61 | // name. |
62 | } |
63 | |
64 | private: |
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( |
73 | args: utils::getUnwrittenDesignators(Syn: InitList)); |
74 | } |
75 | }; |
76 | |
77 | unsigned getNumberOfDesignated(const InitListExpr *SyntacticInitList) { |
78 | return llvm::count_if(Range: *SyntacticInitList, P: [](auto *InitExpr) { |
79 | return isa<DesignatedInitExpr>(InitExpr); |
80 | }); |
81 | } |
82 | |
83 | AST_MATCHER(CXXRecordDecl, isAggregate) { |
84 | return Node.hasDefinition() && Node.isAggregate(); |
85 | } |
86 | |
87 | AST_MATCHER(CXXRecordDecl, isPOD) { |
88 | return Node.hasDefinition() && Node.isPOD(); |
89 | } |
90 | |
91 | AST_MATCHER(InitListExpr, isFullyDesignated) { |
92 | if (const InitListExpr *SyntacticForm = |
93 | Node.isSyntacticForm() ? &Node : Node.getSyntacticForm()) |
94 | return getNumberOfDesignated(SyntacticInitList: SyntacticForm) == SyntacticForm->getNumInits(); |
95 | return true; |
96 | } |
97 | |
98 | AST_MATCHER(InitListExpr, hasMoreThanOneElement) { |
99 | return Node.getNumInits() > 1; |
100 | } |
101 | |
102 | } // namespace |
103 | |
104 | UseDesignatedInitializersCheck::UseDesignatedInitializersCheck( |
105 | StringRef Name, ClangTidyContext *Context) |
106 | : ClangTidyCheck(Name, Context), IgnoreSingleElementAggregates(Options.get( |
107 | LocalName: IgnoreSingleElementAggregatesName, |
108 | Default: IgnoreSingleElementAggregatesDefault)), |
109 | RestrictToPODTypes( |
110 | Options.get(LocalName: RestrictToPODTypesName, Default: RestrictToPODTypesDefault)), |
111 | IgnoreMacros( |
112 | Options.getLocalOrGlobal(LocalName: IgnoreMacrosName, Default: IgnoreMacrosDefault)), |
113 | StrictCStandardCompliance(Options.get(LocalName: StrictCStandardComplianceName, |
114 | Default: StrictCStandardComplianceDefault)), |
115 | StrictCppStandardCompliance( |
116 | Options.get(LocalName: StrictCppStandardComplianceName, |
117 | Default: StrictCppStandardComplianceDefault)) {} |
118 | |
119 | void UseDesignatedInitializersCheck::registerMatchers(MatchFinder *Finder) { |
120 | const auto HasBaseWithFields = |
121 | hasAnyBase(BaseSpecMatcher: hasType(InnerMatcher: cxxRecordDecl(has(fieldDecl())))); |
122 | Finder->addMatcher( |
123 | NodeMatch: initListExpr( |
124 | hasType(InnerMatcher: cxxRecordDecl( |
125 | RestrictToPODTypes ? isPOD() : isAggregate(), |
126 | unless(anyOf(HasBaseWithFields, hasName(Name: "::std::array")))) |
127 | .bind(ID: "type")), |
128 | IgnoreSingleElementAggregates ? hasMoreThanOneElement() : anything(), |
129 | unless(isFullyDesignated())) |
130 | .bind(ID: "init"), |
131 | Action: this); |
132 | } |
133 | |
134 | void UseDesignatedInitializersCheck::check( |
135 | const MatchFinder::MatchResult &Result) { |
136 | const auto *InitList = Result.Nodes.getNodeAs<InitListExpr>(ID: "init"); |
137 | const auto *Type = Result.Nodes.getNodeAs<CXXRecordDecl>(ID: "type"); |
138 | if (!Type || !InitList) |
139 | return; |
140 | const auto *SyntacticInitList = InitList->getSyntacticForm(); |
141 | if (!SyntacticInitList) |
142 | return; |
143 | Designators Designators{SyntacticInitList}; |
144 | const unsigned NumberOfDesignated = getNumberOfDesignated(SyntacticInitList); |
145 | if (SyntacticInitList->getNumInits() - NumberOfDesignated > |
146 | Designators.size()) |
147 | return; |
148 | |
149 | // If the whole initializer list is un-designated, issue only one warning and |
150 | // a single fix-it for the whole expression. |
151 | if (0 == NumberOfDesignated) { |
152 | if (IgnoreMacros && InitList->getBeginLoc().isMacroID()) |
153 | return; |
154 | { |
155 | DiagnosticBuilder Diag = |
156 | diag(Loc: InitList->getLBraceLoc(), |
157 | Description: "use designated initializer list to initialize %0"); |
158 | Diag << Type << InitList->getSourceRange(); |
159 | for (const Stmt *InitExpr : *SyntacticInitList) { |
160 | const auto Designator = Designators[InitExpr->getBeginLoc()]; |
161 | if (Designator && !Designator->empty()) |
162 | Diag << FixItHint::CreateInsertion(InsertionLoc: InitExpr->getBeginLoc(), |
163 | Code: ("."+ *Designator + "=").str()); |
164 | } |
165 | } |
166 | diag(Type->getBeginLoc(), "aggregate type is defined here", |
167 | DiagnosticIDs::Note); |
168 | return; |
169 | } |
170 | |
171 | // In case that only a few elements are un-designated (not all as before), the |
172 | // check offers dedicated issues and fix-its for each of them. |
173 | for (const auto *InitExpr : *SyntacticInitList) { |
174 | if (isa<DesignatedInitExpr>(Val: InitExpr)) |
175 | continue; |
176 | if (IgnoreMacros && InitExpr->getBeginLoc().isMacroID()) |
177 | continue; |
178 | const auto Designator = Designators[InitExpr->getBeginLoc()]; |
179 | if (!Designator || Designator->empty()) { |
180 | // There should always be a designator. If there's unexpectedly none, we |
181 | // at least report a generic diagnostic. |
182 | diag(Loc: InitExpr->getBeginLoc(), Description: "use designated init expression") |
183 | << InitExpr->getSourceRange(); |
184 | } else { |
185 | diag(Loc: InitExpr->getBeginLoc(), |
186 | Description: "use designated init expression to initialize field '%0'") |
187 | << InitExpr->getSourceRange() << *Designator |
188 | << FixItHint::CreateInsertion(InsertionLoc: InitExpr->getBeginLoc(), |
189 | Code: ("."+ *Designator + "=").str()); |
190 | } |
191 | } |
192 | } |
193 | |
194 | void UseDesignatedInitializersCheck::storeOptions( |
195 | ClangTidyOptions::OptionMap &Opts) { |
196 | Options.store(Options&: Opts, LocalName: IgnoreSingleElementAggregatesName, |
197 | Value: IgnoreSingleElementAggregates); |
198 | Options.store(Options&: Opts, LocalName: RestrictToPODTypesName, Value: RestrictToPODTypes); |
199 | Options.store(Options&: Opts, LocalName: IgnoreMacrosName, Value: IgnoreMacros); |
200 | Options.store(Options&: Opts, LocalName: StrictCStandardComplianceName, Value: StrictCStandardCompliance); |
201 | Options.store(Options&: Opts, LocalName: StrictCppStandardComplianceName, |
202 | Value: StrictCppStandardCompliance); |
203 | } |
204 | |
205 | } // namespace clang::tidy::modernize |
206 |
Definitions
- IgnoreSingleElementAggregatesName
- IgnoreSingleElementAggregatesDefault
- RestrictToPODTypesName
- RestrictToPODTypesDefault
- IgnoreMacrosName
- IgnoreMacrosDefault
- StrictCStandardComplianceName
- StrictCStandardComplianceDefault
- StrictCppStandardComplianceName
- StrictCppStandardComplianceDefault
- Designators
- Designators
- size
- operator[]
- getCached
- getNumberOfDesignated
- isAggregate
- isPOD
- isFullyDesignated
- hasMoreThanOneElement
- UseDesignatedInitializersCheck
- registerMatchers
- check
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more