clang 23.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 return true;
59 }
60 if (!ExcludeEnum && CurrentToken->is(tok::kw_enum))
61 return true;
62 }
63 BracketLevel += GetBracketLevelChange(CurrentToken);
64 }
65 return false;
66 };
67 unsigned NewlineCount =
68 (Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always ? 1 : 0) + 1;
69 WhitespaceManager Whitespaces(
70 Env.getSourceManager(), Style,
71 Style.LineEnding > FormatStyle::LE_CRLF
73 Env.getSourceManager().getBufferData(Env.getFileID()),
74 Style.LineEnding == FormatStyle::LE_DeriveCRLF)
75 : Style.LineEnding == FormatStyle::LE_CRLF);
76 for (unsigned I = 0; I < Lines.size(); ++I) {
77 const auto &CurrentLine = Lines[I];
78 if (CurrentLine->InPPDirective)
79 continue;
80 FormatToken *TargetToken = nullptr;
81 AnnotatedLine *TargetLine;
82 auto OpeningLineIndex = CurrentLine->MatchingOpeningBlockLineIndex;
83 AnnotatedLine *OpeningLine = nullptr;
84 const auto IsAccessSpecifierToken = [](const FormatToken *Token) {
85 return Token->isAccessSpecifier() || Token->isObjCAccessSpecifier();
86 };
87 const auto InsertReplacement = [&](const int NewlineToInsert) {
88 assert(TargetLine);
89 assert(TargetToken);
90
91 // Do not handle EOF newlines.
92 if (TargetToken->is(tok::eof))
93 return;
94 if (IsAccessSpecifierToken(TargetToken) ||
95 (OpeningLineIndex > 0 &&
96 IsAccessSpecifierToken(Lines[OpeningLineIndex - 1]->First))) {
97 return;
98 }
99 if (!TargetLine->Affected)
100 return;
101 Whitespaces.replaceWhitespace(*TargetToken, NewlineToInsert,
102 TargetToken->OriginalColumn,
103 TargetToken->OriginalColumn);
104 };
105 const auto IsPPConditional = [&](const size_t LineIndex) {
106 const auto &Line = Lines[LineIndex];
107 return Line->First->is(tok::hash) && Line->First->Next &&
108 Line->First->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_else,
109 tok::pp_ifndef, tok::pp_elifndef,
110 tok::pp_elifdef, tok::pp_elif,
111 tok::pp_endif);
112 };
113 const auto FollowingOtherOpening = [&]() {
114 return OpeningLineIndex == 0 ||
115 Lines[OpeningLineIndex - 1]->Last->opensScope() ||
116 IsPPConditional(OpeningLineIndex - 1);
117 };
118 const auto HasEnumOnLine = [&]() {
119 bool FoundEnumKeyword = false;
120 int BracketLevel = 0;
121 for (const FormatToken *CurrentToken = CurrentLine->First; CurrentToken;
122 CurrentToken = CurrentToken->Next) {
123 if (BracketLevel == 0) {
124 if (CurrentToken->is(tok::kw_enum))
125 FoundEnumKeyword = true;
126 else if (FoundEnumKeyword && CurrentToken->is(tok::l_brace))
127 return true;
128 }
129 BracketLevel += GetBracketLevelChange(CurrentToken);
130 }
131 return FoundEnumKeyword && I + 1 < Lines.size() &&
132 Lines[I + 1]->First->is(tok::l_brace);
133 };
134
135 bool IsDefBlock = false;
136 const auto MayPrecedeDefinition = [&](const int Direction = -1) {
137 assert(Direction >= -1);
138 assert(Direction <= 1);
139
140 if (Lines[OpeningLineIndex]->First->is(TT_CSharpGenericTypeConstraint))
141 return true;
142
143 const size_t OperateIndex = OpeningLineIndex + Direction;
144 assert(OperateIndex < Lines.size());
145 const auto &OperateLine = Lines[OperateIndex];
146 if (LikelyDefinition(OperateLine))
147 return false;
148
149 const auto *NextLine =
150 OperateIndex + 1 < Lines.size() ? Lines[OperateIndex + 1] : nullptr;
151
152 if (const auto *Tok = OperateLine->First;
153 Tok->is(tok::comment) && !isClangFormatOn(Tok->TokenText)) {
154 const bool IsEndComment = Tok->NewlinesBefore == 1 && NextLine &&
155 NextLine->First->NewlinesBefore > 1;
156 if (!IsEndComment)
157 return true;
158 }
159
160 // A single line identifier that is not in the last line.
161 if (OperateLine->First->is(tok::identifier) &&
162 OperateLine->First == OperateLine->Last && NextLine) {
163 // UnwrappedLineParser's recognition of free-standing macro like
164 // Q_OBJECT may also recognize some uppercased type names that may be
165 // used as return type as that kind of macros, which is a bit hard to
166 // distinguish one from another purely from token patterns. Here, we
167 // try not to add new lines below those identifiers.
168 if (NextLine->MightBeFunctionDecl &&
169 NextLine->mightBeFunctionDefinition() &&
170 NextLine->First->NewlinesBefore == 1 &&
171 OperateLine->First->is(TT_FunctionLikeOrFreestandingMacro)) {
172 return true;
173 }
174 }
175
176 if (Style.isCSharp() && OperateLine->First->is(TT_AttributeLSquare))
177 return true;
178 return false;
179 };
180
181 if (HasEnumOnLine() &&
182 !LikelyDefinition(CurrentLine, /*ExcludeEnum=*/true)) {
183 // We have no scope opening/closing information for enum.
184 IsDefBlock = true;
185 OpeningLineIndex = I;
186 while (OpeningLineIndex > 0 && MayPrecedeDefinition())
187 --OpeningLineIndex;
188 OpeningLine = Lines[OpeningLineIndex];
189 TargetLine = OpeningLine;
190 TargetToken = TargetLine->First;
191 if (!FollowingOtherOpening())
192 InsertReplacement(NewlineCount);
193 else if (IsNeverStyle)
194 InsertReplacement(OpeningLineIndex != 0);
195 TargetLine = CurrentLine;
196 TargetToken = TargetLine->First;
197 while (TargetToken && TargetToken->isNot(tok::r_brace))
198 TargetToken = TargetToken->Next;
199 if (!TargetToken)
200 while (I < Lines.size() && Lines[I]->First->isNot(tok::r_brace))
201 ++I;
202 } else if (CurrentLine->First->closesScope()) {
203 if (OpeningLineIndex > Lines.size())
204 continue;
205 // Handling the case that opening brace has its own line, with checking
206 // whether the last line already had an opening brace to guard against
207 // misrecognition.
208 if (OpeningLineIndex > 0 &&
209 Lines[OpeningLineIndex]->First->is(tok::l_brace) &&
210 Lines[OpeningLineIndex - 1]->Last->isNot(tok::l_brace)) {
211 --OpeningLineIndex;
212 }
213 OpeningLine = Lines[OpeningLineIndex];
214 // Closing a function definition.
215 if (LikelyDefinition(OpeningLine)) {
216 IsDefBlock = true;
217 while (OpeningLineIndex > 0 && MayPrecedeDefinition())
218 --OpeningLineIndex;
219 OpeningLine = Lines[OpeningLineIndex];
220 TargetLine = OpeningLine;
221 TargetToken = TargetLine->First;
222 if (!FollowingOtherOpening()) {
223 // Avoid duplicated replacement.
224 if (TargetToken->isNot(tok::l_brace))
225 InsertReplacement(NewlineCount);
226 } else if (IsNeverStyle) {
227 InsertReplacement(OpeningLineIndex != 0);
228 }
229 }
230 }
231
232 // Not the last token.
233 if (IsDefBlock && I + 1 < Lines.size()) {
234 OpeningLineIndex = I + 1;
235 TargetLine = Lines[OpeningLineIndex];
236 TargetToken = TargetLine->First;
237
238 // No empty line for continuously closing scopes. The token will be
239 // handled in another case if the line following is opening a
240 // definition.
241 if (!TargetToken->closesScope() && !IsPPConditional(OpeningLineIndex)) {
242 // Check whether current line may precede a definition line.
243 while (OpeningLineIndex + 1 < Lines.size() &&
244 MayPrecedeDefinition(/*Direction=*/0)) {
245 ++OpeningLineIndex;
246 }
247 TargetLine = Lines[OpeningLineIndex];
248 if (!LikelyDefinition(TargetLine)) {
249 OpeningLineIndex = I + 1;
250 TargetLine = Lines[I + 1];
251 TargetToken = TargetLine->First;
252 InsertReplacement(NewlineCount);
253 }
254 } else if (IsNeverStyle) {
255 InsertReplacement(/*NewlineToInsert=*/1);
256 }
257 }
258 }
259 for (const auto &R : Whitespaces.generateReplacements()) {
260 // The add method returns an Error instance which simulates program exit
261 // code through overloading boolean operator, thus false here indicates
262 // success.
263 if (Result.add(R))
264 return;
265 }
266}
267} // namespace format
268} // namespace clang
This file declares DefinitionBlockSeparator, a TokenAnalyzer that inserts or removes empty lines sepa...
FormatToken()
Token Tok
The Token.
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:4771
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
Definition TypeBase.h:905
Encapsulates keywords that are context sensitive or for languages not properly supported by Clang's l...
IdentifierInfo * kw_function
A wrapper around a Token storing information about the whitespace characters preceding it.