1 | //===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===// |
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 | #include "UnwrappedLineFormatter.h" |
10 | #include "FormatToken.h" |
11 | #include "NamespaceEndCommentsFixer.h" |
12 | #include "WhitespaceManager.h" |
13 | #include "llvm/Support/Debug.h" |
14 | #include <queue> |
15 | |
16 | #define DEBUG_TYPE "format-formatter" |
17 | |
18 | namespace clang { |
19 | namespace format { |
20 | |
21 | namespace { |
22 | |
23 | bool startsExternCBlock(const AnnotatedLine &Line) { |
24 | const FormatToken *Next = Line.First->getNextNonComment(); |
25 | const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr; |
26 | return Line.startsWith(Tokens: tok::kw_extern) && Next && Next->isStringLiteral() && |
27 | NextNext && NextNext->is(Kind: tok::l_brace); |
28 | } |
29 | |
30 | bool isRecordLBrace(const FormatToken &Tok) { |
31 | return Tok.isOneOf(K1: TT_ClassLBrace, K2: TT_EnumLBrace, Ks: TT_RecordLBrace, |
32 | Ks: TT_StructLBrace, Ks: TT_UnionLBrace); |
33 | } |
34 | |
35 | /// Tracks the indent level of \c AnnotatedLines across levels. |
36 | /// |
37 | /// \c nextLine must be called for each \c AnnotatedLine, after which \c |
38 | /// getIndent() will return the indent for the last line \c nextLine was called |
39 | /// with. |
40 | /// If the line is not formatted (and thus the indent does not change), calling |
41 | /// \c adjustToUnmodifiedLine after the call to \c nextLine will cause |
42 | /// subsequent lines on the same level to be indented at the same level as the |
43 | /// given line. |
44 | class LevelIndentTracker { |
45 | public: |
46 | LevelIndentTracker(const FormatStyle &Style, |
47 | const AdditionalKeywords &Keywords, unsigned StartLevel, |
48 | int AdditionalIndent) |
49 | : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) { |
50 | for (unsigned i = 0; i != StartLevel; ++i) |
51 | IndentForLevel.push_back(Elt: Style.IndentWidth * i + AdditionalIndent); |
52 | } |
53 | |
54 | /// Returns the indent for the current line. |
55 | unsigned getIndent() const { return Indent; } |
56 | |
57 | /// Update the indent state given that \p Line is going to be formatted |
58 | /// next. |
59 | void nextLine(const AnnotatedLine &Line) { |
60 | Offset = getIndentOffset(Line); |
61 | // Update the indent level cache size so that we can rely on it |
62 | // having the right size in adjustToUnmodifiedline. |
63 | if (Line.Level >= IndentForLevel.size()) |
64 | IndentForLevel.resize(N: Line.Level + 1, NV: -1); |
65 | if (Style.IndentPPDirectives != FormatStyle::PPDIS_None && |
66 | (Line.InPPDirective || |
67 | (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash && |
68 | Line.Type == LT_CommentAbovePPDirective))) { |
69 | unsigned PPIndentWidth = |
70 | (Style.PPIndentWidth >= 0) ? Style.PPIndentWidth : Style.IndentWidth; |
71 | Indent = Line.InMacroBody |
72 | ? Line.PPLevel * PPIndentWidth + |
73 | (Line.Level - Line.PPLevel) * Style.IndentWidth |
74 | : Line.Level * PPIndentWidth; |
75 | Indent += AdditionalIndent; |
76 | } else { |
77 | // When going to lower levels, forget previous higher levels so that we |
78 | // recompute future higher levels. But don't forget them if we enter a PP |
79 | // directive, since these do not terminate a C++ code block. |
80 | if (!Line.InPPDirective) { |
81 | assert(Line.Level <= IndentForLevel.size()); |
82 | IndentForLevel.resize(N: Line.Level + 1); |
83 | } |
84 | Indent = getIndent(Level: Line.Level); |
85 | } |
86 | if (static_cast<int>(Indent) + Offset >= 0) |
87 | Indent += Offset; |
88 | if (Line.IsContinuation) |
89 | Indent = Line.Level * Style.IndentWidth + Style.ContinuationIndentWidth; |
90 | } |
91 | |
92 | /// Update the level indent to adapt to the given \p Line. |
93 | /// |
94 | /// When a line is not formatted, we move the subsequent lines on the same |
95 | /// level to the same indent. |
96 | /// Note that \c nextLine must have been called before this method. |
97 | void adjustToUnmodifiedLine(const AnnotatedLine &Line) { |
98 | if (Line.InPPDirective || Line.IsContinuation) |
99 | return; |
100 | assert(Line.Level < IndentForLevel.size()); |
101 | if (Line.First->is(Kind: tok::comment) && IndentForLevel[Line.Level] != -1) |
102 | return; |
103 | unsigned LevelIndent = Line.First->OriginalColumn; |
104 | if (static_cast<int>(LevelIndent) - Offset >= 0) |
105 | LevelIndent -= Offset; |
106 | IndentForLevel[Line.Level] = LevelIndent; |
107 | } |
108 | |
109 | private: |
110 | /// Get the offset of the line relatively to the level. |
111 | /// |
112 | /// For example, 'public:' labels in classes are offset by 1 or 2 |
113 | /// characters to the left from their level. |
114 | int getIndentOffset(const AnnotatedLine &Line) { |
115 | if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) |
116 | return 0; |
117 | const auto &RootToken = *Line.First; |
118 | if (Line.Type == LT_AccessModifier || |
119 | RootToken.isAccessSpecifier(/*ColonRequired=*/false) || |
120 | RootToken.isObjCAccessSpecifier() || |
121 | (RootToken.isOneOf(K1: Keywords.kw_signals, K2: Keywords.kw_qsignals) && |
122 | RootToken.Next && RootToken.Next->is(Kind: tok::colon))) { |
123 | // The AccessModifierOffset may be overridden by IndentAccessModifiers, |
124 | // in which case we take a negative value of the IndentWidth to simulate |
125 | // the upper indent level. |
126 | return Style.IndentAccessModifiers ? -Style.IndentWidth |
127 | : Style.AccessModifierOffset; |
128 | } |
129 | return 0; |
130 | } |
131 | |
132 | /// Get the indent of \p Level from \p IndentForLevel. |
133 | /// |
134 | /// \p IndentForLevel must contain the indent for the level \c l |
135 | /// at \p IndentForLevel[l], or a value < 0 if the indent for |
136 | /// that level is unknown. |
137 | unsigned getIndent(unsigned Level) const { |
138 | assert(Level < IndentForLevel.size()); |
139 | if (IndentForLevel[Level] != -1) |
140 | return IndentForLevel[Level]; |
141 | if (Level == 0) |
142 | return 0; |
143 | return getIndent(Level: Level - 1) + Style.IndentWidth; |
144 | } |
145 | |
146 | const FormatStyle &Style; |
147 | const AdditionalKeywords &Keywords; |
148 | const unsigned AdditionalIndent; |
149 | |
150 | /// The indent in characters for each level. It remembers the indent of |
151 | /// previous lines (that are not PP directives) of equal or lower levels. This |
152 | /// is used to align formatted lines to the indent of previous non-formatted |
153 | /// lines. Think about the --lines parameter of clang-format. |
154 | SmallVector<int> IndentForLevel; |
155 | |
156 | /// Offset of the current line relative to the indent level. |
157 | /// |
158 | /// For example, the 'public' keywords is often indented with a negative |
159 | /// offset. |
160 | int Offset = 0; |
161 | |
162 | /// The current line's indent. |
163 | unsigned Indent = 0; |
164 | }; |
165 | |
166 | const FormatToken * |
167 | getMatchingNamespaceToken(const AnnotatedLine *Line, |
168 | const ArrayRef<AnnotatedLine *> &AnnotatedLines) { |
169 | if (!Line->startsWith(Tokens: tok::r_brace)) |
170 | return nullptr; |
171 | size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex; |
172 | if (StartLineIndex == UnwrappedLine::kInvalidIndex) |
173 | return nullptr; |
174 | assert(StartLineIndex < AnnotatedLines.size()); |
175 | return AnnotatedLines[StartLineIndex]->First->getNamespaceToken(); |
176 | } |
177 | |
178 | StringRef getNamespaceTokenText(const AnnotatedLine *Line) { |
179 | const FormatToken *NamespaceToken = Line->First->getNamespaceToken(); |
180 | return NamespaceToken ? NamespaceToken->TokenText : StringRef(); |
181 | } |
182 | |
183 | StringRef |
184 | getMatchingNamespaceTokenText(const AnnotatedLine *Line, |
185 | const ArrayRef<AnnotatedLine *> &AnnotatedLines) { |
186 | const FormatToken *NamespaceToken = |
187 | getMatchingNamespaceToken(Line, AnnotatedLines); |
188 | return NamespaceToken ? NamespaceToken->TokenText : StringRef(); |
189 | } |
190 | |
191 | class LineJoiner { |
192 | public: |
193 | LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords, |
194 | const SmallVectorImpl<AnnotatedLine *> &Lines) |
195 | : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()), |
196 | AnnotatedLines(Lines) {} |
197 | |
198 | /// Returns the next line, merging multiple lines into one if possible. |
199 | const AnnotatedLine *getNextMergedLine(bool DryRun, |
200 | LevelIndentTracker &IndentTracker) { |
201 | if (Next == End) |
202 | return nullptr; |
203 | const AnnotatedLine *Current = *Next; |
204 | IndentTracker.nextLine(Line: *Current); |
205 | unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, I: Next, E: End); |
206 | if (MergedLines > 0 && Style.ColumnLimit == 0) { |
207 | // Disallow line merging if there is a break at the start of one of the |
208 | // input lines. |
209 | for (unsigned i = 0; i < MergedLines; ++i) |
210 | if (Next[i + 1]->First->NewlinesBefore > 0) |
211 | MergedLines = 0; |
212 | } |
213 | if (!DryRun) |
214 | for (unsigned i = 0; i < MergedLines; ++i) |
215 | join(A&: *Next[0], B: *Next[i + 1]); |
216 | Next = Next + MergedLines + 1; |
217 | return Current; |
218 | } |
219 | |
220 | private: |
221 | /// Calculates how many lines can be merged into 1 starting at \p I. |
222 | unsigned |
223 | tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker, |
224 | ArrayRef<AnnotatedLine *>::const_iterator I, |
225 | ArrayRef<AnnotatedLine *>::const_iterator E) { |
226 | const unsigned Indent = IndentTracker.getIndent(); |
227 | |
228 | // Can't join the last line with anything. |
229 | if (I + 1 == E) |
230 | return 0; |
231 | // We can never merge stuff if there are trailing line comments. |
232 | const AnnotatedLine *TheLine = *I; |
233 | if (TheLine->Last->is(TT: TT_LineComment)) |
234 | return 0; |
235 | const auto &NextLine = *I[1]; |
236 | if (NextLine.Type == LT_Invalid || NextLine.First->MustBreakBefore) |
237 | return 0; |
238 | if (TheLine->InPPDirective && |
239 | (!NextLine.InPPDirective || NextLine.First->HasUnescapedNewline)) { |
240 | return 0; |
241 | } |
242 | |
243 | if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit) |
244 | return 0; |
245 | |
246 | unsigned Limit = |
247 | Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent; |
248 | // If we already exceed the column limit, we set 'Limit' to 0. The different |
249 | // tryMerge..() functions can then decide whether to still do merging. |
250 | Limit = TheLine->Last->TotalLength > Limit |
251 | ? 0 |
252 | : Limit - TheLine->Last->TotalLength; |
253 | |
254 | if (TheLine->Last->is(TT: TT_FunctionLBrace) && |
255 | TheLine->First == TheLine->Last && |
256 | !Style.BraceWrapping.SplitEmptyFunction && |
257 | NextLine.First->is(Kind: tok::r_brace)) { |
258 | return tryMergeSimpleBlock(I, E, Limit); |
259 | } |
260 | |
261 | const auto *PreviousLine = I != AnnotatedLines.begin() ? I[-1] : nullptr; |
262 | // Handle empty record blocks where the brace has already been wrapped. |
263 | if (PreviousLine && TheLine->Last->is(Kind: tok::l_brace) && |
264 | TheLine->First == TheLine->Last) { |
265 | bool EmptyBlock = NextLine.First->is(Kind: tok::r_brace); |
266 | |
267 | const FormatToken *Tok = PreviousLine->First; |
268 | if (Tok && Tok->is(Kind: tok::comment)) |
269 | Tok = Tok->getNextNonComment(); |
270 | |
271 | if (Tok && Tok->getNamespaceToken()) { |
272 | return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock |
273 | ? tryMergeSimpleBlock(I, E, Limit) |
274 | : 0; |
275 | } |
276 | |
277 | if (Tok && Tok->is(Kind: tok::kw_typedef)) |
278 | Tok = Tok->getNextNonComment(); |
279 | if (Tok && Tok->isOneOf(K1: tok::kw_class, K2: tok::kw_struct, Ks: tok::kw_union, |
280 | Ks: tok::kw_extern, Ks: Keywords.kw_interface)) { |
281 | return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock |
282 | ? tryMergeSimpleBlock(I, E, Limit) |
283 | : 0; |
284 | } |
285 | |
286 | if (Tok && Tok->is(Kind: tok::kw_template) && |
287 | Style.BraceWrapping.SplitEmptyRecord && EmptyBlock) { |
288 | return 0; |
289 | } |
290 | } |
291 | |
292 | auto ShouldMergeShortFunctions = [this, &I, &NextLine, PreviousLine, |
293 | TheLine]() { |
294 | if (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All) |
295 | return true; |
296 | if (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty && |
297 | NextLine.First->is(Kind: tok::r_brace)) { |
298 | return true; |
299 | } |
300 | |
301 | if (Style.AllowShortFunctionsOnASingleLine & |
302 | FormatStyle::SFS_InlineOnly) { |
303 | // Just checking TheLine->Level != 0 is not enough, because it |
304 | // provokes treating functions inside indented namespaces as short. |
305 | if (Style.isJavaScript() && TheLine->Last->is(TT: TT_FunctionLBrace)) |
306 | return true; |
307 | |
308 | if (TheLine->Level != 0) { |
309 | if (!PreviousLine) |
310 | return false; |
311 | |
312 | // TODO: Use IndentTracker to avoid loop? |
313 | // Find the last line with lower level. |
314 | const AnnotatedLine *Line = nullptr; |
315 | for (auto J = I - 1; J >= AnnotatedLines.begin(); --J) { |
316 | assert(*J); |
317 | if (((*J)->InPPDirective && !(*J)->InMacroBody) || |
318 | (*J)->isComment() || (*J)->Level > TheLine->Level) { |
319 | continue; |
320 | } |
321 | if ((*J)->Level < TheLine->Level || |
322 | (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths && |
323 | (*J)->First->is(Kind: tok::l_brace))) { |
324 | Line = *J; |
325 | break; |
326 | } |
327 | } |
328 | |
329 | if (!Line) |
330 | return false; |
331 | |
332 | // Check if the found line starts a record. |
333 | const auto * = Line->getLastNonComment(); |
334 | // There must be another token (usually `{`), because we chose a |
335 | // non-PPDirective and non-comment line that has a smaller level. |
336 | assert(LastNonComment); |
337 | return isRecordLBrace(Tok: *LastNonComment); |
338 | } |
339 | } |
340 | |
341 | return false; |
342 | }; |
343 | |
344 | bool MergeShortFunctions = ShouldMergeShortFunctions(); |
345 | |
346 | const auto * = TheLine->getFirstNonComment(); |
347 | if (!FirstNonComment) |
348 | return 0; |
349 | |
350 | // FIXME: There are probably cases where we should use FirstNonComment |
351 | // instead of TheLine->First. |
352 | |
353 | if (Style.AllowShortNamespacesOnASingleLine && |
354 | TheLine->First->is(Kind: tok::kw_namespace)) { |
355 | const auto result = tryMergeNamespace(I, E, Limit); |
356 | if (result > 0) |
357 | return result; |
358 | } |
359 | |
360 | if (Style.CompactNamespaces) { |
361 | if (const auto *NSToken = TheLine->First->getNamespaceToken()) { |
362 | int J = 1; |
363 | assert(TheLine->MatchingClosingBlockLineIndex > 0); |
364 | for (auto ClosingLineIndex = TheLine->MatchingClosingBlockLineIndex - 1; |
365 | I + J != E && NSToken->TokenText == getNamespaceTokenText(Line: I[J]) && |
366 | ClosingLineIndex == I[J]->MatchingClosingBlockLineIndex && |
367 | I[J]->Last->TotalLength < Limit; |
368 | ++J, --ClosingLineIndex) { |
369 | Limit -= I[J]->Last->TotalLength + 1; |
370 | |
371 | // Reduce indent level for bodies of namespaces which were compacted, |
372 | // but only if their content was indented in the first place. |
373 | auto *ClosingLine = AnnotatedLines.begin() + ClosingLineIndex + 1; |
374 | const int OutdentBy = I[J]->Level - TheLine->Level; |
375 | assert(OutdentBy >= 0); |
376 | for (auto *CompactedLine = I + J; CompactedLine <= ClosingLine; |
377 | ++CompactedLine) { |
378 | if (!(*CompactedLine)->InPPDirective) { |
379 | const int Level = (*CompactedLine)->Level; |
380 | (*CompactedLine)->Level = std::max(a: Level - OutdentBy, b: 0); |
381 | } |
382 | } |
383 | } |
384 | return J - 1; |
385 | } |
386 | |
387 | if (auto nsToken = getMatchingNamespaceToken(Line: TheLine, AnnotatedLines)) { |
388 | int i = 0; |
389 | unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1; |
390 | for (; I + 1 + i != E && |
391 | nsToken->TokenText == |
392 | getMatchingNamespaceTokenText(Line: I[i + 1], AnnotatedLines) && |
393 | openingLine == I[i + 1]->MatchingOpeningBlockLineIndex; |
394 | i++, --openingLine) { |
395 | // No space between consecutive braces. |
396 | I[i + 1]->First->SpacesRequiredBefore = |
397 | I[i]->Last->isNot(Kind: tok::r_brace); |
398 | |
399 | // Indent like the outer-most namespace. |
400 | IndentTracker.nextLine(Line: *I[i + 1]); |
401 | } |
402 | return i; |
403 | } |
404 | } |
405 | |
406 | const auto * = TheLine->getLastNonComment(); |
407 | assert(LastNonComment); |
408 | // FIXME: There are probably cases where we should use LastNonComment |
409 | // instead of TheLine->Last. |
410 | |
411 | // Try to merge a function block with left brace unwrapped. |
412 | if (LastNonComment->is(TT: TT_FunctionLBrace) && |
413 | TheLine->First != LastNonComment) { |
414 | return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0; |
415 | } |
416 | |
417 | // Try to merge a control statement block with left brace unwrapped. |
418 | if (TheLine->Last->is(Kind: tok::l_brace) && FirstNonComment != TheLine->Last && |
419 | (FirstNonComment->isOneOf(K1: tok::kw_if, K2: tok::kw_while, Ks: tok::kw_for, |
420 | Ks: TT_ForEachMacro) || |
421 | TheLine->startsWithExportBlock())) { |
422 | return Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never |
423 | ? tryMergeSimpleBlock(I, E, Limit) |
424 | : 0; |
425 | } |
426 | // Try to merge a control statement block with left brace wrapped. |
427 | if (NextLine.First->is(TT: TT_ControlStatementLBrace)) { |
428 | // If possible, merge the next line's wrapped left brace with the |
429 | // current line. Otherwise, leave it on the next line, as this is a |
430 | // multi-line control statement. |
431 | return Style.BraceWrapping.AfterControlStatement == |
432 | FormatStyle::BWACS_Always |
433 | ? tryMergeSimpleBlock(I, E, Limit) |
434 | : 0; |
435 | } |
436 | if (PreviousLine && TheLine->First->is(Kind: tok::l_brace)) { |
437 | switch (PreviousLine->First->Tok.getKind()) { |
438 | case tok::at: |
439 | // Don't merge block with left brace wrapped after ObjC special blocks. |
440 | if (PreviousLine->First->Next && |
441 | PreviousLine->First->Next->isOneOf(K1: tok::objc_autoreleasepool, |
442 | K2: tok::objc_synchronized)) { |
443 | return 0; |
444 | } |
445 | break; |
446 | |
447 | case tok::kw_case: |
448 | case tok::kw_default: |
449 | // Don't merge block with left brace wrapped after case labels. |
450 | return 0; |
451 | |
452 | default: |
453 | break; |
454 | } |
455 | } |
456 | |
457 | // Don't merge an empty template class or struct if SplitEmptyRecords |
458 | // is defined. |
459 | if (PreviousLine && Style.BraceWrapping.SplitEmptyRecord && |
460 | TheLine->Last->is(Kind: tok::l_brace) && PreviousLine->Last) { |
461 | const FormatToken *Previous = PreviousLine->Last; |
462 | if (Previous) { |
463 | if (Previous->is(Kind: tok::comment)) |
464 | Previous = Previous->getPreviousNonComment(); |
465 | if (Previous) { |
466 | if (Previous->is(Kind: tok::greater) && !PreviousLine->InPPDirective) |
467 | return 0; |
468 | if (Previous->is(Kind: tok::identifier)) { |
469 | const FormatToken *PreviousPrevious = |
470 | Previous->getPreviousNonComment(); |
471 | if (PreviousPrevious && |
472 | PreviousPrevious->isOneOf(K1: tok::kw_class, K2: tok::kw_struct)) { |
473 | return 0; |
474 | } |
475 | } |
476 | } |
477 | } |
478 | } |
479 | |
480 | if (TheLine->First->is(TT: TT_SwitchExpressionLabel)) { |
481 | return Style.AllowShortCaseExpressionOnASingleLine |
482 | ? tryMergeShortCaseLabels(I, E, Limit) |
483 | : 0; |
484 | } |
485 | |
486 | if (TheLine->Last->is(Kind: tok::l_brace)) { |
487 | bool ShouldMerge = false; |
488 | // Try to merge records. |
489 | if (TheLine->Last->is(TT: TT_EnumLBrace)) { |
490 | ShouldMerge = Style.AllowShortEnumsOnASingleLine; |
491 | } else if (TheLine->Last->is(TT: TT_CompoundRequirementLBrace)) { |
492 | ShouldMerge = Style.AllowShortCompoundRequirementOnASingleLine; |
493 | } else if (TheLine->Last->isOneOf(K1: TT_ClassLBrace, K2: TT_StructLBrace)) { |
494 | // NOTE: We use AfterClass (whereas AfterStruct exists) for both classes |
495 | // and structs, but it seems that wrapping is still handled correctly |
496 | // elsewhere. |
497 | ShouldMerge = !Style.BraceWrapping.AfterClass || |
498 | (NextLine.First->is(Kind: tok::r_brace) && |
499 | !Style.BraceWrapping.SplitEmptyRecord); |
500 | } else if (TheLine->InPPDirective || |
501 | !TheLine->First->isOneOf(K1: tok::kw_class, K2: tok::kw_enum, |
502 | Ks: tok::kw_struct)) { |
503 | // Try to merge a block with left brace unwrapped that wasn't yet |
504 | // covered. |
505 | ShouldMerge = !Style.BraceWrapping.AfterFunction || |
506 | (NextLine.First->is(Kind: tok::r_brace) && |
507 | !Style.BraceWrapping.SplitEmptyFunction); |
508 | } |
509 | return ShouldMerge ? tryMergeSimpleBlock(I, E, Limit) : 0; |
510 | } |
511 | |
512 | // Try to merge a function block with left brace wrapped. |
513 | if (NextLine.First->is(TT: TT_FunctionLBrace) && |
514 | Style.BraceWrapping.AfterFunction) { |
515 | if (NextLine.Last->is(TT: TT_LineComment)) |
516 | return 0; |
517 | |
518 | // Check for Limit <= 2 to account for the " {". |
519 | if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(Line: TheLine))) |
520 | return 0; |
521 | Limit -= 2; |
522 | |
523 | unsigned MergedLines = 0; |
524 | if (MergeShortFunctions || |
525 | (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty && |
526 | NextLine.First == NextLine.Last && I + 2 != E && |
527 | I[2]->First->is(Kind: tok::r_brace))) { |
528 | MergedLines = tryMergeSimpleBlock(I: I + 1, E, Limit); |
529 | // If we managed to merge the block, count the function header, which is |
530 | // on a separate line. |
531 | if (MergedLines > 0) |
532 | ++MergedLines; |
533 | } |
534 | return MergedLines; |
535 | } |
536 | auto IsElseLine = [&TheLine]() -> bool { |
537 | const FormatToken *First = TheLine->First; |
538 | if (First->is(Kind: tok::kw_else)) |
539 | return true; |
540 | |
541 | return First->is(Kind: tok::r_brace) && First->Next && |
542 | First->Next->is(Kind: tok::kw_else); |
543 | }; |
544 | if (TheLine->First->is(Kind: tok::kw_if) || |
545 | (IsElseLine() && (Style.AllowShortIfStatementsOnASingleLine == |
546 | FormatStyle::SIS_AllIfsAndElse))) { |
547 | return Style.AllowShortIfStatementsOnASingleLine |
548 | ? tryMergeSimpleControlStatement(I, E, Limit) |
549 | : 0; |
550 | } |
551 | if (TheLine->First->isOneOf(K1: tok::kw_for, K2: tok::kw_while, Ks: tok::kw_do, |
552 | Ks: TT_ForEachMacro)) { |
553 | return Style.AllowShortLoopsOnASingleLine |
554 | ? tryMergeSimpleControlStatement(I, E, Limit) |
555 | : 0; |
556 | } |
557 | if (TheLine->First->isOneOf(K1: tok::kw_case, K2: tok::kw_default)) { |
558 | return Style.AllowShortCaseLabelsOnASingleLine |
559 | ? tryMergeShortCaseLabels(I, E, Limit) |
560 | : 0; |
561 | } |
562 | if (TheLine->InPPDirective && |
563 | (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) { |
564 | return tryMergeSimplePPDirective(I, E, Limit); |
565 | } |
566 | return 0; |
567 | } |
568 | |
569 | unsigned |
570 | tryMergeSimplePPDirective(ArrayRef<AnnotatedLine *>::const_iterator I, |
571 | ArrayRef<AnnotatedLine *>::const_iterator E, |
572 | unsigned Limit) { |
573 | if (Limit == 0) |
574 | return 0; |
575 | if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline) |
576 | return 0; |
577 | if (1 + I[1]->Last->TotalLength > Limit) |
578 | return 0; |
579 | return 1; |
580 | } |
581 | |
582 | unsigned tryMergeNamespace(ArrayRef<AnnotatedLine *>::const_iterator I, |
583 | ArrayRef<AnnotatedLine *>::const_iterator E, |
584 | unsigned Limit) { |
585 | if (Limit == 0) |
586 | return 0; |
587 | |
588 | // The merging code is relative to the opening namespace brace, which could |
589 | // be either on the first or second line due to the brace wrapping rules. |
590 | const bool OpenBraceWrapped = Style.BraceWrapping.AfterNamespace; |
591 | const auto *BraceOpenLine = I + OpenBraceWrapped; |
592 | |
593 | assert(*BraceOpenLine); |
594 | if (BraceOpenLine[0]->Last->isNot(Kind: TT_NamespaceLBrace)) |
595 | return 0; |
596 | |
597 | if (std::distance(first: BraceOpenLine, last: E) <= 2) |
598 | return 0; |
599 | |
600 | if (BraceOpenLine[0]->Last->is(Kind: tok::comment)) |
601 | return 0; |
602 | |
603 | assert(BraceOpenLine[1]); |
604 | const auto &L1 = *BraceOpenLine[1]; |
605 | if (L1.InPPDirective != (*I)->InPPDirective || |
606 | (L1.InPPDirective && L1.First->HasUnescapedNewline)) { |
607 | return 0; |
608 | } |
609 | |
610 | assert(BraceOpenLine[2]); |
611 | const auto &L2 = *BraceOpenLine[2]; |
612 | if (L2.Type == LT_Invalid) |
613 | return 0; |
614 | |
615 | Limit = limitConsideringMacros(I: I + 1, E, Limit); |
616 | |
617 | const auto LinesToBeMerged = OpenBraceWrapped + 2; |
618 | if (!nextNLinesFitInto(I, E: I + LinesToBeMerged, Limit)) |
619 | return 0; |
620 | |
621 | // Check if it's a namespace inside a namespace, and call recursively if so. |
622 | // '3' is the sizes of the whitespace and closing brace for " _inner_ }". |
623 | if (L1.First->is(Kind: tok::kw_namespace)) { |
624 | if (L1.Last->is(Kind: tok::comment) || !Style.CompactNamespaces) |
625 | return 0; |
626 | |
627 | assert(Limit >= L1.Last->TotalLength + 3); |
628 | const auto InnerLimit = Limit - L1.Last->TotalLength - 3; |
629 | const auto MergedLines = |
630 | tryMergeNamespace(I: BraceOpenLine + 1, E, Limit: InnerLimit); |
631 | if (MergedLines == 0) |
632 | return 0; |
633 | const auto N = MergedLines + LinesToBeMerged; |
634 | // Check if there is even a line after the inner result. |
635 | if (std::distance(first: I, last: E) <= N) |
636 | return 0; |
637 | // Check that the line after the inner result starts with a closing brace |
638 | // which we are permitted to merge into one line. |
639 | if (I[N]->First->is(TT: TT_NamespaceRBrace) && |
640 | !I[N]->First->MustBreakBefore && |
641 | BraceOpenLine[MergedLines + 1]->Last->isNot(Kind: tok::comment) && |
642 | nextNLinesFitInto(I, E: I + N + 1, Limit)) { |
643 | return N; |
644 | } |
645 | return 0; |
646 | } |
647 | |
648 | // There's no inner namespace, so we are considering to merge at most one |
649 | // line. |
650 | |
651 | // The line which is in the namespace should end with semicolon. |
652 | if (L1.Last->isNot(Kind: tok::semi)) |
653 | return 0; |
654 | |
655 | // Last, check that the third line starts with a closing brace. |
656 | if (L2.First->isNot(Kind: TT_NamespaceRBrace) || L2.First->MustBreakBefore) |
657 | return 0; |
658 | |
659 | // If so, merge all lines. |
660 | return LinesToBeMerged; |
661 | } |
662 | |
663 | unsigned |
664 | tryMergeSimpleControlStatement(ArrayRef<AnnotatedLine *>::const_iterator I, |
665 | ArrayRef<AnnotatedLine *>::const_iterator E, |
666 | unsigned Limit) { |
667 | if (Limit == 0) |
668 | return 0; |
669 | if (Style.BraceWrapping.AfterControlStatement == |
670 | FormatStyle::BWACS_Always && |
671 | I[1]->First->is(Kind: tok::l_brace) && |
672 | Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) { |
673 | return 0; |
674 | } |
675 | if (I[1]->InPPDirective != (*I)->InPPDirective || |
676 | (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) { |
677 | return 0; |
678 | } |
679 | Limit = limitConsideringMacros(I: I + 1, E, Limit); |
680 | AnnotatedLine &Line = **I; |
681 | if (Line.First->isNot(Kind: tok::kw_do) && Line.First->isNot(Kind: tok::kw_else) && |
682 | Line.Last->isNot(Kind: tok::kw_else) && Line.Last->isNot(Kind: tok::r_paren)) { |
683 | return 0; |
684 | } |
685 | // Only merge `do while` if `do` is the only statement on the line. |
686 | if (Line.First->is(Kind: tok::kw_do) && Line.Last->isNot(Kind: tok::kw_do)) |
687 | return 0; |
688 | if (1 + I[1]->Last->TotalLength > Limit) |
689 | return 0; |
690 | // Don't merge with loops, ifs, a single semicolon or a line comment. |
691 | if (I[1]->First->isOneOf(K1: tok::semi, K2: tok::kw_if, Ks: tok::kw_for, Ks: tok::kw_while, |
692 | Ks: TT_ForEachMacro, Ks: TT_LineComment)) { |
693 | return 0; |
694 | } |
695 | // Only inline simple if's (no nested if or else), unless specified |
696 | if (Style.AllowShortIfStatementsOnASingleLine == |
697 | FormatStyle::SIS_WithoutElse) { |
698 | if (I + 2 != E && Line.startsWith(Tokens: tok::kw_if) && |
699 | I[2]->First->is(Kind: tok::kw_else)) { |
700 | return 0; |
701 | } |
702 | } |
703 | return 1; |
704 | } |
705 | |
706 | unsigned tryMergeShortCaseLabels(ArrayRef<AnnotatedLine *>::const_iterator I, |
707 | ArrayRef<AnnotatedLine *>::const_iterator E, |
708 | unsigned Limit) { |
709 | if (Limit == 0 || I + 1 == E || |
710 | I[1]->First->isOneOf(K1: tok::kw_case, K2: tok::kw_default)) { |
711 | return 0; |
712 | } |
713 | if (I[0]->Last->is(Kind: tok::l_brace) || I[1]->First->is(Kind: tok::l_brace)) |
714 | return 0; |
715 | unsigned NumStmts = 0; |
716 | unsigned Length = 0; |
717 | bool = false; |
718 | bool InPPDirective = I[0]->InPPDirective; |
719 | bool InMacroBody = I[0]->InMacroBody; |
720 | const unsigned Level = I[0]->Level; |
721 | for (; NumStmts < 3; ++NumStmts) { |
722 | if (I + 1 + NumStmts == E) |
723 | break; |
724 | const AnnotatedLine *Line = I[1 + NumStmts]; |
725 | if (Line->InPPDirective != InPPDirective) |
726 | break; |
727 | if (Line->InMacroBody != InMacroBody) |
728 | break; |
729 | if (Line->First->isOneOf(K1: tok::kw_case, K2: tok::kw_default, Ks: tok::r_brace)) |
730 | break; |
731 | if (Line->First->isOneOf(K1: tok::kw_if, K2: tok::kw_for, Ks: tok::kw_switch, |
732 | Ks: tok::kw_while) || |
733 | EndsWithComment) { |
734 | return 0; |
735 | } |
736 | if (Line->First->is(Kind: tok::comment)) { |
737 | if (Level != Line->Level) |
738 | return 0; |
739 | const auto *J = I + 2 + NumStmts; |
740 | for (; J != E; ++J) { |
741 | Line = *J; |
742 | if (Line->InPPDirective != InPPDirective) |
743 | break; |
744 | if (Line->First->isOneOf(K1: tok::kw_case, K2: tok::kw_default, Ks: tok::r_brace)) |
745 | break; |
746 | if (Line->First->isNot(Kind: tok::comment) || Level != Line->Level) |
747 | return 0; |
748 | } |
749 | break; |
750 | } |
751 | if (Line->Last->is(Kind: tok::comment)) |
752 | EndsWithComment = true; |
753 | Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space. |
754 | } |
755 | if (NumStmts == 0 || NumStmts == 3 || Length > Limit) |
756 | return 0; |
757 | return NumStmts; |
758 | } |
759 | |
760 | unsigned tryMergeSimpleBlock(ArrayRef<AnnotatedLine *>::const_iterator I, |
761 | ArrayRef<AnnotatedLine *>::const_iterator E, |
762 | unsigned Limit) { |
763 | // Don't merge with a preprocessor directive. |
764 | if (I[1]->Type == LT_PreprocessorDirective) |
765 | return 0; |
766 | |
767 | AnnotatedLine &Line = **I; |
768 | |
769 | // Don't merge ObjC @ keywords and methods. |
770 | // FIXME: If an option to allow short exception handling clauses on a single |
771 | // line is added, change this to not return for @try and friends. |
772 | if (!Style.isJava() && Line.First->isOneOf(K1: tok::at, K2: tok::minus, Ks: tok::plus)) |
773 | return 0; |
774 | |
775 | // Check that the current line allows merging. This depends on whether we |
776 | // are in a control flow statements as well as several style flags. |
777 | if (Line.First->is(Kind: tok::kw_case) || |
778 | (Line.First->Next && Line.First->Next->is(Kind: tok::kw_else))) { |
779 | return 0; |
780 | } |
781 | // default: in switch statement |
782 | if (Line.First->is(Kind: tok::kw_default)) { |
783 | const FormatToken *Tok = Line.First->getNextNonComment(); |
784 | if (Tok && Tok->is(Kind: tok::colon)) |
785 | return 0; |
786 | } |
787 | |
788 | auto IsCtrlStmt = [](const auto &Line) { |
789 | return Line.First->isOneOf(tok::kw_if, tok::kw_else, tok::kw_while, |
790 | tok::kw_do, tok::kw_for, TT_ForEachMacro); |
791 | }; |
792 | |
793 | const bool IsSplitBlock = |
794 | Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never || |
795 | (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Empty && |
796 | I[1]->First->isNot(Kind: tok::r_brace)); |
797 | |
798 | if (IsCtrlStmt(Line) || |
799 | Line.First->isOneOf(K1: tok::kw_try, K2: tok::kw___try, Ks: tok::kw_catch, |
800 | Ks: tok::kw___finally, Ks: tok::r_brace, |
801 | Ks: Keywords.kw___except) || |
802 | Line.startsWithExportBlock()) { |
803 | if (IsSplitBlock) |
804 | return 0; |
805 | // Don't merge when we can't except the case when |
806 | // the control statement block is empty |
807 | if (!Style.AllowShortIfStatementsOnASingleLine && |
808 | Line.First->isOneOf(K1: tok::kw_if, K2: tok::kw_else) && |
809 | !Style.BraceWrapping.AfterControlStatement && |
810 | I[1]->First->isNot(Kind: tok::r_brace)) { |
811 | return 0; |
812 | } |
813 | if (!Style.AllowShortIfStatementsOnASingleLine && |
814 | Line.First->isOneOf(K1: tok::kw_if, K2: tok::kw_else) && |
815 | Style.BraceWrapping.AfterControlStatement == |
816 | FormatStyle::BWACS_Always && |
817 | I + 2 != E && I[2]->First->isNot(Kind: tok::r_brace)) { |
818 | return 0; |
819 | } |
820 | if (!Style.AllowShortLoopsOnASingleLine && |
821 | Line.First->isOneOf(K1: tok::kw_while, K2: tok::kw_do, Ks: tok::kw_for, |
822 | Ks: TT_ForEachMacro) && |
823 | !Style.BraceWrapping.AfterControlStatement && |
824 | I[1]->First->isNot(Kind: tok::r_brace)) { |
825 | return 0; |
826 | } |
827 | if (!Style.AllowShortLoopsOnASingleLine && |
828 | Line.First->isOneOf(K1: tok::kw_while, K2: tok::kw_do, Ks: tok::kw_for, |
829 | Ks: TT_ForEachMacro) && |
830 | Style.BraceWrapping.AfterControlStatement == |
831 | FormatStyle::BWACS_Always && |
832 | I + 2 != E && I[2]->First->isNot(Kind: tok::r_brace)) { |
833 | return 0; |
834 | } |
835 | // FIXME: Consider an option to allow short exception handling clauses on |
836 | // a single line. |
837 | // FIXME: This isn't covered by tests. |
838 | // FIXME: For catch, __except, __finally the first token on the line |
839 | // is '}', so this isn't correct here. |
840 | if (Line.First->isOneOf(K1: tok::kw_try, K2: tok::kw___try, Ks: tok::kw_catch, |
841 | Ks: Keywords.kw___except, Ks: tok::kw___finally)) { |
842 | return 0; |
843 | } |
844 | } |
845 | |
846 | if (Line.endsWith(Tokens: tok::l_brace)) { |
847 | if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never && |
848 | Line.First->is(TT: TT_BlockLBrace)) { |
849 | return 0; |
850 | } |
851 | |
852 | if (IsSplitBlock && Line.First == Line.Last && |
853 | I > AnnotatedLines.begin() && |
854 | (I[-1]->endsWith(Tokens: tok::kw_else) || IsCtrlStmt(*I[-1]))) { |
855 | return 0; |
856 | } |
857 | FormatToken *Tok = I[1]->First; |
858 | auto ShouldMerge = [Tok]() { |
859 | if (Tok->isNot(Kind: tok::r_brace) || Tok->MustBreakBefore) |
860 | return false; |
861 | const FormatToken *Next = Tok->getNextNonComment(); |
862 | return !Next || Next->is(Kind: tok::semi); |
863 | }; |
864 | |
865 | if (ShouldMerge()) { |
866 | // We merge empty blocks even if the line exceeds the column limit. |
867 | Tok->SpacesRequiredBefore = |
868 | (Style.SpaceInEmptyBlock || Line.Last->is(Kind: tok::comment)) ? 1 : 0; |
869 | Tok->CanBreakBefore = true; |
870 | return 1; |
871 | } else if (Limit != 0 && !Line.startsWithNamespace() && |
872 | !startsExternCBlock(Line)) { |
873 | // We don't merge short records. |
874 | if (isRecordLBrace(Tok: *Line.Last)) |
875 | return 0; |
876 | |
877 | // Check that we still have three lines and they fit into the limit. |
878 | if (I + 2 == E || I[2]->Type == LT_Invalid) |
879 | return 0; |
880 | Limit = limitConsideringMacros(I: I + 2, E, Limit); |
881 | |
882 | if (!nextTwoLinesFitInto(I, Limit)) |
883 | return 0; |
884 | |
885 | // Second, check that the next line does not contain any braces - if it |
886 | // does, readability declines when putting it into a single line. |
887 | if (I[1]->Last->is(TT: TT_LineComment)) |
888 | return 0; |
889 | do { |
890 | if (Tok->is(Kind: tok::l_brace) && Tok->isNot(Kind: BK_BracedInit)) |
891 | return 0; |
892 | Tok = Tok->Next; |
893 | } while (Tok); |
894 | |
895 | // Last, check that the third line starts with a closing brace. |
896 | Tok = I[2]->First; |
897 | if (Tok->isNot(Kind: tok::r_brace)) |
898 | return 0; |
899 | |
900 | // Don't merge "if (a) { .. } else {". |
901 | if (Tok->Next && Tok->Next->is(Kind: tok::kw_else)) |
902 | return 0; |
903 | |
904 | // Don't merge a trailing multi-line control statement block like: |
905 | // } else if (foo && |
906 | // bar) |
907 | // { <-- current Line |
908 | // baz(); |
909 | // } |
910 | if (Line.First == Line.Last && |
911 | Line.First->is(TT: TT_ControlStatementLBrace) && |
912 | Style.BraceWrapping.AfterControlStatement == |
913 | FormatStyle::BWACS_MultiLine) { |
914 | return 0; |
915 | } |
916 | |
917 | return 2; |
918 | } |
919 | } else if (I[1]->First->is(Kind: tok::l_brace)) { |
920 | if (I[1]->Last->is(TT: TT_LineComment)) |
921 | return 0; |
922 | |
923 | // Check for Limit <= 2 to account for the " {". |
924 | if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(Line: *I))) |
925 | return 0; |
926 | Limit -= 2; |
927 | unsigned MergedLines = 0; |
928 | if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never || |
929 | (I[1]->First == I[1]->Last && I + 2 != E && |
930 | I[2]->First->is(Kind: tok::r_brace))) { |
931 | MergedLines = tryMergeSimpleBlock(I: I + 1, E, Limit); |
932 | // If we managed to merge the block, count the statement header, which |
933 | // is on a separate line. |
934 | if (MergedLines > 0) |
935 | ++MergedLines; |
936 | } |
937 | return MergedLines; |
938 | } |
939 | return 0; |
940 | } |
941 | |
942 | /// Returns the modified column limit for \p I if it is inside a macro and |
943 | /// needs a trailing '\'. |
944 | unsigned limitConsideringMacros(ArrayRef<AnnotatedLine *>::const_iterator I, |
945 | ArrayRef<AnnotatedLine *>::const_iterator E, |
946 | unsigned Limit) { |
947 | if (I[0]->InPPDirective && I + 1 != E && |
948 | !I[1]->First->HasUnescapedNewline && I[1]->First->isNot(Kind: tok::eof)) { |
949 | return Limit < 2 ? 0 : Limit - 2; |
950 | } |
951 | return Limit; |
952 | } |
953 | |
954 | bool nextTwoLinesFitInto(ArrayRef<AnnotatedLine *>::const_iterator I, |
955 | unsigned Limit) { |
956 | if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore) |
957 | return false; |
958 | return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit; |
959 | } |
960 | |
961 | bool nextNLinesFitInto(ArrayRef<AnnotatedLine *>::const_iterator I, |
962 | ArrayRef<AnnotatedLine *>::const_iterator E, |
963 | unsigned Limit) { |
964 | unsigned JoinedLength = 0; |
965 | for (const auto *J = I + 1; J != E; ++J) { |
966 | if ((*J)->First->MustBreakBefore) |
967 | return false; |
968 | |
969 | JoinedLength += 1 + (*J)->Last->TotalLength; |
970 | if (JoinedLength > Limit) |
971 | return false; |
972 | } |
973 | return true; |
974 | } |
975 | |
976 | bool containsMustBreak(const AnnotatedLine *Line) { |
977 | assert(Line->First); |
978 | // Ignore the first token, because in this situation, it applies more to the |
979 | // last token of the previous line. |
980 | for (const FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) |
981 | if (Tok->MustBreakBefore) |
982 | return true; |
983 | return false; |
984 | } |
985 | |
986 | void join(AnnotatedLine &A, const AnnotatedLine &B) { |
987 | assert(!A.Last->Next); |
988 | assert(!B.First->Previous); |
989 | if (B.Affected) |
990 | A.Affected = true; |
991 | A.Last->Next = B.First; |
992 | B.First->Previous = A.Last; |
993 | B.First->CanBreakBefore = true; |
994 | unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore; |
995 | for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) { |
996 | Tok->TotalLength += LengthA; |
997 | A.Last = Tok; |
998 | } |
999 | } |
1000 | |
1001 | const FormatStyle &Style; |
1002 | const AdditionalKeywords &Keywords; |
1003 | const ArrayRef<AnnotatedLine *>::const_iterator End; |
1004 | |
1005 | ArrayRef<AnnotatedLine *>::const_iterator Next; |
1006 | const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines; |
1007 | }; |
1008 | |
1009 | static void markFinalized(FormatToken *Tok) { |
1010 | if (Tok->is(Kind: tok::hash) && !Tok->Previous && Tok->Next && |
1011 | Tok->Next->isOneOf(K1: tok::pp_if, K2: tok::pp_ifdef, Ks: tok::pp_ifndef, |
1012 | Ks: tok::pp_elif, Ks: tok::pp_elifdef, Ks: tok::pp_elifndef, |
1013 | Ks: tok::pp_else, Ks: tok::pp_endif)) { |
1014 | Tok = Tok->Next; |
1015 | } |
1016 | for (; Tok; Tok = Tok->Next) { |
1017 | if (Tok->MacroCtx && Tok->MacroCtx->Role == MR_ExpandedArg) { |
1018 | // In the first pass we format all macro arguments in the expanded token |
1019 | // stream. Instead of finalizing the macro arguments, we mark that they |
1020 | // will be modified as unexpanded arguments (as part of the macro call |
1021 | // formatting) in the next pass. |
1022 | Tok->MacroCtx->Role = MR_UnexpandedArg; |
1023 | // Reset whether spaces or a line break are required before this token, as |
1024 | // that is context dependent, and that context may change when formatting |
1025 | // the macro call. For example, given M(x) -> 2 * x, and the macro call |
1026 | // M(var), the token 'var' will have SpacesRequiredBefore = 1 after being |
1027 | // formatted as part of the expanded macro, but SpacesRequiredBefore = 0 |
1028 | // for its position within the macro call. |
1029 | Tok->SpacesRequiredBefore = 0; |
1030 | if (!Tok->MustBreakBeforeFinalized) |
1031 | Tok->MustBreakBefore = 0; |
1032 | } else { |
1033 | Tok->Finalized = true; |
1034 | } |
1035 | } |
1036 | } |
1037 | |
1038 | #ifndef NDEBUG |
1039 | static void printLineState(const LineState &State) { |
1040 | llvm::dbgs() << "State: " ; |
1041 | for (const ParenState &P : State.Stack) { |
1042 | llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F" ) << "|" << P.Indent << "|" |
1043 | << P.LastSpace << "|" << P.NestedBlockIndent << " " ; |
1044 | } |
1045 | llvm::dbgs() << State.NextToken->TokenText << "\n" ; |
1046 | } |
1047 | #endif |
1048 | |
1049 | /// Base class for classes that format one \c AnnotatedLine. |
1050 | class LineFormatter { |
1051 | public: |
1052 | LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces, |
1053 | const FormatStyle &Style, |
1054 | UnwrappedLineFormatter *BlockFormatter) |
1055 | : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style), |
1056 | BlockFormatter(BlockFormatter) {} |
1057 | virtual ~LineFormatter() {} |
1058 | |
1059 | /// Formats an \c AnnotatedLine and returns the penalty. |
1060 | /// |
1061 | /// If \p DryRun is \c false, directly applies the changes. |
1062 | virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, |
1063 | unsigned FirstStartColumn, bool DryRun) = 0; |
1064 | |
1065 | protected: |
1066 | /// If the \p State's next token is an r_brace closing a nested block, |
1067 | /// format the nested block before it. |
1068 | /// |
1069 | /// Returns \c true if all children could be placed successfully and adapts |
1070 | /// \p Penalty as well as \p State. If \p DryRun is false, also directly |
1071 | /// creates changes using \c Whitespaces. |
1072 | /// |
1073 | /// The crucial idea here is that children always get formatted upon |
1074 | /// encountering the closing brace right after the nested block. Now, if we |
1075 | /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is |
1076 | /// \c false), the entire block has to be kept on the same line (which is only |
1077 | /// possible if it fits on the line, only contains a single statement, etc. |
1078 | /// |
1079 | /// If \p NewLine is true, we format the nested block on separate lines, i.e. |
1080 | /// break after the "{", format all lines with correct indentation and the put |
1081 | /// the closing "}" on yet another new line. |
1082 | /// |
1083 | /// This enables us to keep the simple structure of the |
1084 | /// \c UnwrappedLineFormatter, where we only have two options for each token: |
1085 | /// break or don't break. |
1086 | bool formatChildren(LineState &State, bool NewLine, bool DryRun, |
1087 | unsigned &Penalty) { |
1088 | const FormatToken *LBrace = State.NextToken->getPreviousNonComment(); |
1089 | bool HasLBrace = LBrace && LBrace->is(Kind: tok::l_brace) && LBrace->is(BBK: BK_Block); |
1090 | FormatToken &Previous = *State.NextToken->Previous; |
1091 | if (Previous.Children.size() == 0 || (!HasLBrace && !LBrace->MacroParent)) { |
1092 | // The previous token does not open a block. Nothing to do. We don't |
1093 | // assert so that we can simply call this function for all tokens. |
1094 | return true; |
1095 | } |
1096 | |
1097 | if (NewLine || Previous.MacroParent) { |
1098 | const ParenState &P = State.Stack.back(); |
1099 | |
1100 | int AdditionalIndent = |
1101 | P.Indent - Previous.Children[0]->Level * Style.IndentWidth; |
1102 | Penalty += |
1103 | BlockFormatter->format(Lines: Previous.Children, DryRun, AdditionalIndent, |
1104 | /*FixBadIndentation=*/true); |
1105 | return true; |
1106 | } |
1107 | |
1108 | if (Previous.Children[0]->First->MustBreakBefore) |
1109 | return false; |
1110 | |
1111 | // Cannot merge into one line if this line ends on a comment. |
1112 | if (Previous.is(Kind: tok::comment)) |
1113 | return false; |
1114 | |
1115 | // Cannot merge multiple statements into a single line. |
1116 | if (Previous.Children.size() > 1) |
1117 | return false; |
1118 | |
1119 | const AnnotatedLine *Child = Previous.Children[0]; |
1120 | // We can't put the closing "}" on a line with a trailing comment. |
1121 | if (Child->Last->isTrailingComment()) |
1122 | return false; |
1123 | |
1124 | // If the child line exceeds the column limit, we wouldn't want to merge it. |
1125 | // We add +2 for the trailing " }". |
1126 | if (Style.ColumnLimit > 0 && |
1127 | Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) { |
1128 | return false; |
1129 | } |
1130 | |
1131 | if (!DryRun) { |
1132 | Whitespaces->replaceWhitespace( |
1133 | Tok&: *Child->First, /*Newlines=*/0, /*Spaces=*/1, |
1134 | /*StartOfTokenColumn=*/State.Column, /*IsAligned=*/false, |
1135 | InPPDirective: State.Line->InPPDirective); |
1136 | } |
1137 | Penalty += |
1138 | formatLine(Line: *Child, FirstIndent: State.Column + 1, /*FirstStartColumn=*/0, DryRun); |
1139 | if (!DryRun) |
1140 | markFinalized(Tok: Child->First); |
1141 | |
1142 | State.Column += 1 + Child->Last->TotalLength; |
1143 | return true; |
1144 | } |
1145 | |
1146 | ContinuationIndenter *Indenter; |
1147 | |
1148 | private: |
1149 | WhitespaceManager *Whitespaces; |
1150 | const FormatStyle &Style; |
1151 | UnwrappedLineFormatter *BlockFormatter; |
1152 | }; |
1153 | |
1154 | /// Formatter that keeps the existing line breaks. |
1155 | class NoColumnLimitLineFormatter : public LineFormatter { |
1156 | public: |
1157 | NoColumnLimitLineFormatter(ContinuationIndenter *Indenter, |
1158 | WhitespaceManager *Whitespaces, |
1159 | const FormatStyle &Style, |
1160 | UnwrappedLineFormatter *BlockFormatter) |
1161 | : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} |
1162 | |
1163 | /// Formats the line, simply keeping all of the input's line breaking |
1164 | /// decisions. |
1165 | unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, |
1166 | unsigned FirstStartColumn, bool DryRun) override { |
1167 | assert(!DryRun); |
1168 | LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn, |
1169 | Line: &Line, /*DryRun=*/false); |
1170 | while (State.NextToken) { |
1171 | bool Newline = |
1172 | Indenter->mustBreak(State) || |
1173 | (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0); |
1174 | unsigned Penalty = 0; |
1175 | formatChildren(State, NewLine: Newline, /*DryRun=*/false, Penalty); |
1176 | Indenter->addTokenToState(State, Newline, /*DryRun=*/false); |
1177 | } |
1178 | return 0; |
1179 | } |
1180 | }; |
1181 | |
1182 | /// Formatter that puts all tokens into a single line without breaks. |
1183 | class NoLineBreakFormatter : public LineFormatter { |
1184 | public: |
1185 | NoLineBreakFormatter(ContinuationIndenter *Indenter, |
1186 | WhitespaceManager *Whitespaces, const FormatStyle &Style, |
1187 | UnwrappedLineFormatter *BlockFormatter) |
1188 | : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} |
1189 | |
1190 | /// Puts all tokens into a single line. |
1191 | unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, |
1192 | unsigned FirstStartColumn, bool DryRun) override { |
1193 | unsigned Penalty = 0; |
1194 | LineState State = |
1195 | Indenter->getInitialState(FirstIndent, FirstStartColumn, Line: &Line, DryRun); |
1196 | while (State.NextToken) { |
1197 | formatChildren(State, /*NewLine=*/false, DryRun, Penalty); |
1198 | Indenter->addTokenToState( |
1199 | State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun); |
1200 | } |
1201 | return Penalty; |
1202 | } |
1203 | }; |
1204 | |
1205 | /// Finds the best way to break lines. |
1206 | class OptimizingLineFormatter : public LineFormatter { |
1207 | public: |
1208 | OptimizingLineFormatter(ContinuationIndenter *Indenter, |
1209 | WhitespaceManager *Whitespaces, |
1210 | const FormatStyle &Style, |
1211 | UnwrappedLineFormatter *BlockFormatter) |
1212 | : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} |
1213 | |
1214 | /// Formats the line by finding the best line breaks with line lengths |
1215 | /// below the column limit. |
1216 | unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, |
1217 | unsigned FirstStartColumn, bool DryRun) override { |
1218 | LineState State = |
1219 | Indenter->getInitialState(FirstIndent, FirstStartColumn, Line: &Line, DryRun); |
1220 | |
1221 | // If the ObjC method declaration does not fit on a line, we should format |
1222 | // it with one arg per line. |
1223 | if (State.Line->Type == LT_ObjCMethodDecl) |
1224 | State.Stack.back().BreakBeforeParameter = true; |
1225 | |
1226 | // Find best solution in solution space. |
1227 | return analyzeSolutionSpace(InitialState&: State, DryRun); |
1228 | } |
1229 | |
1230 | private: |
1231 | struct CompareLineStatePointers { |
1232 | bool operator()(LineState *obj1, LineState *obj2) const { |
1233 | return *obj1 < *obj2; |
1234 | } |
1235 | }; |
1236 | |
1237 | /// A pair of <penalty, count> that is used to prioritize the BFS on. |
1238 | /// |
1239 | /// In case of equal penalties, we want to prefer states that were inserted |
1240 | /// first. During state generation we make sure that we insert states first |
1241 | /// that break the line as late as possible. |
1242 | typedef std::pair<unsigned, unsigned> OrderedPenalty; |
1243 | |
1244 | /// An edge in the solution space from \c Previous->State to \c State, |
1245 | /// inserting a newline dependent on the \c NewLine. |
1246 | struct StateNode { |
1247 | StateNode(const LineState &State, bool NewLine, StateNode *Previous) |
1248 | : State(State), NewLine(NewLine), Previous(Previous) {} |
1249 | LineState State; |
1250 | bool NewLine; |
1251 | StateNode *Previous; |
1252 | }; |
1253 | |
1254 | /// An item in the prioritized BFS search queue. The \c StateNode's |
1255 | /// \c State has the given \c OrderedPenalty. |
1256 | typedef std::pair<OrderedPenalty, StateNode *> QueueItem; |
1257 | |
1258 | /// The BFS queue type. |
1259 | typedef std::priority_queue<QueueItem, SmallVector<QueueItem>, |
1260 | std::greater<QueueItem>> |
1261 | QueueType; |
1262 | |
1263 | /// Analyze the entire solution space starting from \p InitialState. |
1264 | /// |
1265 | /// This implements a variant of Dijkstra's algorithm on the graph that spans |
1266 | /// the solution space (\c LineStates are the nodes). The algorithm tries to |
1267 | /// find the shortest path (the one with lowest penalty) from \p InitialState |
1268 | /// to a state where all tokens are placed. Returns the penalty. |
1269 | /// |
1270 | /// If \p DryRun is \c false, directly applies the changes. |
1271 | unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) { |
1272 | std::set<LineState *, CompareLineStatePointers> Seen; |
1273 | |
1274 | // Increasing count of \c StateNode items we have created. This is used to |
1275 | // create a deterministic order independent of the container. |
1276 | unsigned Count = 0; |
1277 | QueueType Queue; |
1278 | |
1279 | // Insert start element into queue. |
1280 | StateNode *RootNode = |
1281 | new (Allocator.Allocate()) StateNode(InitialState, false, nullptr); |
1282 | Queue.push(x: QueueItem(OrderedPenalty(0, Count), RootNode)); |
1283 | ++Count; |
1284 | |
1285 | unsigned Penalty = 0; |
1286 | |
1287 | // While not empty, take first element and follow edges. |
1288 | while (!Queue.empty()) { |
1289 | // Quit if we still haven't found a solution by now. |
1290 | if (Count > 25'000'000) |
1291 | return 0; |
1292 | |
1293 | Penalty = Queue.top().first.first; |
1294 | StateNode *Node = Queue.top().second; |
1295 | if (!Node->State.NextToken) { |
1296 | LLVM_DEBUG(llvm::dbgs() |
1297 | << "\n---\nPenalty for line: " << Penalty << "\n" ); |
1298 | break; |
1299 | } |
1300 | Queue.pop(); |
1301 | |
1302 | // Cut off the analysis of certain solutions if the analysis gets too |
1303 | // complex. See description of IgnoreStackForComparison. |
1304 | if (Count > 50'000) |
1305 | Node->State.IgnoreStackForComparison = true; |
1306 | |
1307 | if (!Seen.insert(x: &Node->State).second) { |
1308 | // State already examined with lower penalty. |
1309 | continue; |
1310 | } |
1311 | |
1312 | FormatDecision LastFormat = Node->State.NextToken->getDecision(); |
1313 | if (LastFormat == FD_Unformatted || LastFormat == FD_Continue) |
1314 | addNextStateToQueue(Penalty, PreviousNode: Node, /*NewLine=*/false, Count: &Count, Queue: &Queue); |
1315 | if (LastFormat == FD_Unformatted || LastFormat == FD_Break) |
1316 | addNextStateToQueue(Penalty, PreviousNode: Node, /*NewLine=*/true, Count: &Count, Queue: &Queue); |
1317 | } |
1318 | |
1319 | if (Queue.empty()) { |
1320 | // We were unable to find a solution, do nothing. |
1321 | // FIXME: Add diagnostic? |
1322 | LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n" ); |
1323 | return 0; |
1324 | } |
1325 | |
1326 | // Reconstruct the solution. |
1327 | if (!DryRun) |
1328 | reconstructPath(State&: InitialState, Best: Queue.top().second); |
1329 | |
1330 | LLVM_DEBUG(llvm::dbgs() |
1331 | << "Total number of analyzed states: " << Count << "\n" ); |
1332 | LLVM_DEBUG(llvm::dbgs() << "---\n" ); |
1333 | |
1334 | return Penalty; |
1335 | } |
1336 | |
1337 | /// Add the following state to the analysis queue \c Queue. |
1338 | /// |
1339 | /// Assume the current state is \p PreviousNode and has been reached with a |
1340 | /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true. |
1341 | void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode, |
1342 | bool NewLine, unsigned *Count, QueueType *Queue) { |
1343 | if (NewLine && !Indenter->canBreak(State: PreviousNode->State)) |
1344 | return; |
1345 | if (!NewLine && Indenter->mustBreak(State: PreviousNode->State)) |
1346 | return; |
1347 | |
1348 | StateNode *Node = new (Allocator.Allocate()) |
1349 | StateNode(PreviousNode->State, NewLine, PreviousNode); |
1350 | if (!formatChildren(State&: Node->State, NewLine, /*DryRun=*/true, Penalty)) |
1351 | return; |
1352 | |
1353 | Penalty += Indenter->addTokenToState(State&: Node->State, Newline: NewLine, DryRun: true); |
1354 | |
1355 | Queue->push(x: QueueItem(OrderedPenalty(Penalty, *Count), Node)); |
1356 | ++(*Count); |
1357 | } |
1358 | |
1359 | /// Applies the best formatting by reconstructing the path in the |
1360 | /// solution space that leads to \c Best. |
1361 | void reconstructPath(LineState &State, StateNode *Best) { |
1362 | llvm::SmallVector<StateNode *> Path; |
1363 | // We do not need a break before the initial token. |
1364 | while (Best->Previous) { |
1365 | Path.push_back(Elt: Best); |
1366 | Best = Best->Previous; |
1367 | } |
1368 | for (const auto &Node : llvm::reverse(C&: Path)) { |
1369 | unsigned Penalty = 0; |
1370 | formatChildren(State, NewLine: Node->NewLine, /*DryRun=*/false, Penalty); |
1371 | Penalty += Indenter->addTokenToState(State, Newline: Node->NewLine, DryRun: false); |
1372 | |
1373 | LLVM_DEBUG({ |
1374 | printLineState(Node->Previous->State); |
1375 | if (Node->NewLine) { |
1376 | llvm::dbgs() << "Penalty for placing " |
1377 | << Node->Previous->State.NextToken->Tok.getName() |
1378 | << " on a new line: " << Penalty << "\n" ; |
1379 | } |
1380 | }); |
1381 | } |
1382 | } |
1383 | |
1384 | llvm::SpecificBumpPtrAllocator<StateNode> Allocator; |
1385 | }; |
1386 | |
1387 | } // anonymous namespace |
1388 | |
1389 | unsigned UnwrappedLineFormatter::format( |
1390 | const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun, |
1391 | int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn, |
1392 | unsigned NextStartColumn, unsigned LastStartColumn) { |
1393 | LineJoiner Joiner(Style, Keywords, Lines); |
1394 | |
1395 | // Try to look up already computed penalty in DryRun-mode. |
1396 | std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey( |
1397 | &Lines, AdditionalIndent); |
1398 | auto CacheIt = PenaltyCache.find(x: CacheKey); |
1399 | if (DryRun && CacheIt != PenaltyCache.end()) |
1400 | return CacheIt->second; |
1401 | |
1402 | assert(!Lines.empty()); |
1403 | unsigned Penalty = 0; |
1404 | LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level, |
1405 | AdditionalIndent); |
1406 | const AnnotatedLine *PrevPrevLine = nullptr; |
1407 | const AnnotatedLine *PreviousLine = nullptr; |
1408 | const AnnotatedLine *NextLine = nullptr; |
1409 | |
1410 | // The minimum level of consecutive lines that have been formatted. |
1411 | unsigned RangeMinLevel = UINT_MAX; |
1412 | |
1413 | bool FirstLine = true; |
1414 | for (const AnnotatedLine *Line = |
1415 | Joiner.getNextMergedLine(DryRun, IndentTracker); |
1416 | Line; PrevPrevLine = PreviousLine, PreviousLine = Line, Line = NextLine, |
1417 | FirstLine = false) { |
1418 | assert(Line->First); |
1419 | const AnnotatedLine &TheLine = *Line; |
1420 | unsigned Indent = IndentTracker.getIndent(); |
1421 | |
1422 | // We continue formatting unchanged lines to adjust their indent, e.g. if a |
1423 | // scope was added. However, we need to carefully stop doing this when we |
1424 | // exit the scope of affected lines to prevent indenting the entire |
1425 | // remaining file if it currently missing a closing brace. |
1426 | bool PreviousRBrace = |
1427 | PreviousLine && PreviousLine->startsWith(Tokens: tok::r_brace); |
1428 | bool ContinueFormatting = |
1429 | TheLine.Level > RangeMinLevel || |
1430 | (TheLine.Level == RangeMinLevel && !PreviousRBrace && |
1431 | !TheLine.startsWith(Tokens: TT_NamespaceRBrace)); |
1432 | |
1433 | bool FixIndentation = (FixBadIndentation || ContinueFormatting) && |
1434 | Indent != TheLine.First->OriginalColumn; |
1435 | bool ShouldFormat = TheLine.Affected || FixIndentation; |
1436 | // We cannot format this line; if the reason is that the line had a |
1437 | // parsing error, remember that. |
1438 | if (ShouldFormat && TheLine.Type == LT_Invalid && Status) { |
1439 | Status->FormatComplete = false; |
1440 | Status->Line = |
1441 | SourceMgr.getSpellingLineNumber(Loc: TheLine.First->Tok.getLocation()); |
1442 | } |
1443 | |
1444 | if (ShouldFormat && TheLine.Type != LT_Invalid) { |
1445 | if (!DryRun) { |
1446 | bool LastLine = TheLine.First->is(Kind: tok::eof); |
1447 | formatFirstToken(Line: TheLine, PreviousLine, PrevPrevLine, Lines, Indent, |
1448 | NewlineIndent: LastLine ? LastStartColumn : NextStartColumn + Indent); |
1449 | } |
1450 | |
1451 | NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker); |
1452 | unsigned ColumnLimit = getColumnLimit(InPPDirective: TheLine.InPPDirective, NextLine); |
1453 | bool FitsIntoOneLine = |
1454 | !TheLine.ContainsMacroCall && |
1455 | (TheLine.Last->TotalLength + Indent <= ColumnLimit || |
1456 | (TheLine.Type == LT_ImportStatement && |
1457 | (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) || |
1458 | (Style.isCSharp() && |
1459 | TheLine.InPPDirective)); // don't split #regions in C# |
1460 | if (Style.ColumnLimit == 0) { |
1461 | NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this) |
1462 | .formatLine(Line: TheLine, FirstIndent: NextStartColumn + Indent, |
1463 | FirstStartColumn: FirstLine ? FirstStartColumn : 0, DryRun); |
1464 | } else if (FitsIntoOneLine) { |
1465 | Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this) |
1466 | .formatLine(Line: TheLine, FirstIndent: NextStartColumn + Indent, |
1467 | FirstStartColumn: FirstLine ? FirstStartColumn : 0, DryRun); |
1468 | } else { |
1469 | Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this) |
1470 | .formatLine(Line: TheLine, FirstIndent: NextStartColumn + Indent, |
1471 | FirstStartColumn: FirstLine ? FirstStartColumn : 0, DryRun); |
1472 | } |
1473 | RangeMinLevel = std::min(a: RangeMinLevel, b: TheLine.Level); |
1474 | } else { |
1475 | // If no token in the current line is affected, we still need to format |
1476 | // affected children. |
1477 | if (TheLine.ChildrenAffected) { |
1478 | for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) |
1479 | if (!Tok->Children.empty()) |
1480 | format(Lines: Tok->Children, DryRun); |
1481 | } |
1482 | |
1483 | // Adapt following lines on the current indent level to the same level |
1484 | // unless the current \c AnnotatedLine is not at the beginning of a line. |
1485 | bool StartsNewLine = |
1486 | TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst; |
1487 | if (StartsNewLine) |
1488 | IndentTracker.adjustToUnmodifiedLine(Line: TheLine); |
1489 | if (!DryRun) { |
1490 | bool ReformatLeadingWhitespace = |
1491 | StartsNewLine && ((PreviousLine && PreviousLine->Affected) || |
1492 | TheLine.LeadingEmptyLinesAffected); |
1493 | // Format the first token. |
1494 | if (ReformatLeadingWhitespace) { |
1495 | formatFirstToken(Line: TheLine, PreviousLine, PrevPrevLine, Lines, |
1496 | Indent: TheLine.First->OriginalColumn, |
1497 | NewlineIndent: TheLine.First->OriginalColumn); |
1498 | } else { |
1499 | Whitespaces->addUntouchableToken(Tok: *TheLine.First, |
1500 | InPPDirective: TheLine.InPPDirective); |
1501 | } |
1502 | |
1503 | // Notify the WhitespaceManager about the unchanged whitespace. |
1504 | for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next) |
1505 | Whitespaces->addUntouchableToken(Tok: *Tok, InPPDirective: TheLine.InPPDirective); |
1506 | } |
1507 | NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker); |
1508 | RangeMinLevel = UINT_MAX; |
1509 | } |
1510 | if (!DryRun) |
1511 | markFinalized(Tok: TheLine.First); |
1512 | } |
1513 | PenaltyCache[CacheKey] = Penalty; |
1514 | return Penalty; |
1515 | } |
1516 | |
1517 | static auto computeNewlines(const AnnotatedLine &Line, |
1518 | const AnnotatedLine *PreviousLine, |
1519 | const AnnotatedLine *PrevPrevLine, |
1520 | const SmallVectorImpl<AnnotatedLine *> &Lines, |
1521 | const FormatStyle &Style) { |
1522 | const auto &RootToken = *Line.First; |
1523 | auto Newlines = |
1524 | std::min(a: RootToken.NewlinesBefore, b: Style.MaxEmptyLinesToKeep + 1); |
1525 | // Remove empty lines before "}" where applicable. |
1526 | if (RootToken.is(Kind: tok::r_brace) && |
1527 | (!RootToken.Next || |
1528 | (RootToken.Next->is(Kind: tok::semi) && !RootToken.Next->Next)) && |
1529 | // Do not remove empty lines before namespace closing "}". |
1530 | !getNamespaceToken(Line: &Line, AnnotatedLines: Lines)) { |
1531 | Newlines = std::min(a: Newlines, b: 1u); |
1532 | } |
1533 | // Remove empty lines at the start of nested blocks (lambdas/arrow functions) |
1534 | if (!PreviousLine && Line.Level > 0) |
1535 | Newlines = std::min(a: Newlines, b: 1u); |
1536 | if (Newlines == 0 && !RootToken.IsFirst) |
1537 | Newlines = 1; |
1538 | if (RootToken.IsFirst && |
1539 | (!Style.KeepEmptyLines.AtStartOfFile || !RootToken.HasUnescapedNewline)) { |
1540 | Newlines = 0; |
1541 | } |
1542 | |
1543 | // Remove empty lines after "{". |
1544 | if (!Style.KeepEmptyLines.AtStartOfBlock && PreviousLine && |
1545 | PreviousLine->Last->is(Kind: tok::l_brace) && |
1546 | !PreviousLine->startsWithNamespace() && |
1547 | !(PrevPrevLine && PrevPrevLine->startsWithNamespace() && |
1548 | PreviousLine->startsWith(Tokens: tok::l_brace)) && |
1549 | !startsExternCBlock(Line: *PreviousLine)) { |
1550 | Newlines = 1; |
1551 | } |
1552 | |
1553 | if (Style.WrapNamespaceBodyWithEmptyLines != FormatStyle::WNBWELS_Leave) { |
1554 | // Modify empty lines after TT_NamespaceLBrace. |
1555 | if (PreviousLine && PreviousLine->endsWith(Tokens: TT_NamespaceLBrace)) { |
1556 | if (Style.WrapNamespaceBodyWithEmptyLines == FormatStyle::WNBWELS_Never) |
1557 | Newlines = 1; |
1558 | else if (!Line.startsWithNamespace()) |
1559 | Newlines = std::max(a: Newlines, b: 2u); |
1560 | } |
1561 | // Modify empty lines before TT_NamespaceRBrace. |
1562 | if (Line.startsWith(Tokens: TT_NamespaceRBrace)) { |
1563 | if (Style.WrapNamespaceBodyWithEmptyLines == FormatStyle::WNBWELS_Never) |
1564 | Newlines = 1; |
1565 | else if (!PreviousLine->startsWith(Tokens: TT_NamespaceRBrace)) |
1566 | Newlines = std::max(a: Newlines, b: 2u); |
1567 | } |
1568 | } |
1569 | |
1570 | // Insert or remove empty line before access specifiers. |
1571 | if (PreviousLine && RootToken.isAccessSpecifier()) { |
1572 | switch (Style.EmptyLineBeforeAccessModifier) { |
1573 | case FormatStyle::ELBAMS_Never: |
1574 | if (Newlines > 1) |
1575 | Newlines = 1; |
1576 | break; |
1577 | case FormatStyle::ELBAMS_Leave: |
1578 | Newlines = std::max(a: RootToken.NewlinesBefore, b: 1u); |
1579 | break; |
1580 | case FormatStyle::ELBAMS_LogicalBlock: |
1581 | if (PreviousLine->Last->isOneOf(K1: tok::semi, K2: tok::r_brace) && Newlines <= 1) |
1582 | Newlines = 2; |
1583 | if (PreviousLine->First->isAccessSpecifier()) |
1584 | Newlines = 1; // Previous is an access modifier remove all new lines. |
1585 | break; |
1586 | case FormatStyle::ELBAMS_Always: { |
1587 | const FormatToken *previousToken; |
1588 | if (PreviousLine->Last->is(Kind: tok::comment)) |
1589 | previousToken = PreviousLine->Last->getPreviousNonComment(); |
1590 | else |
1591 | previousToken = PreviousLine->Last; |
1592 | if ((!previousToken || previousToken->isNot(Kind: tok::l_brace)) && |
1593 | Newlines <= 1) { |
1594 | Newlines = 2; |
1595 | } |
1596 | } break; |
1597 | } |
1598 | } |
1599 | |
1600 | // Insert or remove empty line after access specifiers. |
1601 | if (PreviousLine && PreviousLine->First->isAccessSpecifier() && |
1602 | (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline)) { |
1603 | // EmptyLineBeforeAccessModifier is handling the case when two access |
1604 | // modifiers follow each other. |
1605 | if (!RootToken.isAccessSpecifier()) { |
1606 | switch (Style.EmptyLineAfterAccessModifier) { |
1607 | case FormatStyle::ELAAMS_Never: |
1608 | Newlines = 1; |
1609 | break; |
1610 | case FormatStyle::ELAAMS_Leave: |
1611 | Newlines = std::max(a: Newlines, b: 1u); |
1612 | break; |
1613 | case FormatStyle::ELAAMS_Always: |
1614 | if (RootToken.is(Kind: tok::r_brace)) // Do not add at end of class. |
1615 | Newlines = 1u; |
1616 | else |
1617 | Newlines = std::max(a: Newlines, b: 2u); |
1618 | break; |
1619 | } |
1620 | } |
1621 | } |
1622 | |
1623 | return Newlines; |
1624 | } |
1625 | |
1626 | void UnwrappedLineFormatter::formatFirstToken( |
1627 | const AnnotatedLine &Line, const AnnotatedLine *PreviousLine, |
1628 | const AnnotatedLine *PrevPrevLine, |
1629 | const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent, |
1630 | unsigned NewlineIndent) { |
1631 | FormatToken &RootToken = *Line.First; |
1632 | if (RootToken.is(Kind: tok::eof)) { |
1633 | unsigned Newlines = std::min( |
1634 | a: RootToken.NewlinesBefore, |
1635 | b: Style.KeepEmptyLines.AtEndOfFile ? Style.MaxEmptyLinesToKeep + 1 : 1); |
1636 | unsigned TokenIndent = Newlines ? NewlineIndent : 0; |
1637 | Whitespaces->replaceWhitespace(Tok&: RootToken, Newlines, Spaces: TokenIndent, |
1638 | StartOfTokenColumn: TokenIndent); |
1639 | return; |
1640 | } |
1641 | |
1642 | if (RootToken.Newlines < 0) { |
1643 | RootToken.Newlines = |
1644 | computeNewlines(Line, PreviousLine, PrevPrevLine, Lines, Style); |
1645 | assert(RootToken.Newlines >= 0); |
1646 | } |
1647 | |
1648 | if (RootToken.Newlines > 0) |
1649 | Indent = NewlineIndent; |
1650 | |
1651 | // Preprocessor directives get indented before the hash only if specified. In |
1652 | // Javascript import statements are indented like normal statements. |
1653 | if (!Style.isJavaScript() && |
1654 | Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash && |
1655 | (Line.Type == LT_PreprocessorDirective || |
1656 | Line.Type == LT_ImportStatement)) { |
1657 | Indent = 0; |
1658 | } |
1659 | |
1660 | Whitespaces->replaceWhitespace(Tok&: RootToken, Newlines: RootToken.Newlines, Spaces: Indent, StartOfTokenColumn: Indent, |
1661 | /*IsAligned=*/false, |
1662 | InPPDirective: Line.InPPDirective && |
1663 | !RootToken.HasUnescapedNewline); |
1664 | } |
1665 | |
1666 | unsigned |
1667 | UnwrappedLineFormatter::getColumnLimit(bool InPPDirective, |
1668 | const AnnotatedLine *NextLine) const { |
1669 | // In preprocessor directives reserve two chars for trailing " \" if the |
1670 | // next line continues the preprocessor directive. |
1671 | bool ContinuesPPDirective = |
1672 | InPPDirective && |
1673 | // If there is no next line, this is likely a child line and the parent |
1674 | // continues the preprocessor directive. |
1675 | (!NextLine || |
1676 | (NextLine->InPPDirective && |
1677 | // If there is an unescaped newline between this line and the next, the |
1678 | // next line starts a new preprocessor directive. |
1679 | !NextLine->First->HasUnescapedNewline)); |
1680 | return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0); |
1681 | } |
1682 | |
1683 | } // namespace format |
1684 | } // namespace clang |
1685 | |