clang-tools 23.0.0git
ElseAfterReturnCheck.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/ASTMatchers/ASTMatchFinder.h"
12#include "clang/Lex/Lexer.h"
13#include "clang/Lex/Preprocessor.h"
14#include "clang/Tooling/FixIt.h"
15#include "llvm/ADT/SmallVector.h"
16
17using namespace clang::ast_matchers;
18
20
21namespace {
22
23class PPConditionalCollector : public PPCallbacks {
24public:
25 PPConditionalCollector(
27 const SourceManager &SM)
28 : Collections(Collections), SM(SM) {}
29 void Endif(SourceLocation Loc, SourceLocation IfLoc) override {
30 if (!SM.isWrittenInSameFile(Loc, IfLoc))
31 return;
32 SmallVectorImpl<SourceRange> &Collection = Collections[SM.getFileID(Loc)];
33 assert(Collection.empty() || Collection.back().getEnd() < Loc);
34 Collection.emplace_back(IfLoc, Loc);
35 }
36
37private:
39 const SourceManager &SM;
40};
41
42AST_MATCHER_P(Stmt, stripLabelLikeStatements,
43 ast_matchers::internal::Matcher<Stmt>, InnerMatcher) {
44 const Stmt *S = Node.stripLabelLikeStatements();
45 return InnerMatcher.matches(*S, Finder, Builder);
46}
47
48AST_MATCHER_P(Stmt, hasFinalStmt, ast_matchers::internal::Matcher<Stmt>,
49 InnerMatcher) {
50 for (const Stmt *S = &Node;;) {
51 S = S->stripLabelLikeStatements();
52 if (const auto *Compound = dyn_cast<CompoundStmt>(S)) {
53 if (Compound->body_empty())
54 return false;
55 S = Compound->body_back();
56 } else {
57 return InnerMatcher.matches(*S, Finder, Builder);
58 }
59 }
60}
61
62} // namespace
63
64static constexpr char InterruptingStr[] = "interrupting";
65static constexpr char WarningMessage[] = "do not use 'else' after %0";
66static constexpr char WarnOnUnfixableStr[] = "WarnOnUnfixable";
67static constexpr char WarnOnConditionVariablesStr[] =
68 "WarnOnConditionVariables";
69
70static const DeclRefExpr *findUsage(const Stmt *Node, const Decl *D) {
71 if (!Node)
72 return nullptr;
73 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Node)) {
74 if (DeclRef->getDecl() == D)
75 return DeclRef;
76 } else {
77 for (const Stmt *ChildNode : Node->children())
78 if (const DeclRefExpr *Result = findUsage(ChildNode, D))
79 return Result;
80 }
81 return nullptr;
82}
83
84static const DeclRefExpr *findUsageRange(const Stmt *Node,
85 DeclStmt::decl_const_range Decls) {
86 if (!Node)
87 return nullptr;
88 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Node)) {
89 if (llvm::is_contained(Decls, DeclRef->getDecl()))
90 return DeclRef;
91 } else {
92 for (const Stmt *ChildNode : Node->children())
93 if (const DeclRefExpr *Result = findUsageRange(ChildNode, Decls))
94 return Result;
95 }
96 return nullptr;
97}
98
99static const DeclRefExpr *checkInitDeclUsageInElse(const IfStmt *If) {
100 const auto *InitDeclStmt = dyn_cast_or_null<DeclStmt>(If->getInit());
101 if (!InitDeclStmt)
102 return nullptr;
103 if (InitDeclStmt->isSingleDecl()) {
104 const Decl *InitDecl = InitDeclStmt->getSingleDecl();
105 assert(isa<VarDecl>(InitDecl) && "SingleDecl must be a VarDecl");
106 return findUsage(If->getElse(), InitDecl);
107 }
108 return findUsageRange(If->getElse(), InitDeclStmt->decls());
109}
110
111static const DeclRefExpr *checkConditionVarUsageInElse(const IfStmt *If) {
112 if (const VarDecl *CondVar = If->getConditionVariable())
113 return findUsage(If->getElse(), CondVar);
114 return nullptr;
115}
116
117static bool containsDeclInScope(const Stmt *Node) {
118 if (isa<DeclStmt>(Node))
119 return true;
120 if (const auto *Compound = dyn_cast<CompoundStmt>(Node))
121 return llvm::any_of(Compound->body(), [](const Stmt *SubNode) {
122 return isa<DeclStmt>(SubNode);
123 });
124 return false;
125}
126
127static void removeElseAndBrackets(DiagnosticBuilder &Diag, ASTContext &Context,
128 const Stmt *Else, SourceLocation ElseLoc) {
129 auto Remap = [&](SourceLocation Loc) {
130 return Context.getSourceManager().getExpansionLoc(Loc);
131 };
132
133 if (const auto *CS = dyn_cast<CompoundStmt>(Else)) {
134 Diag << tooling::fixit::createRemoval(ElseLoc)
135 << tooling::fixit::createRemoval(Remap(CS->getLBracLoc()))
136 << tooling::fixit::createRemoval(Remap(CS->getRBracLoc()));
137 } else {
138 Diag << tooling::fixit::createRemoval(Remap(ElseLoc));
139 }
140}
141
143 ClangTidyContext *Context)
144 : ClangTidyCheck(Name, Context),
145 WarnOnUnfixable(Options.get(WarnOnUnfixableStr, true)),
146 WarnOnConditionVariables(Options.get(WarnOnConditionVariablesStr, true)) {
147}
148
150 Options.store(Opts, WarnOnUnfixableStr, WarnOnUnfixable);
151 Options.store(Opts, WarnOnConditionVariablesStr, WarnOnConditionVariables);
152}
153
154void ElseAfterReturnCheck::registerPPCallbacks(const SourceManager &SM,
155 Preprocessor *PP,
156 Preprocessor *ModuleExpanderPP) {
157 PP->addPPCallbacks(
158 std::make_unique<PPConditionalCollector>(this->PPConditionals, SM));
159}
160
161void ElseAfterReturnCheck::registerMatchers(MatchFinder *Finder) {
162 const auto InterruptsControlFlow =
163 stmt(anyOf(returnStmt(), continueStmt(), breakStmt(), cxxThrowExpr(),
164 callExpr(callee(functionDecl(isNoReturn())))));
165
166 const auto IfWithInterruptingThenElse =
167 ifStmt(unless(isConstexpr()), unless(isConsteval()),
168 hasThen(hasFinalStmt(InterruptsControlFlow.bind(InterruptingStr))),
169 hasElse(stmt().bind("else")))
170 .bind("if");
171
172 Finder->addMatcher(compoundStmt(forEach(stripLabelLikeStatements(
173 IfWithInterruptingThenElse)))
174 .bind("cs"),
175 this);
176}
177
179 const ElseAfterReturnCheck::ConditionalBranchMap &ConditionalBranchMap,
180 const SourceManager &SM, SourceLocation StartLoc, SourceLocation EndLoc) {
181 const SourceLocation ExpandedStartLoc = SM.getExpansionLoc(StartLoc);
182 const SourceLocation ExpandedEndLoc = SM.getExpansionLoc(EndLoc);
183 if (!SM.isWrittenInSameFile(ExpandedStartLoc, ExpandedEndLoc))
184 return false;
185
186 // StartLoc and EndLoc expand to the same macro.
187 if (ExpandedStartLoc == ExpandedEndLoc)
188 return false;
189
190 assert(ExpandedStartLoc < ExpandedEndLoc);
191
192 auto Iter = ConditionalBranchMap.find(SM.getFileID(ExpandedEndLoc));
193
194 if (Iter == ConditionalBranchMap.end() || Iter->getSecond().empty())
195 return false;
196
197 const SmallVectorImpl<SourceRange> &ConditionalBranches = Iter->getSecond();
198
199 assert(llvm::is_sorted(ConditionalBranches,
200 [](const SourceRange &LHS, const SourceRange &RHS) {
201 return LHS.getEnd() < RHS.getEnd();
202 }));
203
204 // First conditional block that ends after ExpandedStartLoc.
205 const auto *Begin =
206 llvm::lower_bound(ConditionalBranches, ExpandedStartLoc,
207 [](const SourceRange &LHS, const SourceLocation &RHS) {
208 return LHS.getEnd() < RHS;
209 });
210 const auto *End = ConditionalBranches.end();
211 for (; Begin != End && Begin->getEnd() < ExpandedEndLoc; ++Begin)
212 if (Begin->getBegin() < ExpandedStartLoc)
213 return true;
214 return false;
215}
216
217static StringRef getControlFlowString(const Stmt &Stmt) {
218 if (isa<ReturnStmt>(Stmt))
219 return "'return'";
220 if (isa<ContinueStmt>(Stmt))
221 return "'continue'";
222 if (isa<BreakStmt>(Stmt))
223 return "'break'";
224 if (isa<CXXThrowExpr>(Stmt))
225 return "'throw'";
226 if (isa<CallExpr>(Stmt))
227 return "calling a function that doesn't return";
228 llvm_unreachable("Unknown control flow interrupter");
229}
230
231void ElseAfterReturnCheck::check(const MatchFinder::MatchResult &Result) {
232 const auto *If = Result.Nodes.getNodeAs<IfStmt>("if");
233 const auto *Else = Result.Nodes.getNodeAs<Stmt>("else");
234 const auto *OuterScope = Result.Nodes.getNodeAs<CompoundStmt>("cs");
235 const auto *Interrupt = Result.Nodes.getNodeAs<Stmt>(InterruptingStr);
236 const SourceLocation ElseLoc = If->getElseLoc();
237
239 PPConditionals, *Result.SourceManager, Interrupt->getBeginLoc(),
240 ElseLoc))
241 return;
242
243 const bool IsLastInScope = OuterScope->body_back() == If;
244 const StringRef ControlFlowInterrupter = getControlFlowString(*Interrupt);
245
246 if (!IsLastInScope && containsDeclInScope(Else)) {
247 if (WarnOnUnfixable) {
248 // Warn, but don't attempt an autofix.
249 diag(ElseLoc, WarningMessage) << ControlFlowInterrupter;
250 }
251 return;
252 }
253
254 if (checkConditionVarUsageInElse(If) != nullptr) {
255 if (!WarnOnConditionVariables)
256 return;
257 if (IsLastInScope) {
258 // If the if statement is the last statement of its enclosing statements
259 // scope, we can pull the decl out of the if statement.
260 DiagnosticBuilder Diag = diag(ElseLoc, WarningMessage)
261 << ControlFlowInterrupter
262 << SourceRange(ElseLoc);
263 if (checkInitDeclUsageInElse(If) != nullptr) {
264 Diag << tooling::fixit::createReplacement(
265 SourceRange(If->getIfLoc()),
266 (tooling::fixit::getText(*If->getInit(), *Result.Context) +
267 StringRef("\n"))
268 .str())
269 << tooling::fixit::createRemoval(If->getInit()->getSourceRange());
270 }
271 const DeclStmt *VDeclStmt = If->getConditionVariableDeclStmt();
272 const VarDecl *VDecl = If->getConditionVariable();
273 const std::string Repl =
274 (tooling::fixit::getText(*VDeclStmt, *Result.Context) +
275 StringRef(";\n") +
276 tooling::fixit::getText(If->getIfLoc(), *Result.Context))
277 .str();
278 Diag << tooling::fixit::createReplacement(SourceRange(If->getIfLoc()),
279 Repl)
280 << tooling::fixit::createReplacement(VDeclStmt->getSourceRange(),
281 VDecl->getName());
282 removeElseAndBrackets(Diag, *Result.Context, Else, ElseLoc);
283 } else if (WarnOnUnfixable) {
284 // Warn, but don't attempt an autofix.
285 diag(ElseLoc, WarningMessage) << ControlFlowInterrupter;
286 }
287 return;
288 }
289
290 if (checkInitDeclUsageInElse(If) != nullptr) {
291 if (!WarnOnConditionVariables)
292 return;
293 if (IsLastInScope) {
294 // If the if statement is the last statement of its enclosing statements
295 // scope, we can pull the decl out of the if statement.
296 DiagnosticBuilder Diag = diag(ElseLoc, WarningMessage)
297 << ControlFlowInterrupter
298 << SourceRange(ElseLoc);
299 Diag << tooling::fixit::createReplacement(
300 SourceRange(If->getIfLoc()),
301 (tooling::fixit::getText(*If->getInit(), *Result.Context) +
302 "\n" +
303 tooling::fixit::getText(If->getIfLoc(), *Result.Context))
304 .str())
305 << tooling::fixit::createRemoval(If->getInit()->getSourceRange());
306 removeElseAndBrackets(Diag, *Result.Context, Else, ElseLoc);
307 } else if (WarnOnUnfixable) {
308 // Warn, but don't attempt an autofix.
309 diag(ElseLoc, WarningMessage) << ControlFlowInterrupter;
310 }
311 return;
312 }
313
314 DiagnosticBuilder Diag = diag(ElseLoc, WarningMessage)
315 << ControlFlowInterrupter << SourceRange(ElseLoc);
316 removeElseAndBrackets(Diag, *Result.Context, Else, ElseLoc);
317}
318
319} // namespace clang::tidy::readability
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
ElseAfterReturnCheck(StringRef Name, ClangTidyContext *Context)
llvm::DenseMap< FileID, SmallVector< SourceRange, 1 > > ConditionalBranchMap
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID)
static constexpr char InterruptingStr[]
static bool containsDeclInScope(const Stmt *Node)
static constexpr char WarnOnUnfixableStr[]
static bool hasPreprocessorBranchEndBetweenLocations(const ElseAfterReturnCheck::ConditionalBranchMap &ConditionalBranchMap, const SourceManager &SM, SourceLocation StartLoc, SourceLocation EndLoc)
static StringRef getControlFlowString(const Stmt &Stmt)
static const DeclRefExpr * checkConditionVarUsageInElse(const IfStmt *If)
static constexpr char WarnOnConditionVariablesStr[]
static void removeElseAndBrackets(DiagnosticBuilder &Diag, ASTContext &Context, const Stmt *Else, SourceLocation ElseLoc)
static const DeclRefExpr * findUsage(const Stmt *Node, const Decl *D)
static const DeclRefExpr * checkInitDeclUsageInElse(const IfStmt *If)
static constexpr char WarningMessage[]
static const DeclRefExpr * findUsageRange(const Stmt *Node, DeclStmt::decl_const_range Decls)
llvm::StringMap< ClangTidyValue > OptionMap