clang 24.0.0git
DefinitionBlockSeparator.cpp
Go to the documentation of this file.
1//===--- DefinitionBlockSeparator.cpp ---------------------------*- C++ -*-===//
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 implements DefinitionBlockSeparator, a TokenAnalyzer that inserts
11/// or removes empty lines separating definition blocks like classes, structs,
12/// functions, enums, and namespaces in between.
13///
14//===----------------------------------------------------------------------===//
15
17#define DEBUG_TYPE "definition-block-separator"
18
19namespace clang {
20namespace format {
21std::pair<tooling::Replacements, unsigned> DefinitionBlockSeparator::analyze(
22 TokenAnnotator &Annotator, SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
23 FormatTokenLexer &Tokens) {
24 assert(Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave);
25 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
27 separateBlocks(AnnotatedLines, Result, Tokens);
28 return {Result, 0};
29}
30
31void DefinitionBlockSeparator::separateBlocks(
33 FormatTokenLexer &Tokens) {
34 const bool IsNeverStyle =
35 Style.SeparateDefinitionBlocks == FormatStyle::SDS_Never;
36 const AdditionalKeywords &ExtraKeywords = Tokens.getKeywords();
37 auto GetBracketLevelChange = [](const FormatToken *Tok) {
38 if (Tok->isOneOf(tok::l_brace, tok::l_paren, tok::l_square))
39 return 1;
40 if (Tok->isOneOf(tok::r_brace, tok::r_paren, tok::r_square))
41 return -1;
42 return 0;
43 };
44 auto LikelyDefinition = [&](const AnnotatedLine *Line,
45 bool ExcludeEnum = false) {
46 if ((Line->MightBeFunctionDecl && Line->mightBeFunctionDefinition()) ||
47 Line->startsWithNamespace()) {
48 return true;
49 }
50 int BracketLevel = 0;
51 for (const FormatToken *CurrentToken = Line->First; CurrentToken;
52 CurrentToken = CurrentToken->Next) {
53 if (BracketLevel == 0) {
54 if (CurrentToken->isOneOf(tok::kw_class, tok::kw_struct,
55 tok::kw_union) ||
56 (Style.isJavaScript() &&
57 CurrentToken->is(ExtraKeywords.kw_function))) {
58 if (!ExcludeEnum)
59 return true;
60 // The class/struct keyword in a scoped enum is not a record
61 // definition.
62 const auto *Previous = CurrentToken->getPreviousNonComment();
63 if (!Previous || Previous->isNot(tok::kw_enum))
64 return true;
65 }
66 if (!ExcludeEnum && CurrentToken->is(tok::kw_enum))
67 return true;
68 }
69 BracketLevel += GetBracketLevelChange(CurrentToken);
70 }
71 return false;
72 };
73 unsigned NewlineCount =
74 (Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always ? 1 : 0) + 1;
75
76 Style.MaxEmptyLinesToKeep =
77 std::max(Style.MaxEmptyLinesToKeep, NewlineCount - 1);
78
79 WhitespaceManager Whitespaces(
80 Env.getSourceManager(), Style,
81 Style.LineEnding > FormatStyle::LE_CRLF
83 Env.getSourceManager().getBufferData(Env.getFileID()),
85 : Style.LineEnding == FormatStyle::LE_CRLF);
86 for (unsigned I = 0; I < Lines.size(); ++I) {
87 const auto &CurrentLine = Lines[I];
88 // In the macro expansion pass, MatchingOpeningBlockLineIndex still refers
89 // to the unexpanded line sequence. Expanding a macro into multiple lines
90 // changes line positions, so a closing brace can be matched to the wrong
91 // opening line. Skip this pass and separate blocks in the subsequent pass
92 // over reconstructed macro calls, where the indices are valid.
93 if (CurrentLine->InPPDirective || CurrentLine->InMacroExpansion)
94 continue;
95 FormatToken *TargetToken = nullptr;
96 AnnotatedLine *TargetLine;
97 auto OpeningLineIndex = CurrentLine->MatchingOpeningBlockLineIndex;
98 AnnotatedLine *OpeningLine = nullptr;
99 const auto IsAccessSpecifierToken = [](const FormatToken *Token) {
100 return Token->isAccessSpecifier() || Token->isObjCAccessSpecifier();
101 };
102 const auto InsertReplacement = [&](const int NewlineToInsert) {
103 assert(TargetLine);
104 assert(TargetToken);
105
106 // Lines should not be added in the disabled region.
107 if (TargetToken->is(tok::comment) &&
108 isClangFormatOn(TargetToken->TokenText)) {
109 return;
110 }
111 // Do not handle EOF newlines.
112 if (TargetToken->is(tok::eof))
113 return;
114 if (IsAccessSpecifierToken(TargetToken) ||
115 (OpeningLineIndex > 0 &&
116 IsAccessSpecifierToken(Lines[OpeningLineIndex - 1]->First))) {
117 return;
118 }
119 if (!TargetLine->Affected)
120 return;
121 Whitespaces.replaceWhitespace(*TargetToken, NewlineToInsert,
122 TargetToken->OriginalColumn,
123 TargetToken->OriginalColumn);
124 };
125 const auto IsPPConditional = [&](const size_t LineIndex) {
126 const auto &Line = Lines[LineIndex];
127 return Line->First->is(tok::hash) && Line->First->Next &&
128 Line->First->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_else,
129 tok::pp_ifndef, tok::pp_elifndef,
130 tok::pp_elifdef, tok::pp_elif,
131 tok::pp_endif);
132 };
133 const auto FollowingOtherOpening = [&]() {
134 return OpeningLineIndex == 0 ||
135 Lines[OpeningLineIndex - 1]->Last->opensScope() ||
136 IsPPConditional(OpeningLineIndex - 1);
137 };
138 const auto HasEnumOnLine = [&]() {
139 bool FoundEnumKeyword = false;
140 int BracketLevel = 0;
141 for (const FormatToken *CurrentToken = CurrentLine->First; CurrentToken;
142 CurrentToken = CurrentToken->Next) {
143 if (BracketLevel == 0) {
144 if (CurrentToken->is(tok::kw_enum))
145 FoundEnumKeyword = true;
146 else if (FoundEnumKeyword && CurrentToken->is(tok::l_brace))
147 return true;
148 }
149 BracketLevel += GetBracketLevelChange(CurrentToken);
150 }
151 return FoundEnumKeyword && I + 1 < Lines.size() &&
152 Lines[I + 1]->First->is(tok::l_brace);
153 };
154
155 bool IsDefBlock = false;
156 const auto MayPrecedeDefinition = [&](const int Direction = -1) {
157 assert(Direction >= -1);
158 assert(Direction <= 1);
159
160 if (Lines[OpeningLineIndex]->First->is(TT_CSharpGenericTypeConstraint))
161 return true;
162
163 const size_t OperateIndex = OpeningLineIndex + Direction;
164 assert(OperateIndex < Lines.size());
165 const auto &OperateLine = Lines[OperateIndex];
166 if (LikelyDefinition(OperateLine))
167 return false;
168
169 const auto *NextLine =
170 OperateIndex + 1 < Lines.size() ? Lines[OperateIndex + 1] : nullptr;
171
172 if (const auto *Tok = OperateLine->First;
173 Tok->is(tok::comment) && !isClangFormatOn(Tok->TokenText)) {
174 const bool IsEndComment = Tok->NewlinesBefore == 1 && NextLine &&
175 NextLine->First->NewlinesBefore > 1;
176 if (!IsEndComment)
177 return true;
178 }
179
180 // A single line identifier that is not in the last line.
181 if (OperateLine->First->is(tok::identifier) &&
182 OperateLine->First == OperateLine->Last && NextLine) {
183 // UnwrappedLineParser's recognition of free-standing macro like
184 // Q_OBJECT may also recognize some uppercased type names that may be
185 // used as return type as that kind of macros, which is a bit hard to
186 // distinguish one from another purely from token patterns. Here, we
187 // try not to add new lines below those identifiers.
188 if (NextLine->MightBeFunctionDecl &&
189 NextLine->mightBeFunctionDefinition() &&
190 NextLine->First->NewlinesBefore == 1 &&
191 OperateLine->First->is(TT_FunctionLikeOrFreestandingMacro)) {
192 return true;
193 }
194 }
195
196 if (Style.isCSharp() && OperateLine->First->is(TT_AttributeLSquare))
197 return true;
198 return false;
199 };
200
201 if (HasEnumOnLine() &&
202 !LikelyDefinition(CurrentLine, /*ExcludeEnum=*/true)) {
203 // We have no scope opening/closing information for enum.
204 IsDefBlock = true;
205 OpeningLineIndex = I;
206 while (OpeningLineIndex > 0 && MayPrecedeDefinition())
207 --OpeningLineIndex;
208 OpeningLine = Lines[OpeningLineIndex];
209 TargetLine = OpeningLine;
210 TargetToken = TargetLine->First;
211 if (!FollowingOtherOpening())
212 InsertReplacement(NewlineCount);
213 else if (IsNeverStyle)
214 InsertReplacement(OpeningLineIndex != 0);
215 TargetLine = CurrentLine;
216 TargetToken = TargetLine->First;
217 while (TargetToken && TargetToken->isNot(tok::r_brace))
218 TargetToken = TargetToken->Next;
219 if (!TargetToken)
220 while (I < Lines.size() && Lines[I]->First->isNot(tok::r_brace))
221 ++I;
222 } else if (CurrentLine->First->closesScope()) {
223 if (OpeningLineIndex > Lines.size())
224 continue;
225 // A function try block should be together.
226 if (CurrentLine->First->startsSequence(tok::r_brace, tok::kw_catch))
227 continue;
228 // Handling the case that opening brace has its own line, with checking
229 // whether the last line already had an opening brace to guard against
230 // misrecognition.
231 if (OpeningLineIndex > 0 &&
232 Lines[OpeningLineIndex]->First->is(tok::l_brace) &&
233 Lines[OpeningLineIndex - 1]->Last->isNot(tok::l_brace)) {
234 --OpeningLineIndex;
235 }
236 OpeningLine = Lines[OpeningLineIndex];
237 // Closing a function definition.
238 if (LikelyDefinition(OpeningLine)) {
239 IsDefBlock = true;
240 while (OpeningLineIndex > 0 && MayPrecedeDefinition())
241 --OpeningLineIndex;
242 OpeningLine = Lines[OpeningLineIndex];
243 TargetLine = OpeningLine;
244 TargetToken = TargetLine->First;
245 if (!FollowingOtherOpening()) {
246 // Avoid duplicated replacement.
247 if (TargetToken->isNot(tok::l_brace))
248 InsertReplacement(NewlineCount);
249 } else if (IsNeverStyle) {
250 InsertReplacement(OpeningLineIndex != 0);
251 }
252 }
253 }
254
255 // Not the last token.
256 if (IsDefBlock && I + 1 < Lines.size()) {
257 OpeningLineIndex = I + 1;
258 TargetLine = Lines[OpeningLineIndex];
259 TargetToken = TargetLine->First;
260
261 // No empty line for continuously closing scopes. The token will be
262 // handled in another case if the line following is opening a
263 // definition.
264 if (!TargetToken->closesScope() && !IsPPConditional(OpeningLineIndex)) {
265 // Check whether current line may precede a definition line.
266 while (OpeningLineIndex + 1 < Lines.size() &&
267 MayPrecedeDefinition(/*Direction=*/0)) {
268 ++OpeningLineIndex;
269 }
270 TargetLine = Lines[OpeningLineIndex];
271 if (!LikelyDefinition(TargetLine)) {
272 OpeningLineIndex = I + 1;
273 TargetLine = Lines[I + 1];
274 TargetToken = TargetLine->First;
275 InsertReplacement(NewlineCount);
276 }
277 } else if (IsNeverStyle) {
278 InsertReplacement(/*NewlineToInsert=*/1);
279 }
280 }
281 }
282 for (const auto &R : Whitespaces.generateReplacements()) {
283 // The add method returns an Error instance which simulates program exit
284 // code through overloading boolean operator, thus false here indicates
285 // success.
286 if (Result.add(R))
287 return;
288 }
289}
290} // namespace format
291} // namespace clang
This file declares DefinitionBlockSeparator, a TokenAnalyzer that inserts or removes empty lines sepa...
FormatToken()
Token Tok
The Token.
FormatToken * Previous
The previous token in the unwrapped line.
std::pair< tooling::Replacements, unsigned > analyze(TokenAnnotator &Annotator, SmallVectorImpl< AnnotatedLine * > &AnnotatedLines, FormatTokenLexer &Tokens) override
const AdditionalKeywords & getKeywords()
AffectedRangeManager AffectedRangeMgr
const Environment & Env
Determines extra information about the tokens comprising an UnwrappedLine.
static bool inputUsesCRLF(StringRef Text, bool DefaultToCRLF)
Infers whether the input is using CRLF.
Maintains a set of replacements that are conflict-free.
bool isClangFormatOn(StringRef Comment)
Definition Format.cpp:5010
Top level wrappers for InstallAPI frontend operations.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
Encapsulates keywords that are context sensitive or for languages not properly supported by Clang's l...
IdentifierInfo * kw_function
@ SDS_Never
Remove any empty line between definition blocks.
Definition Format.h:5045
@ SDS_Always
Insert an empty line between definition blocks.
Definition Format.h:5043
@ SDS_Leave
Leave definition blocks as they are.
Definition Format.h:5041
@ LE_DeriveCRLF
Use \r\n unless the input has more lines ending in \n.
Definition Format.h:3933
A wrapper around a Token storing information about the whitespace characters preceding it.