clang-tools 23.0.0git
BracesAroundStatement.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///
9/// \file
10/// This file provides utilities to put braces around a statement.
11///
12//===----------------------------------------------------------------------===//
13
15#include "../utils/LexerUtils.h"
16#include "LexerUtils.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/Basic/CharInfo.h"
19#include "clang/Basic/LangOptions.h"
20#include "clang/Lex/Lexer.h"
21
22namespace clang::tidy::utils {
23
24BraceInsertionHints::operator bool() const { return DiagnosticPos.isValid(); }
25
27 return OpeningBracePos.isValid() && ClosingBracePos.isValid();
28}
29
31 const SourceManager &SourceMgr) const {
32 return SourceMgr.getSpellingLineNumber(ClosingBracePos) -
33 SourceMgr.getSpellingLineNumber(OpeningBracePos);
34}
35
37 return OpeningBracePos.isValid()
38 ? FixItHint::CreateInsertion(OpeningBracePos, " {")
39 : FixItHint();
40}
41
43 return ClosingBracePos.isValid()
44 ? FixItHint::CreateInsertion(ClosingBracePos, ClosingBrace)
45 : FixItHint();
46}
47
48static tok::TokenKind getTokenKind(SourceLocation Loc, const SourceManager &SM,
49 const LangOptions &LangOpts) {
50 Token Tok;
51 const SourceLocation Beginning =
52 Lexer::GetBeginningOfToken(Loc, SM, LangOpts);
53 const bool Invalid = Lexer::getRawToken(Beginning, Tok, SM, LangOpts);
54 assert(!Invalid && "Expected a valid token.");
55
56 if (Invalid)
57 return tok::NUM_TOKENS;
58
59 return Tok.getKind();
60}
61
62static SourceLocation findEndLocation(const Stmt &S, const SourceManager &SM,
63 const LangOptions &LangOpts) {
64 SourceLocation Loc = lexer::getUnifiedEndLoc(S, SM, LangOpts);
65 if (!Loc.isValid())
66 return Loc;
67
68 // Start searching right after S.
69 Loc = Loc.getLocWithOffset(1);
70
71 for (;;) {
72 assert(Loc.isValid());
73 while (isHorizontalWhitespace(*SM.getCharacterData(Loc)))
74 Loc = Loc.getLocWithOffset(1);
75
76 if (isVerticalWhitespace(*SM.getCharacterData(Loc))) {
77 // EOL, insert brace before.
78 break;
79 }
80 const tok::TokenKind TokKind = getTokenKind(Loc, SM, LangOpts);
81 if (TokKind != tok::comment) {
82 // Non-comment token, insert brace before.
83 break;
84 }
85
86 const SourceLocation TokEndLoc =
87 Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
88 const SourceRange TokRange(Loc, TokEndLoc);
89 const StringRef Comment = Lexer::getSourceText(
90 CharSourceRange::getTokenRange(TokRange), SM, LangOpts);
91 if (Comment.starts_with("/*") && Comment.contains('\n')) {
92 // Multi-line block comment, insert brace before.
93 break;
94 }
95 // else: Trailing comment, insert brace after the newline.
96
97 // Fast-forward current token.
98 Loc = TokEndLoc;
99 }
100 return Loc;
101}
102
104 const LangOptions &LangOpts,
105 const SourceManager &SM,
106 SourceLocation StartLoc,
107 SourceLocation EndLocHint) {
108 // 1) If there's a corresponding "else" or "while", the check inserts "} "
109 // right before that token.
110 // 2) If there's a multi-line block comment starting on the same line after
111 // the location we're inserting the closing brace at, or there's a non-comment
112 // token, the check inserts "\n}" right before that token.
113 // 3) Otherwise the check finds the end of line (possibly after some block or
114 // line comments) and inserts "\n}" right before that EOL.
115 if (!S || isa<CompoundStmt>(S)) {
116 // Already inside braces.
117 return {};
118 }
119
120 // When TreeTransform, Stmt in constexpr IfStmt will be transform to NullStmt.
121 // This NullStmt can be detected according to beginning token.
122 const SourceLocation StmtBeginLoc = S->getBeginLoc();
123 if (isa<NullStmt>(S) && StmtBeginLoc.isValid() &&
124 getTokenKind(StmtBeginLoc, SM, LangOpts) == tok::l_brace)
125 return {};
126
127 if (StartLoc.isInvalid())
128 return {};
129
130 const Stmt *InnerS = S;
131 while (const auto *AS = dyn_cast<AttributedStmt>(InnerS))
132 InnerS = AS->getSubStmt();
133
134 SourceLocation InsertLoc = StartLoc;
135 if (S != InnerS) {
136 if (std::optional<Token> Tok = utils::lexer::getPreviousToken(
137 InnerS->getBeginLoc(), SM, LangOpts, /*SkipComments=*/true)) {
138 InsertLoc = Tok->getLocation();
139 }
140 }
141
142 // Convert StartLoc to file location, if it's on the same macro expansion
143 // level as the start of the statement. We also need file locations for
144 // Lexer::getLocForEndOfToken working properly.
145 StartLoc = Lexer::makeFileCharRange(CharSourceRange::getCharRange(
146 InsertLoc, InnerS->getBeginLoc()),
147 SM, LangOpts)
148 .getBegin();
149 if (StartLoc.isInvalid())
150 return {};
151 StartLoc = Lexer::getLocForEndOfToken(StartLoc, 0, SM, LangOpts);
152
153 // StartLoc points at the location of the opening brace to be inserted.
154 SourceLocation EndLoc;
155 StringRef ClosingInsertion;
156 if (EndLocHint.isValid()) {
157 EndLoc = EndLocHint;
158 ClosingInsertion = "} ";
159 } else {
160 EndLoc = findEndLocation(*S, SM, LangOpts);
161 ClosingInsertion = "\n}";
162 }
163
164 assert(StartLoc.isValid());
165
166 // Change only if StartLoc and EndLoc are on the same macro expansion level.
167 // This will also catch invalid EndLoc.
168 // Example: LLVM_DEBUG( for(...) do_something() );
169 // In this case fix-it cannot be provided as the semicolon which is not
170 // visible here is part of the macro. Adding braces here would require adding
171 // another semicolon.
172 if (Lexer::makeFileCharRange(
173 CharSourceRange::getTokenRange(SourceRange(
174 SM.getSpellingLoc(StartLoc), SM.getSpellingLoc(EndLoc))),
175 SM, LangOpts)
176 .isInvalid())
177 return {StartLoc};
178 return {StartLoc, EndLoc, ClosingInsertion};
179}
180
181} // namespace clang::tidy::utils
This file provides utilities to put braces around a statement.
SourceLocation getUnifiedEndLoc(const Stmt &S, const SourceManager &SM, const LangOptions &LangOpts)
Stmt->getEndLoc does not always behave the same way depending on Token type.
std::optional< Token > getPreviousToken(SourceLocation Location, const SourceManager &SM, const LangOptions &LangOpts, bool SkipComments)
Returns previous token or std::nullopt if not found.
static SourceLocation findEndLocation(const Stmt &S, const SourceManager &SM, const LangOptions &LangOpts)
BraceInsertionHints getBraceInsertionsHints(const Stmt *const S, const LangOptions &LangOpts, const SourceManager &SM, SourceLocation StartLoc, SourceLocation EndLocHint)
Create fix-it hints for braces that wrap the given statement when applied.
static tok::TokenKind getTokenKind(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
A provider of fix-it hints to insert opening and closing braces.
SourceLocation DiagnosticPos
The position of a potential diagnostic.
FixItHint closingBraceFixIt() const
Fix-it to insert a closing brace.
bool offersFixIts() const
Indicates whether the hint provides fix-its to insert braces.
unsigned resultingCompoundLineExtent(const SourceManager &SourceMgr) const
The number of lines between the inserted opening brace and its closing counterpart.
FixItHint openingBraceFixIt() const
Fix-it to insert an opening brace.