clang-tools 6.0.0

BracesAroundStatementsCheck.cpp
Go to the documentation of this file.
1 //===--- BracesAroundStatementsCheck.cpp - clang-tidy ---------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "BracesAroundStatementsCheck.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
13 #include "clang/Lex/Lexer.h"
14
15 using namespace clang::ast_matchers;
16
17 namespace clang {
18 namespace tidy {
19 namespace readability {
20 namespace {
21
22 tok::TokenKind getTokenKind(SourceLocation Loc, const SourceManager &SM,
23 const ASTContext *Context) {
24 Token Tok;
25 SourceLocation Beginning =
26 Lexer::GetBeginningOfToken(Loc, SM, Context->getLangOpts());
27 const bool Invalid =
28 Lexer::getRawToken(Beginning, Tok, SM, Context->getLangOpts());
29 assert(!Invalid && "Expected a valid token.");
30
31 if (Invalid)
32 return tok::NUM_TOKENS;
33
34 return Tok.getKind();
35 }
36
37 SourceLocation forwardSkipWhitespaceAndComments(SourceLocation Loc,
38 const SourceManager &SM,
39 const ASTContext *Context) {
40 assert(Loc.isValid());
41 for (;;) {
42 while (isWhitespace(*SM.getCharacterData(Loc)))
43 Loc = Loc.getLocWithOffset(1);
44
45 tok::TokenKind TokKind = getTokenKind(Loc, SM, Context);
46 if (TokKind == tok::NUM_TOKENS || TokKind != tok::comment)
47 return Loc;
48
49 // Fast-forward current token.
50 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, Context->getLangOpts());
51 }
52 }
53
54 SourceLocation findEndLocation(SourceLocation LastTokenLoc,
55 const SourceManager &SM,
56 const ASTContext *Context) {
57 SourceLocation Loc =
58 Lexer::GetBeginningOfToken(LastTokenLoc, SM, Context->getLangOpts());
59 // Loc points to the beginning of the last (non-comment non-ws) token
60 // before end or ';'.
61 assert(Loc.isValid());
62 bool SkipEndWhitespaceAndComments = true;
63 tok::TokenKind TokKind = getTokenKind(Loc, SM, Context);
64 if (TokKind == tok::NUM_TOKENS || TokKind == tok::semi ||
65 TokKind == tok::r_brace) {
66 // If we are at ";" or "}", we found the last token. We could use as well
67 // `if (isa<NullStmt>(S))`, but it wouldn't work for nested statements.
68 SkipEndWhitespaceAndComments = false;
69 }
70
71 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, Context->getLangOpts());
72 // Loc points past the last token before end or after ';'.
73 if (SkipEndWhitespaceAndComments) {
74 Loc = forwardSkipWhitespaceAndComments(Loc, SM, Context);
75 tok::TokenKind TokKind = getTokenKind(Loc, SM, Context);
76 if (TokKind == tok::semi)
77 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, Context->getLangOpts());
78 }
79
80 for (;;) {
81 assert(Loc.isValid());
82 while (isHorizontalWhitespace(*SM.getCharacterData(Loc))) {
83 Loc = Loc.getLocWithOffset(1);
84 }
85
86 if (isVerticalWhitespace(*SM.getCharacterData(Loc))) {
87 // EOL, insert brace before.
88 break;
89 }
90 tok::TokenKind TokKind = getTokenKind(Loc, SM, Context);
91 if (TokKind != tok::comment) {
92 // Non-comment token, insert brace before.
93 break;
94 }
95
96 SourceLocation TokEndLoc =
97 Lexer::getLocForEndOfToken(Loc, 0, SM, Context->getLangOpts());
98 SourceRange TokRange(Loc, TokEndLoc);
99 StringRef Comment = Lexer::getSourceText(
100 CharSourceRange::getTokenRange(TokRange), SM, Context->getLangOpts());
101 if (Comment.startswith("/*") && Comment.find('\n') != StringRef::npos) {
102 // Multi-line block comment, insert brace before.
103 break;
104 }
105 // else: Trailing comment, insert brace after the newline.
106
107 // Fast-forward current token.
108 Loc = TokEndLoc;
109 }
110 return Loc;
111 }
112
113 } // namespace
114
115 BracesAroundStatementsCheck::BracesAroundStatementsCheck(
116 StringRef Name, ClangTidyContext *Context)
117 : ClangTidyCheck(Name, Context),
118 // Always add braces by default.
119 ShortStatementLines(Options.get("ShortStatementLines", 0U)) {}
120
121 void BracesAroundStatementsCheck::storeOptions(
122 ClangTidyOptions::OptionMap &Opts) {
123 Options.store(Opts, "ShortStatementLines", ShortStatementLines);
124 }
125
126 void BracesAroundStatementsCheck::registerMatchers(MatchFinder *Finder) {
127 Finder->addMatcher(ifStmt().bind("if"), this);
128 Finder->addMatcher(whileStmt().bind("while"), this);
129 Finder->addMatcher(doStmt().bind("do"), this);
130 Finder->addMatcher(forStmt().bind("for"), this);
131 Finder->addMatcher(cxxForRangeStmt().bind("for-range"), this);
132 }
133
134 void BracesAroundStatementsCheck::check(
135 const MatchFinder::MatchResult &Result) {
136 const SourceManager &SM = *Result.SourceManager;
137 const ASTContext *Context = Result.Context;
138
139 // Get location of closing parenthesis or 'do' to insert opening brace.
140 if (auto S = Result.Nodes.getNodeAs<ForStmt>("for")) {
141 checkStmt(Result, S->getBody(), S->getRParenLoc());
142 } else if (auto S = Result.Nodes.getNodeAs<CXXForRangeStmt>("for-range")) {
143 checkStmt(Result, S->getBody(), S->getRParenLoc());
144 } else if (auto S = Result.Nodes.getNodeAs<DoStmt>("do")) {
145 checkStmt(Result, S->getBody(), S->getDoLoc(), S->getWhileLoc());
146 } else if (auto S = Result.Nodes.getNodeAs<WhileStmt>("while")) {
147 SourceLocation StartLoc = findRParenLoc(S, SM, Context);
148 if (StartLoc.isInvalid())
149 return;
150 checkStmt(Result, S->getBody(), StartLoc);
151 } else if (auto S = Result.Nodes.getNodeAs<IfStmt>("if")) {
152 SourceLocation StartLoc = findRParenLoc(S, SM, Context);
153 if (StartLoc.isInvalid())
154 return;
155 if (ForceBracesStmts.erase(S))
156 ForceBracesStmts.insert(S->getThen());
157 bool BracedIf = checkStmt(Result, S->getThen(), StartLoc, S->getElseLoc());
158 const Stmt *Else = S->getElse();
159 if (Else && BracedIf)
160 ForceBracesStmts.insert(Else);
161 if (Else && !isa<IfStmt>(Else)) {
162 // Omit 'else if' statements here, they will be handled directly.
163 checkStmt(Result, Else, S->getElseLoc());
164 }
165 } else {
166 llvm_unreachable("Invalid match");
167 }
168 }
169
170 /// Find location of right parenthesis closing condition.
171 template <typename IfOrWhileStmt>
172 SourceLocation
173 BracesAroundStatementsCheck::findRParenLoc(const IfOrWhileStmt *S,
174 const SourceManager &SM,
175 const ASTContext *Context) {
176 // Skip macros.
177 if (S->getLocStart().isMacroID())
178 return SourceLocation();
179
180 SourceLocation CondEndLoc = S->getCond()->getLocEnd();
181 if (const DeclStmt *CondVar = S->getConditionVariableDeclStmt())
182 CondEndLoc = CondVar->getLocEnd();
183
184 if (!CondEndLoc.isValid()) {
185 return SourceLocation();
186 }
187
188 SourceLocation PastCondEndLoc =
189 Lexer::getLocForEndOfToken(CondEndLoc, 0, SM, Context->getLangOpts());
190 if (PastCondEndLoc.isInvalid())
191 return SourceLocation();
192 SourceLocation RParenLoc =
193 forwardSkipWhitespaceAndComments(PastCondEndLoc, SM, Context);
194 if (RParenLoc.isInvalid())
195 return SourceLocation();
196 tok::TokenKind TokKind = getTokenKind(RParenLoc, SM, Context);
197 if (TokKind != tok::r_paren)
198 return SourceLocation();
199 return RParenLoc;
200 }
201
202 /// Determine if the statement needs braces around it, and add them if it does.
203 /// Returns true if braces where added.
204 bool BracesAroundStatementsCheck::checkStmt(
205 const MatchFinder::MatchResult &Result, const Stmt *S,
206 SourceLocation InitialLoc, SourceLocation EndLocHint) {
207 // 1) If there's a corresponding "else" or "while", the check inserts "} "
208 // right before that token.
209 // 2) If there's a multi-line block comment starting on the same line after
210 // the location we're inserting the closing brace at, or there's a non-comment
211 // token, the check inserts "\n}" right before that token.
212 // 3) Otherwise the check finds the end of line (possibly after some block or
213 // line comments) and inserts "\n}" right before that EOL.
214 if (!S || isa<CompoundStmt>(S)) {
215 // Already inside braces.
216 return false;
217 }
218
219 if (!InitialLoc.isValid())
220 return false;
221 const SourceManager &SM = *Result.SourceManager;
222 const ASTContext *Context = Result.Context;
223
224 // Treat macros.
225 CharSourceRange FileRange = Lexer::makeFileCharRange(
226 CharSourceRange::getTokenRange(S->getSourceRange()), SM,
227 Context->getLangOpts());
228 if (FileRange.isInvalid())
229 return false;
230
231 // Convert InitialLoc to file location, if it's on the same macro expansion
232 // level as the start of the statement. We also need file locations for
233 // Lexer::getLocForEndOfToken working properly.
234 InitialLoc = Lexer::makeFileCharRange(
235 CharSourceRange::getCharRange(InitialLoc, S->getLocStart()),
236 SM, Context->getLangOpts())
237 .getBegin();
238 if (InitialLoc.isInvalid())
239 return false;
240 SourceLocation StartLoc =
241 Lexer::getLocForEndOfToken(InitialLoc, 0, SM, Context->getLangOpts());
242
243 // StartLoc points at the location of the opening brace to be inserted.
244 SourceLocation EndLoc;
245 std::string ClosingInsertion;
246 if (EndLocHint.isValid()) {
247 EndLoc = EndLocHint;
248 ClosingInsertion = "} ";
249 } else {
250 const auto FREnd = FileRange.getEnd().getLocWithOffset(-1);
251 EndLoc = findEndLocation(FREnd, SM, Context);
252 ClosingInsertion = "\n}";
253 }
254
255 assert(StartLoc.isValid());
256 assert(EndLoc.isValid());
257 // Don't require braces for statements spanning less than certain number of
258 // lines.
259 if (ShortStatementLines && !ForceBracesStmts.erase(S)) {
260 unsigned StartLine = SM.getSpellingLineNumber(StartLoc);
261 unsigned EndLine = SM.getSpellingLineNumber(EndLoc);
262 if (EndLine - StartLine < ShortStatementLines)
263 return false;
264 }
265
266 auto Diag = diag(StartLoc, "statement should be inside braces");
267 Diag << FixItHint::CreateInsertion(StartLoc, " {")
268 << FixItHint::CreateInsertion(EndLoc, ClosingInsertion);
269 return true;
270 }
271
272 void BracesAroundStatementsCheck::onEndOfTranslationUnit() {
273 ForceBracesStmts.clear();
274 }
275
276 } // namespace readability
277 } // namespace tidy
278 } // namespace clang
Loc
SourceLocation Loc
&#39;#&#39; location in the include directive
Definition: IncludeOrderCheck.cpp:36
clang::ast_matchers
Definition: ClangTidyDiagnosticConsumer.h:27
clang::tidy::OptionsView::store
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.
Definition: ClangTidy.cpp:449
clang::tidy::readability::BracesAroundStatementsCheck::registerMatchers
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Definition: BracesAroundStatementsCheck.cpp:126
Name
StringHandle Name
Definition: PreprocessorTracker.cpp:525
clang::tidy::ClangTidyCheck
Base class for all clang-tidy checks.
Definition: ClangTidy.h:127
clang::tidy::ClangTidyCheck::Options
OptionsView Options
Definition: ClangTidy.h:183
clang::tidy::readability::BracesAroundStatementsCheck::onEndOfTranslationUnit
void onEndOfTranslationUnit() override
Definition: BracesAroundStatementsCheck.cpp:272
clang::tidy::ClangTidyOptions::OptionMap
std::map< std::string, std::string > OptionMap
Definition: ClangTidyOptions.h:99
BracesAroundStatementsCheck.h
clang::tidy::readability::BracesAroundStatementsCheck::storeOptions
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
Definition: BracesAroundStatementsCheck.cpp:121
clang
Definition: AndroidTidyModule.cpp:28
clang::tidy::ClangTidyContext
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Definition: ClangTidyDiagnosticConsumer.h:104
clang::tidy::ClangTidyCheck::diag
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check&#39;s name.
Definition: ClangTidy.cpp:416
clang::tidy::readability::BracesAroundStatementsCheck::check
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Definition: BracesAroundStatementsCheck.cpp:134