clang-tools 22.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 // Convert StartLoc to file location, if it's on the same macro expansion
131 // level as the start of the statement. We also need file locations for
132 // Lexer::getLocForEndOfToken working properly.
133 StartLoc = Lexer::makeFileCharRange(
134 CharSourceRange::getCharRange(StartLoc, S->getBeginLoc()), SM,
135 LangOpts)
136 .getBegin();
137 if (StartLoc.isInvalid())
138 return {};
139 StartLoc = Lexer::getLocForEndOfToken(StartLoc, 0, SM, LangOpts);
140
141 // StartLoc points at the location of the opening brace to be inserted.
142 SourceLocation EndLoc;
143 StringRef ClosingInsertion;
144 if (EndLocHint.isValid()) {
145 EndLoc = EndLocHint;
146 ClosingInsertion = "} ";
147 } else {
148 EndLoc = findEndLocation(*S, SM, LangOpts);
149 ClosingInsertion = "\n}";
150 }
151
152 assert(StartLoc.isValid());
153
154 // Change only if StartLoc and EndLoc are on the same macro expansion level.
155 // This will also catch invalid EndLoc.
156 // Example: LLVM_DEBUG( for(...) do_something() );
157 // In this case fix-it cannot be provided as the semicolon which is not
158 // visible here is part of the macro. Adding braces here would require adding
159 // another semicolon.
160 if (Lexer::makeFileCharRange(
161 CharSourceRange::getTokenRange(SourceRange(
162 SM.getSpellingLoc(StartLoc), SM.getSpellingLoc(EndLoc))),
163 SM, LangOpts)
164 .isInvalid())
165 return {StartLoc};
166 return {StartLoc, EndLoc, ClosingInsertion};
167}
168
169} // 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.
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.